text:
Q: Gameplay screen recorder for Ubuntu? Are there any gameplay screen recorders out there for Ubuntu?
I intend to use it for Urban Terror recording.

A: The app that I use and love for game-play recording is SimpleScreenRecorder.

It's low on resource-use, and records video and sound, and as its name suggests it's very simple to use.
To install simpleScreenRecorder go to a terminal by pressing ctrl+alt+T and run these commands:
sudo add-apt-repository ppa:maarten-baert/simplescreenrecorder
sudo apt-get update
sudo apt-get install simplescreenrecorder

note if you want to record 32-bit OpenGL applications on a 64-bit system run this command too:
sudo apt-get install simplescreenrecorder-lib:i386

Note2 the openGL recorder is still experimental but runs very smoothly and with no problem.

A: Instead of searching for a gameplay recorder, you should search for a screen recorder. Here's a good one:
gkt-recordmydesktop -- audio and video capture
Related: How to record my screen?


text: Q: Opencart вывод товаров в opencart в админке задается количество товаров какие выводятся. Как сделать чтобы при одном расширении выводилось четное количество. А при другом нечетное. Чтобы при перестроении с col-md-4 на col-sm-6 не оставался лишний товар. на md выводится 15, а на переходе к sm чтобы 14 было. Спасибо

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails - Model Associations Question I have these models:
class Profile
  has_many :projects, :through => "teams"
  has_many :teams, :foreign_key => "member_id"
  has_many :own_projects, :class_name => "Project", :foreign_key => :profile_id
  has_many :own_teams, :through => :own_projects, :source => :teams
end

class Project
  belongs_to :profile, :class_name => "Profile"
  has_many :teams
  has_many :members, :class_name => "Profile", :through => "teams", :foreign_key => "member_id"
end

class Team
  belongs_to :member, :class_name => 'Profile'
  belongs_to :project
end

I want to create model Evaluation. It will need the ID of the Project Owner, the ID of a Member of this Project, and the ID of the Project. Explaining better, The Owner of the Project will Evaluate all his members, one by one. And the members will evaluate just the owner of the project. The table Evaluation will have a lot of attributes plus those Ids mentioned before.
My question is: How would my models be to make it function with evaluation, and how would be model evaluation itself? has_and_belongs_to_many or has_many :through?
Thanks.
Edited
Shot in the dark
class Evaluations < ActiveRecord::Base
  belongs_to :evaluated, :class_name => 'Profile', :foreign_key => "evaluated_id"
  belongs_to: :evaluator, :class_name => 'Profile', :foreign_key => "profile_id"
end

Guess I won't need the ID from Project...

A: *

*Project owner evaluates member performance for a project

*Members will evaluate the project owner for his performance on a project

*So, Evaluation has an evaluator, evaluee, a project, and other attributes

*We also need to know the types of the evaluee and evaluator

Create 2 evaluation classes one for EmployeeEvaluation, one for ManagerEvaluation.  Use Single table inheritance.
class Evaluation < ActiveRecord::Base
  attr_accessible :evaluator, :evaluee
  belongs_to :project
end

class EmployeeEvaluation < Evaluation #project manager evaluation of employee
  def evaluator
    Manager.find(self.evaluator)
  end

  def evaluee
    Employee.find(self.evaluee)
  end
end

class ManagerEvaluation < Evaluation
  def evaluator
    Employee.find(self.evaluator)
  end

  def evaluee
    Manager.find(self.evaluee)
  end
end


text:
Q: Image on a splash screen before Inno Setup installer does not display I am trying to create a splash screen for my installer in Inno Setup.
I create a form that is displayed for 2 seconds at the beginning of the installer, but the image is not displayed in it.
Only when I use the ShowModal function is it displayed, but it does not close after 2 seconds.
Here is my code:
[Code]
var
SplashForm: TSetupForm;
BIRegistry: TBitmapImage;

procedure SplashScreen;
begin
  SplashForm := CreateCustomForm;
  SplashForm.Position := poScreenCenter;
  SplashForm.BorderStyle := bsNone;
  BIRegistry := TBitmapImage.Create(SplashForm);
  BIRegistry.Bitmap.LoadFromFile(ExpandConstant('{tmp}\regtoexe.bmp'));
  BIRegistry.Parent := SplashForm;
  BIRegistry.AutoSize := True;
  SplashForm.ClientHeight := BIRegistry.Height;
  SplashForm.ClientWidth := BIRegistry.Width;
  SplashForm.Show;
  Sleep(2000);
  SplashForm.Close;
end;

procedure InitializeWizard;
begin
  ExtractTemporaryFile('regtoexe.bmp');

  SplashScreen;

What's wrong with this code?

A: That's because by calling Sleep you freeze Windows message pump, so the image cannot draw.

Quick and dirty solution is to force repaint before the Sleep:
SplashForm.Show;
SplashForm.Repaint;
Sleep(2000);
SplashForm.Close;

This is what Inno Setup Script Includes (ISSI) package was doing.

More correct way is to use the ShowModal and have the modal window close automatically after specified time:
var
  CloseSplashTimer: LongWord;

function SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc: LongWord): LongWord;
  external 'SetTimer@User32.dll stdcall';
function KillTimer(hWnd, nIDEvent: LongWord): LongWord;
  external 'KillTimer@User32.dll stdcall';

procedure CloseSplashProc(
  H: LongWord; Msg: LongWord; IdEvent: LongWord; Time: LongWord);
begin
  KillTimer(0, CloseSplashTimer);
  SplashForm.Close;
end;

procedure SplashScreen;
begin
  SplashForm := CreateCustomForm;
  // rest of your splash window setup code

  CloseSplashTimer := SetTimer(0, 0, 2000, CreateCallback(@CloseSplashProc));
  SplashForm.ShowModal;
end;

Based on: MsgBox - Make unclickable OK Button and change to countdown - Inno Setup


text:
Q: Adapting the Command Pattern to a singleton that makes multiple API connections A teammate wrote a connector to a service that instantiates an API connection and proceeds to use that same connection throughout the code. It turns out that the way these connectors are created, they're actually singletons. So as soon as more than one connection is needed, we'll have a lot of trouble on our hands. I was about to just rewrite the connector, but another teammate said something about how this was a good place to use the Command pattern.
Unfortunately, the only examples I can find online are ones where the Commands in question relate to undoing things, or menus. In this context, what sort of functionality do things like Invoker, Receiver, Command, etc map onto?
Pattern Term    My domain
Invoker      -> Connection instance
Receiver     -> ?
Command(s)   -> GetSomeData(userInfo, creds, constraints), GetSomeOtherData(userInfo, creds, constraints), ...
User         -> Connector singleton?
Invoker      -> Also Connector singleton?

I was going to just move the API Connection object into its own class, rather than being a property on the Connector singleton, and then new up that Connection object with the proper creds and pass it along to each GetSomeData method. Am I wrong in finding the command pattern stuff to be a little bit overkill-y?
Sorry for the somewhat disjointed question, it boils down to: what command pattern concept maps onto which of my current concerns, and what are the benefits of doing it that way?

A: To me your teammate seems to have misunderstood something.
Using Command pattern would not really help you other than creating a queue of ''task/data`` to send threw the connection. Undo is no use in that case, but you could actually serialized/saved each command with the Memento Pattern and create a log of every command sent threw the connection.
I think your partner, miss the point on which multiple connections will be concurrent if your server is able to sustain concurrent calls.
So either you partner missed something, either your server does not handle concurrency.
Command pattern will in your case only be used to create a log book and with memento store/restore command that have failed/succeeded


text:
Q: how to run a shell scripts at every login in Centos Actually i want to run my shell script at every time when a user login as well as at boot. i have tried using using crontab but it runs only at boot not at every login.so please tell  me how to do this.
#crontab -e
@reboot  /home/user/test.sh

A: You can add your script in ~/.bash_profile where ~ represents the homedir of the user for which running the script is intended.


text:
Q: When scraping data from website and writing to a csv file, only the last row was written to the file I am using python and beautiful soup to extract data from a web page and it works. The problem is that its not inserting all the values to the csv file. Like if I extract 10 data values than only the 10th data value goes to csv file, the 9th one doesn't. All 10 data values show up on the terminal but not in csv file.
import libraries
import csv

import urllib.request
from bs4 import BeautifulSoup

# specify the url
quote_page = "https://www.cardekho.com/Hyundai/Gurgaon/cardealers"
#quote_page = input("Enter Data Source Here : ")
page = urllib.request.urlopen(quote_page)

# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, "lxml")

# Take out the <div> of name and get its value
delrname = soup.find_all('div', class_='deleadres')
for name in delrname:
    dname = name.find('div', class_="delrname").text # name
    print(dname)
for address in delrname:
    dadres = address.find('p').text
    print(dadres)
for mobile in delrname:
    dmobile = mobile.find('div', class_="clearfix").text
    print(dmobile)
for email in delrname:
    demail = email.find('div', class_="mobno").text
    print(demail)

#exorting data into csv file....
with open('result.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('result.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['NAME','ADDRES','MOBILE','EMAIL'])
    w.writerow([dname,dadres,dmobile,demail])**strong text**

A: When you assign values in a for-loop, you replace the former value. So outside the loop, you will be left with the final value.
for number in 1, 2, 3:
    print(number) # prints 1, then 2, then 3
print(number) # prints only 3, since that was the final value.

In your script, use a single for-loop to both extract values and write data rows to the csv.
with open('result.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['NAME','ADDRES','MOBILE','EMAIL']) # write header once
    entries = soup.find_all('div', class_='deleadres')
    for entry in entries: # loop over all `.deleadres` elements
        dname = entry.find('div', class_="delrname").text
        dadres = entry.find('p').text
        dmobile = entry.find('div', class_="clearfix").text
        demail = entry.find('div', class_="mobno").text
        w.writerow([dname,dadres,dmobile,demail]) # write data rows for each entry

A: Your mistake is that you are only saving the last value from the loop, hence you are not getting all the values.
Another way to do it:
1) Add your values from the loop to the list
2) Add values from the list to the CSV
page = urllib.request.urlopen(quote_page)
# CREATE NEW LISTS
dname_list = list()
dadres_list = list()
dmobile_list = list()
demail_list = list()

# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, "lxml")

# APPEND TO THE LIST
# Take out the <div> of name and get its value
delrname = soup.find_all('div', class_='deleadres')
for name in delrname:
    dname = name.find('div', class_="delrname").text # name
    print(dname)
    dname_list.append(dname)
for address in delrname:
    dadres = address.find('p').text
    print(dadres)
    dadres_list.append(dadres)
for mobile in delrname:
    dmobile = mobile.find('div', class_="clearfix").text
    print(dmobile)
    dmobile_list.append(dmobile)
for email in delrname:
    demail = email.find('div', class_="mobno").text
    print(demail)
    demail_list.append(demail)

#exorting data into csv file....
with open('result.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('result.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['NAME','ADDRES','MOBILE','EMAIL'])
    # TRAVERSE THROUGH THE LIST
    for i in range(len(dname)):
        try:
            w.writerow([dname_list[i],dadres_list[i],dmobile_list[i],demail_list[i]])
        except IndexError:
            print('')

PS: Haken's answer is a better way of doing it. I just thought of letting you know another way to do it.


text:
Q: Use copy of outside variable inside closure I'm trying to use Cairo with Rust and came to a problem where I can't find a good solution for:
let (width, height) = (400., 300.);

let window = gtk::ApplicationWindow::new(application);
window.set_default_size(width as i32, height as i32);

let drawing_area = Box::new(DrawingArea::new)();

drawing_area.connect_draw(|_, cr| {
    cr.scale(width, height);
    ...
    });

I assumed I could use width and height directly inside the closure since those are primitive types that are copied by default. Yet the compiler complains:
   |     drawing_area.connect_draw(|_, cr| {
   |                               ^^^^^^^ may outlive borrowed value `width`

I couldn't find a good solution for this issue in the Rust documentation, what is the best way to use outside variables inside a closure?
I can't change the signature of the closure since connect_draw expects exactly two input parameters.


text:
Q: How do you test a class with an extended module in ruby with spec I can never find a clear answer for this use case, I apologize if this is a duplicate. In the following example, Is there a clean way to test with rspec that the method in class B gets called?
module A
  def demo_method
    puts 1
  end
end

class B
  extend A
  demo_method
end

A: At first revise your method name method into demo_method as that name is sensitive.
Then
B.should respond_to :demo_method
# => true

A: If you really really need to know that class B is calling a method, you can use the caller method.  It will show you the stack.
You will get this type of stack output:
$: ruby
how-do-you-test-a-class-with-an-extended-module-in-ruby-with-spec.rb
how-do-you-test-a-class-with-an-extended-module-in-ruby-with-spec.rb:10:in
`<class:B>'
how-do-you-test-a-class-with-an-extended-module-in-ruby-with-spec.rb:8:in `<main>' 1
how-do-you-test-a-class-with-an-extended-module-in-ruby-with-spec.rb:14:in
`<main>' 1

You just need to output the caller
module A
  def demo_method
    puts caller
    puts 1
  end
end

class B
  extend A
  demo_method
end

puts B::demo_method

This information may be better served as morsel in logs at debug level, rather than on the screen.  But I hope that helps.


text:
Q: Using Azure as storage for Windows Phone 7 apps I am trying to figure out why I should use Azure. At the moment, I am using a generic web hosting provider to store my users accounts and data. It works pretty ok for me. I am a very small hobbyist so Azure may not be something for me(?). Anyhow, I now have a problem - I am wondering if Azure might be able to help me with. For my apps and sites, I usually have some kind of user account and data storage. For a new WP7-app, I am making I want to store the data online so I can access and modify it from my web site as well. Now I would like to remove the requirement for the user to create another new account for this little app. I realized that the user of the phone already must have a live-account (because its a requirement for using WP7). Could I use this somehow in combination with Azure to store the data specific to every user and then also access it from my web site?

A: This question is really less about Windows Azure, but more about authentication (and SSO)
Here are a couple options for using existing authentication credentials with WP7 and WIndows Azure (or any other hosting environment). Including LiveID, Facebook, Google, Yahoo!, etc.
Here's a quick description of some:
http://blogs.msdn.com/b/eugeniop/archive/2011/03/24/authentication-in-wp7-client-with-rest-services-part-i.aspx
http://blogs.msdn.com/b/eugeniop/archive/2011/04/02/authentication-in-wp7-client-with-rest-services-part-ii.aspx
(also discussed here: How should I handle user identity for a Window Phone / WCF / ASP.NET MVC application?)

A: Yes, Azure can help you with that.
Have a look at this link:
http://www.techrepublic.com/blog/10things/10-reasons-to-use-azure-for-your-cloud-apps/1282


text:
Q: component is not receiving @Input() variable I'm trying to create an inline input edit component.
It's being loaded correctly, but it looks like that @Input() variables are always undefined.
mypage.html
...
<app-inputinline
            [name]="username"
            [fieldValue]="myname"
            [isRequired]="true"
            (updateValue)="saveField('username', $event)"></app-inputinline>
...

inputinline.component.ts
    import { Component, OnInit } from '@angular/core';
    import { Input, EventEmitter, Output, ViewChild, Renderer } from '@angular/core';

    @Component({
      selector: 'app-inputinline',
      templateUrl: './inputinline.component.html',
      styleUrls: ['./inputinline.component.scss'],
    })
    export class InputinlineComponent implements OnInit {

      @Input() name:string;
      @Input() fieldValue:string;
      @Input() isRequired:string;
      @Input() minLength:string;
      @Input() maxLength:string;

      @Output() updateValue: EventEmitter<any> = new EventEmitter();

      @ViewChild('container') container;

      public value:any;
      public isEditView:boolean = false;
      public docEditUnlisten:any;

      constructor(
                  private renderer:Renderer
                  ) { }

      ngOnInit(){
        console.log(this.fieldValue);      <============ THIS SHOWS UNDEFINED
      }

      showEditable()
      {
        this.value = this.fieldValue;
        this.isEditView = true;

        this.docEditUnlisten = this.renderer.listenGlobal('document', 'click', (event) => {
          if(!this.container.nativeElement.contains(event.target)){
            this.showDetail();
          }
        });
      }

      save(){
        this.updateValue.emit(this.value);
      }

      showDetail(){
        this.isEditView = false;
      }

    }

inputinline.component.module.ts
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { CommonModule } from '@angular/common';
    import { IonicModule } from '@ionic/angular';

    import { InputinlineComponent } from './inputinline.component';

    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
      ],
      declarations: [
        InputinlineComponent
      ],
      exports: [
        InputinlineComponent
      ],
      entryComponents: [
      ],
    })
    export class InputinlineComponentModule {
    }

inputinline.component.html
    ...
    <span class="editable-click">
      => {{fieldValue}}
      <div #container class="editable-container editable-inline">
      ...

As you can see I'm trying to display => {{fieldValue}}, but its empty and also in component ngOnInit it shows undefined.
Am I doing something wrong?

A: Bind to a string instead of the variable myname (which would exist in mypage.ts)
<app-inputinline
            [name]="username"
            [fieldValue]="'myname'"
            [isRequired]="true"
            (updateValue)="saveField('username', $event)"></app-inputinline>


text:
Q: JTable cell value change listener Which listener can be used to react to the event of JTable cell value change? I tried using TableModelListener but either I got something wrong, or this listener doesn't react on changing the contents of a cell.
I need to act either to changing the content of a cell or to cell losing focus. What is the best way to do this? Thanks.

A: class extends JTable {

....
(inside contructor)
addPropertyChangeListener(new PropertyChangeListener() {

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if ("tableCellEditor".equals(evt.getPropertyName())) {
            if (isEditing())
                processEditingStarted();
            else
                processEditingStopped();
        }
    }
});

... (end constructor)
protected void processEditingStopped() {
    System.out.println("save " + editingRow + ":" + editingColumn);
}

protected void processEditingStarted() {
    System.out.println("edit " + editingRow + ":" + editingColumn);
    if (editRow > -1 && editColumn > -1)
        oldValue = (String) model.getValueAt(editRow, editColumn);
}

}
more details here: http://tips4java.wordpress.com/2009/06/07/table-cell-listener/

A: Easy way to react to values changing is to customize a table model and react to setValueAt().
If you're looking to make sure edits "stick" when it loses focus, call this on the table.
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

A: As mentioned by Bill, it maybe easier to "watch" the model rather than the JTable, I used this and was able to track changes by column and row:
list.getModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                System.out.println("Column: " + e.getColumn() + " Row: " + e.getFirstRow());
            }
        });

As mentioned in my comment to their answer, it doesn't detect if a change occured only that the cell was edited. So you'll need to check against the original value somehow. But this saved me messing with my JTable constructor.


text:
Q: How to pass Parcelable object from child to parent activity? I'm building a small app that requiere authentication. In my main activity I have a Parcelable class named "user" that contains the username and password of an user, when a user click on a button it starts a new activity passing that user class. It works like a charm, in the child activity the user fill the form to authenticate, then when user press the back button, I would like to send the "user" class back to my main activity.
Is it possible to do that ??

A: Start your child activity with:
startActivityForResult(startIntent, 1);

In your child activity, intercept the back button and append your data:
@Override
public void onBackPressed() {
    Intent data = new Intent();
    data.putExtra("key", yourDataHere);
    setResult(Activity.RESULT_OK, data);
    super.onBackPressed();
}

And get data inside parent activity inside onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == 1 && resultCode == Activity.RESULT_OK){
        DataType yourData = (DataType) data.getParcelableExtra("key");
        //Do whatever you want with yourData
    }
}


text:
Q: Intel C++ compiler bug? (pointers aliasing) I am using Intel C++ compiler 12.0, and working on a program similar to the following, which is very simple and straightforward. The while loop should stop in the first run. However, when I build the code using /O2 flag with the Intel compiler, the while loop never stops. If I disable the optimization, or use visual C++, the loop exits normally. If I change pt->flag to p.flag, which I suppose is the same thing, the loop exits normally too. I think it has something to do with Intel's optimization. Is this a bug in the Intel compiler? or I missed something here?
#include <iostream>

using namespace std;

struct para {
    int i;
    int flag;
};

int main(int argc, char **argv)
{
    para p;
    p.i = 0;
    p.flag = 1;

    para * pt = &p;
    cout << "loop started" << endl;

    int i;
    while (p.flag) {
        if (p.i == 0) {
            for (i=0; i<1; i++) {
                if (p.flag != 1)
                    break;
            }
            if (i==1) {
                pt->flag = 0;
            }
        }
    }
    cout << "loop stopped" << endl;
    return 1;
}

Updates:
Thanks for everybody's answer. I am confused by the explanation of "pointer aliasing". If p is in the registers and pt can't access it, why the following code will break the while loop with the intel compiler? Firstly "pt->flag = 0;" should never take effect because i=0. Secondly even if it's in effect, shouldn't "pointer aliasing" prevent p being modified?
BTW: Can anybody let me know how to turn on/off the pointer aliasing in Visual Studio with intel compiler? Thanks!
#include <iostream>
using namespace std;
struct para {
    int i;
    int flag;
};

int main(int argc, char **argv)
{
    para p;
    p.i = 0;
    p.flag = 1;

    para * pt = &p;
    cout << "loop started" << endl;

    int i=0;
    while (p.flag) {
        if (p.i == 0) {
            //for (i=0; i<1; i++) {
            //  if (p.flag != 1)
            //      break;
            //}
            if (i==1) {
                pt->flag = 0;
            }
        }
    }
    cout << "loop stopped" << endl;
    return 1;
}

A: This is a situation known as pointer aliasing. You have a variable p and a pointer pt that points to the same thing as p. Many optimisations can be used if the compiler can assume that there is only one "name" for a given variable, and /O2 for your compiler may enable this assumption. For example, the compiler could keep all the member variables for p in registers during the loop, which obviously can't be accessed through a memory pointer.
Check your compiler documentation to find out how to tell it to not assume there are no pointer aliases. This could be a compiler switch or a #pragma.


text:
Q: Query value of JoinColumn with JPQL I have two JPA entities
public class Job {
  @ManyToOne
  @JoinColumn(name = "service")
  public Service service;

  @Column(name = "queue_time")
  public Long queueTime;

  @Column(name = "run_time")
  public Long runTime;
}

public class Service {
  @Id
  @Column(name = "id")
  public Long id;

  @Column(name = "name")
  public String name;

  @Column(name = "host")
  public String host;
}

Now I want to do some aggregation queries with JPQL:
SELECT job.service.id, AVG(job.queueTime), AVG(job.runTime) FROM Job job GROUP BY job.service.id

The resulting SQL query (I'm using a MySQL database) looks like this:
SELECT t0.id, AVG(t1.queueTime), AVG(t1.runTime) FROM Service t0, Job t1 WHERE (t0.service = t1.id) GROUP BY t0.id

As you can see, JPA translates my JPQL query to a SQL query with a join. This however slows down the query dramatically. The following SQL query executes ~6 time faster and returns the exact same result set:
SELECT t1.service, AVG(t1.queueTime), AVG(t1.runTime) FROM Job t1 GROUP BY t1.service

If I change the JPQL query to
SELECT job.service, AVG(job.queueTime), AVG(job.runTime) FROM Job job GROUP BY job.service

the resulting SQL query looks like this:
SELECT t0.id, t0.name, t0.host AVG(t1.queueTime), AVG(t1.runTime) FROM Service t0, Job t1 WHERE (t0.service = t1.id) GROUP BY t0.id, t0.name, t0.host

Is there a way to write the JPQL which only queries the job table without making a join to the service table?

A: This question solved the issue for me: How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?
I took the second solution (b) Use read-only fields for the FKs)


text:
Q: Highcharts with datatable There is an example for highcharts:
http://jsfiddle.net/highcharts/z9zXM/
However I couldn't reverse x axis and y axis at table. I mean I want it like:
Tokyo       Jan Feb ..
New York
Berlin
London

Also I want to locate that table at middle under chart.
Any ideas?

A: This is how the loops should be:
// draw category labels
$.each(series, function(serie_index, serie) {
    renderer.text(
        serie.name,
        cellLeft + cellPadding,
        tableTop + (serie_index + 2) * rowHeight - cellPadding
    )
    .css({
        fontWeight: 'bold'
    })
    .add();
});

$.each(chart.xAxis[0].categories, function(category_index, category) {
    cellLeft += colWidth;

    // Apply the cell text
    renderer.text(
            category,
            cellLeft - cellPadding + colWidth,
            tableTop + rowHeight - cellPadding
        )
        .attr({
            align: 'right'
        })
        .css({
            fontWeight: 'bold'
        })
        .add();

    $.each(series, function(i) {

        renderer.text(
                Highcharts.numberFormat(series[i].data[category_index].y, valueDecimals) + valueSuffix,
                cellLeft + colWidth - cellPadding,
                tableTop + (i + 2) * rowHeight - cellPadding
            )
            .attr({
                align: 'right'
            })
            .add();

    });

});

Here is the link: http://jsfiddle.net/pJ3qL/1/
Then you should draw the table borders inside the loops again if you want ;)


text:
Q: BitmapImage exception Here is my XAML code:
<Image Stretch="Fill" Margin="15,0,0,0" ToolTip="{Binding ImagePath}" Width="110" Height="100" >
  <Image.Source>
   <BitmapImage RenderOptions.BitmapScalingMode="LowQuality" CacheOption="OnLoad" DecodePixelWidth="200" CreateOptions="IgnoreColorProfile" UriSource="{Binding ImagePath ,FallbackValue={StaticResource Lost},TargetNullValue={StaticResource Lost}}"/>
  </Image.Source>
</Image>

This is giving me this error:

An unhandled exception of type
  'System.Windows.Markup.XamlParseException' occurred in
  PresentationFramework.dll
Additional information: Initialization of
  'System.Windows.Media.Imaging.BitmapImage' threw an exception.

Some times UriSource get null or invalid path that time i want to display default image

A: BitmapImage throws an initialization exception when file does not exist
This answer worked for me, for the same problem you were having. I was able to return the image I wanted using a converter if the image file was missing.


text:
Q: How to fill min value in sql and php? I have a table in SQL:
Table 1
date       name  s1   s2   s3   s4   min_value
7/10/2017  ram   10   11   12   13   11
7/10/2017  tom   17   16   15   14   16
7/10/2017  ara   13   9    26   22   9

If I total all fields in a single date then
s1 total value 40
s2 total value 36
s3 total value 53
s4 total value 49

Here minimum value is 36. It means minimum value column is s2.
I inserted s2 field value in min_value field respectively.
My question is how will I fill min_value field?
Help me please.
Thanks in advance.

A: Here's code to achieve that:
SELECT [date], s1, s2, s3, s4,
    case when s1 < s2 and s1 < s3 and s1 < s4 then s1
         when s2 < s1 and s2 < s3 and s2 < s4 then s2
         when s3 < s1 and s3 < s2 and s3 < s4 then s3
         else s4 end as [min_value]
FROM (
    SELECT [date], sum(s1) AS s1, sum(s2) AS s2, sum(s3) AS s3, sum(s4) AS s4 FROM [Table1]
    GROUP BY [date]
) AS A


text:
Q: Does 'And' vs 'AndAlso' matter with linq in vb.net? Does it matter if you are using 'And' or 'AndAlso' in linq queries in vb.net?  I know in normal operations 'AndAlso' is short circuit and so will often be faster, but I don't know if that carries over into linq queries.  Does it matter if the linq query is against a database or against an in memory collection?

A: For LINQ to object queries, it would definitely matter. For other LINQ providers, it depends on the provider itself. At the expression tree level, they are different but the provider might choose to translate/run it the same way. For instance, there's no equivalent notion in SQL so LINQ to SQL translates them to identical SQL.

A: Whether or not to use And vs. AndAlso is very dependent on the context of the usage.  However it's almost always preferable to use AndAlso over And.
The short circuit quality of AndAlso will carry over to LINQ queries


text:
Q: Python ImportError $ bin/python src/app/utils/loader.py newTasks checkForStuff
Traceback (most recent call last):
  File "bin/python", line 135, in <module>
    execfile(__file__)
  File "src/app/utils/loader.py", line 154, in <module>
    module = __import__(args.module)
ImportError: No module named newTasks

from the following loader.py:
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Runs python')
    parser.add_argument('module', metavar='module', help="the target module")
    args = parser.parse_args()
    module = __import__(args.module)

newTasks.py is in the same directory as loader.py. It works on my dev box, I did an svn export to staging and the above happened. Any pointers?
Only material difference I can work out is this time I'm running out of virtualenv.
EDIT:
I changed the command line to:
$ bin/python src/app/utils/loader.py utils.newTasks checkForStuff

and the module was found ok. But my next command is to call one of the module functions checkForStuff:
parser.add_argument('func',metavar='function', help="the target function name")
...
func_param = getattr(module,args.func)

and now it cannot find the function?
Traceback (most recent call last):
  File "bin/python", line 135, in <module>
    execfile(__file__)
  File "src/app/utils/loader.py", line 156, in <module>
    func_param = getattr(module,args.func)
AttributeError: 'module' object has no attribute 'checkForStuff'

If I go into bin/python:
>>> import utils.newTasks as nt
>>> nt.checkForStuff
<function checkForStuff at 0x29b2f50>

This is annoying!

A: bin/python is not the python binary on your staging machine. Check whether it inserts the scripts directory into sys.path as ordinary python does.


text:
Q: Are you running Win 7 on a Intel Pentium 4 Motherboard Is anyone running Win 7 on an Intel P4 MB with the monitor attached to the MB connector ?  If so, what VGA driver are you using? Does Win7 allow 800x600 and higher screen resolutions ?

Attempting to upgrade to Win7 from XP Pro screen coloration problems at 800x600 - the only allowed resolution
No issues under XP Pro SP3, on a different HDD and the Monitor ( HP vx74 ) performed as expected.
A screen capture is shown at n2006b.com/Res

*

*Intel D845GERG2L a 2003 MB A97835-106

*Onboard Video Chipset: Intel Extreme Graphics

*Monitor HP vx74 using Microsoft Driver 6.1.7600.16385 which Win7 says is up to date

A: The main issue here is that Intel never provided WDDM 1.1 (Win 7) drivers for old hardware like your 845G chipset's GPU (i.e., Intel Extreme Graphics).
You may try to download & extract the following drivers, go to the device manager and action menu 'Add legacy hardware', then manually point to the .inf file of the intel driver.
https://downloadcenter.intel.com/download/8344
Otherwise, you will have trouble running it, and getting a cheap/not too old AGP GPU  (since you have not PCIe port on your MB) may help.


text:
Q: PHP and MYSQL game timer comparison I am truely sorry if this question is already answered. If so, please redirect me to the correct thread or website. I didn't manage to find the question and answer i am looking for.
So here is my question. I am thinking about building a browser game and i am fairly known with PHP and MySQL. But my only trouble (for now) is with timers.
What i want to do:
User presses a button on a web page to (lets say) level up a building or whatever.
The level up progress takes 2 hours. I did manage to get the current time in PHP and i think i can manage to add two hours to that time. So i can store it in the database.
But my questions are:

*

*How do i format the PHP date and time to be suitable for MySQL? (i've seen alot about strtotime() and methods like that, but i cant seem to get the hang of it because it doesnt really solve my problem)

*What type of column should i use? There are many types, like datetime, timestamp etc..

*On page refresh i want to fetch the timestamp from the database and compare it with the current time. So i can see if it already expired or not. If not i display how many days, hours, minutes or seconds are left. (I dont need code for a real count down timer, that is stuff for when i am really going to code).

This is also going to be used for things like resources and attacks.
But first i want to know if this is even possible in the way i am thinking.
If not or if there is a better way, like doing it in ruby, python or any other language i would love to know what and where is should look into. I am willing to learn other languages to do this.
Now i dont really need (if it's done, i would dearly appreciate it ofcourse) any of you to write it for me. Information on what and where to look would already be much appreciated.
Any help would be much appreciated!
Cheers,
Clemenz

A: I use DateTime class to format date most of the time.
$date = new DateTime('NOW'); //'NOW' could be datetime from database
$formattedDate = $date->format("M j, Y, g:i A");

And you can get the difference between the time using:
$d1=new DateTime("2012-07-09 11:14:15");
$d2=new DateTime("2012-07-08 11:14:15");
$diff=$d2->diff($d1);
print_r( $diff ) ;

Reference for class DateTime: http://php.net/manual/en/class.datetime.php
You can use the columns in the database as said by @DaveChen


text:
Q: Calculating hyperbolic distance between two points I was looking for a formula to calculate the hyperbolic distance between two planes and came across this formula
$$\ln\left(\csc b-\cot b\over \csc a - \cot a\right)$$ where $a$ and $b$ are the angles from the positive real axis, with $b$ being the larger angle.
I wanted to confirm if there was another way of finding the hyperbolic distance or if this was it.


text:
Q: Is there any sound enhancer software for Linux? One of my biggest attachments to Windows is DFX Audio Enhancer because it enhances audio from all applications before reaching my speakers (Restore quality, ambiance/surround simulation, etc.). Is there any similar software/configuration for Linux?
SRS HD Audio Lab (Formerly SRS Audio Sandbox) is kind of the same thing (In case you don't know DFX).
Any guidance would be much appreciated, thanks in advance.
[Sorry for my bad english]

A: If you're using PulseAudio then it's possible to use the module-pipe-* modules to feed the audio data through a SoX executable that has been passed appropriate parameters. Note that this will add a small amount of latency to the audio though, with the specific amount dependent on the SoX parameters.


text:
Q: Replace a substring contained between two substring in javascript I have this string
'bookmarkState={"params":{"date_from":"2014-07-31","date_to":"2014-10-01"}}'
I want to replace 2014-07-31 with 2014-01-01, i.e. the substring contained between '"date_from":"' and '","', using a regular expression in javascript. I have written this code but it doesn't work:
var qs = 'bookmarkState={"params":{"date_from":"2014-07-31","date_to":"2014-10-01"}};'
var regEx = /^(.*?date_from":")[^"]*(".*)$/;
qs = qs.replace(regEx, '2014-01-01');`

A: You don't need a regex to do that:
eval('bookmarkState={"params":{"date_from":"2014-07-31","date_to":"2014-10-01"}}');

bookmarkState.params.date_from = '1988-04-12';

console.log(JSON.stringify(bookmarkState));

A: ^(.*?date_from":")[^"]*(",".*)$

Try this.Replace by $1<your string>$2.See demo.
http://regex101.com/r/qZ0uP0/1


text:
Q: Worst-case time complexity of Python's int.bit_length() When we call the function int.bit_length passing an integer n,
is the worst-case time complexity O(log(n)) or Python uses some trick to improve it (e.g. storing the position of the most significant bit of n when it is created)?

A: In CPython, for values with fewer internal-representation digits than PY_SSIZE_T_MAX/PyLong_SHIFT – i.e. fewer than PY_SSIZE_T_MAX binary digits – it's calculated from the number of internal digits, yes:
msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
msd_bits = bits_in_digit(msd);

if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
    return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);

Otherwise, it goes through bigints again, for overall time complexity of O(log log N) (which isn't exactly true either in this strange mix of practice and theory, so…).
/* expression above may overflow; use Python integers instead */
result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
if (result == NULL)
    return NULL;
x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
if (x == NULL)
    goto error;
y = (PyLongObject *)long_mul(result, x);
Py_DECREF(x);
if (y == NULL)
    goto error;
Py_DECREF(result);
result = y;

x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
if (x == NULL)
    goto error;
y = (PyLongObject *)long_add(result, x);
Py_DECREF(x);
if (y == NULL)
    goto error;
Py_DECREF(result);
result = y;

return (PyObject *)result;

tl;dr: it's O(1)


text:
Q: No module named keras I have successfully installed keras after much struggle in the directory /usr/local/lib/python3.5/dist-packages(by deafult it has been installed there). But whenever i am trying to import or trying to modify the keras backend it says No mudule named keras. What am I doing wrong here and how will I modify the keras.json file in these current conditions?

A: you should be able to edit keras.json directly. it should be at ~/.keras/keras.json .
also it seems you installed keras for python3 but are trying to use it with python(2).
try using pip instead of pip3 (or python3 instead of python). :)
see details here.

A:
What am I doing wrong here?

The problem is that you start Python 2, but you installed it for Python 3. Your system has likely both Python versions, but you installed it only for one.
If you want to start Python 3, try python3:
python3 -c "from keras import backend; print(backend._BACKEND)"

How do I modify the keras.json file?

Open ~/.keras/keras.json with the editor of your choice. For example:
nano ~/.keras/keras.json


text:
Q: How can I route 401 and 403 errors? I have this in my startup:
app.UseMvc(routes =>
{
routes.MapRoute(
    "404-PageNotFound",
    "{*url}",
    new { controller = "Home", action = "Error" }
    );
});

It redirects 404 errors to the Error page as expected.  How can I do this with a 401 and/or 403 error? I have tried this:
app.UseMvc(routes =>
{
    routes.MapRoute(
        "401",
        "{*url}",
        new { controller = "Home", action = "Error" }
        );
});

I have spent hours Googling this today and have found nothing.  Some other answers talk about creating handlers like this: Override AuthorizeAttribute in ASP.Net Core and respond Json status.  However, I believe it is an overkill for me.
How can I route 401 or 403 errors?
If it makes any difference; it is a Web API .NET Core 2.1 returning the 401 / 403 error and an MVC Core MVC 2.1 app handling the error.

A: Configure status code pages
By default, an app doesn't provide a rich status code page for HTTP status codes, such as 404 Not Found. To provide status code pages, use Status Code Pages Middleware.
The middleware is made available by the Microsoft.AspNetCore.Diagnostics package, which is available in the Microsoft.AspNetCore.App metapackage.
Add a line to the Startup.Configure method:

app.UseStatusCodePages(async context =>
{
    context.HttpContext.Response.ContentType = "text/plain";

    await context.HttpContext.Response.WriteAsync(
        "Status code page, status code: " +
        context.HttpContext.Response.StatusCode);
});

Link here for the related documentation


text:
Q: Git and Android Studio nightmare Version Control Yes i'm new in git, but as far as i can see it's a pain.
Assuming that:

*

*I'm working on Windows 7 64 bit

*Git perfectly installed

*Using an Assembla repo which i'm currently using with Eclipse and SVN

*I'm now developing with the absolute latest version of Android Studio (updated just 2 days ago...)

I want to ask here, if is my lack of expertise, or it's simply inferior to SVN (which also gives me a bunch of problems in Android Studio, when in Eclipse i can work like a charm!).
This is what i've done:
- made a project and decide to add to Version Control
- went in project dir and get Bash console.
- "git init" and there aren't all the files under git control because of this ignore list (why and how git decides alone that there are things to ignore here, is a mistery, if someone could explain that would be awesome.)
- Deleted ".ignoregit" file list and give a "git add ."
- now it seems everything's under VC but if when i drilled down in project tree i've found for example "build" folder not checked with git sign icon.
Tried every command like "add -f" and "add *"  and such, no way.
Sometimes it seems fooling me around adding something that wasn't added before, but remove something else from the list of versione files!
Really really inexplicable.
Thanks

A: If you're going to use git I recommend you go through this quick tutorial http://www.gitimmersion.com.  It takes about 2 hours all-in, but you'll have a strong foundation in git when you're done.

A: *

*
why and how git decides alone that there are things to ignore here

The gitignore files are not created by git but I asume by Android studio and they do make sense. You can still decide to delete them.

*You probably have 2 gitignore files, one in the project folder, one in the app module folder.
After deleting them both, all files should be added.


text:
Q: How to make div with left side text and right side Image Bootstrap 4 Here is Image in this image you will found left side some text like name, address and right side image of that person. So please tell me how i will make this with bootstrap 4

A: You can use bootstrap-4 card and col-sm-6 to each part
See here:https://jsfiddle.net/9k8w1fpq/4/
Learn about card:https://www.w3schools.com/bootstrap4/bootstrap_cards.asp

img{
width:100px;
height:100%;}
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

John Doe

Some example text some example text. John Doe is an architect and engineer

      See Profile


text:
Q: BLE subscribe to notification using gatttool or bluepy I am writing a program using bluepy that listen for a characteristic sent by a bluetooth device. I can also use any library or language, the only constraint is to run on Linux and not in mobile environment (it seems is widely used only in mobile devices, no one use BLE with desktop).
Using bluepy I register the delegate and after trying to register for notification calling write('\x01\x00') as described in the bluetooth rfc.
But it doesn't work, any notification for the characteristic is received.
Maybe I am wrong in writing the message for subscribing.
Is there an error in the small snippet I wrote? Thank you so much.
class MyDelegate(btle.DefaultDelegate):

    def __init__(self, hndl):
        btle.DefaultDelegate.__init__(self)
   self.hndl=hndl;

   def handleNotification(self, cHandle, data):
   if (cHandle==self.hndl):
            val = binascii.b2a_hex(data)
            val = binascii.unhexlify(val)
            val = struct.unpack('f', val)[0]
            print str(val) + " deg C"

p = btle.Peripheral("xx:xx:xx:xx", "random")

try:
   srvs = (p.getServices());
   chs=srvs[2].getCharacteristics();
   ch=chs[1];
   print(str(ch)+str(ch.propertiesToString()));
   p.setDelegate(MyDelegate(ch.getHandle()));
   # Setup to turn notifications on, e.g.
   ch.write("\x01\x00");

   # Main loop --------
   while True:
      if p.waitForNotifications(1.0):
      continue

      print "Waiting..."
finally:
    p.disconnect();

A: I was struggling with this myself, and jgrant's comment really helped. I'd like to share my solution, if it could help anyone.
Note that I needed indication, hence the x02 rather than x01.
If it were possible to read the descriptors using bluepy, I would do that, but it doesn't seem to work (bluepy v 1.0.5). The method in the service class appears to be missing, and the method in the peripheral class gets stuck when I try to use it.
from bluepy import btle

class MyDelegate(btle.DefaultDelegate):
    def __init__(self):
        btle.DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
        print("A notification was received: %s" %data)

p = btle.Peripheral(<MAC ADDRESS>, btle.ADDR_TYPE_RANDOM)
p.setDelegate( MyDelegate() )

# Setup to turn notifications on, e.g.
svc = p.getServiceByUUID( <UUID> )
ch = svc.getCharacteristics()[0]
print(ch.valHandle)

p.writeCharacteristic(ch.valHandle+1, "\x02\x00")

while True:
    if p.waitForNotifications(1.0):
        # handleNotification() was called
        continue

    print("Waiting...")
    # Perhaps do something else here

A: It looks like the problem is that you're trying to write \x01\x00 to the characteristic itself. You need to write it to the Client Characteristic Configuration descriptor that proceeds it (0x2902). The handle is likely 1 greater than the characteristic (but you may want to confirm by reading the descriptors).
ch=chs[1]
cccd = ch.valHandle + 1
cccd.write("\x01\x00")

A: What was confusing for me was that in https://ianharvey.github.io/bluepy-doc/notifications.html
the part that enabled the notifications was in comments, so it didn't look obligatory to me.
the bare minimum (given you know the MAC-adress already an you included everything and declared the Delegateclass) for me is
p1 = Peripheral(<MAC>)
ch1 = p1.getCharacteristics()[3]
p1.setDelegate(MyDelegate())
p1.writeCharacteristic(ch1.valHandle + 1, b"\x01\x00")

Note that I already knew I wanted to get notifications from characteristic#3.
Also, without the 'b'-bytesprefix infront of "\x0\x00", it wouldn't work for me.

A: bluepy classes docs and samples are crazy, and not complete. To get more details, just checkout bluepy source (it is not big and easy to read)
But, as starting point you can use this notifications code sample, working with from Heart Rate Service (tested on bluepy 1.3.0)
Don't forget to replace device MAC to your own in Peripheral!
from bluepy import btle
from bluepy.btle import AssignedNumbers

import binascii

class MyDelegate(btle.DefaultDelegate):
    def __init__(self, handle):
        btle.DefaultDelegate.__init__(self)
        self.handle = handle
        print "Created delegate for handle", self.handle
        # ... more initialise here

    def handleNotification(self, cHandle, data):
        if(cHandle == self.handle):
            print "handleNotification for handle: ", cHandle, "; Raw data: ", binascii.b2a_hex(data)
            #Found somewhere. Not tested is this working, but leave here as decode example
            #val = binascii.b2a_hex(data)
            #val = binascii.unhexlify(val)
            #val = struct.unpack('f', val)[0]
            #print str(val) + " deg C"

print "Connecting..."
dev = btle.Peripheral("c8:2b:96:a3:d4:76")

try:
    print "Device services list:"
    for svc in dev.services:
        print str(svc)

    HRService = dev.getServiceByUUID(AssignedNumbers.heartRate)
    print "HRService", HRService

    print "HRService characteristics list: "
    for char in HRService.getCharacteristics():
        print "HRService char[", char.getHandle(), "]: ", char

    HRMeasurementChar = HRService.getCharacteristics(AssignedNumbers.heart_rate_measurement)[0] #Notice! Check is characteristic found before usage in production code!
    print "HRMeasurementChar", HRMeasurementChar, HRMeasurementChar.propertiesToString();

    # Assign delegate to target characteristic
    dev.setDelegate(MyDelegate(HRMeasurementChar.getHandle()));

    # We need to write into org.bluetooth.descriptor.gatt.client_characteristic_configuration descriptor to enabe notifications
    # to do so, we must get this descriptor from characteristic first
    # more details you can find in bluepy source (def getDescriptors(self, forUUID=None, hndEnd=0xFFFF))
    desc = HRMeasurementChar.getDescriptors(AssignedNumbers.client_characteristic_configuration);
    print "desc", desc

    print "Writing \"notification\" flag to descriptor with handle: ", desc[0].handle
    dev.writeCharacteristic(desc[0].handle, b"\x01\x00")# Notice! Do not use [0] in production. Check is descriptor found first!

    print "Waiting for notifications..."

    while True:
        if dev.waitForNotifications(1.0):
            # handleNotification() was called
            continue

finally:
    dev.disconnect();


text:
Q: Calculated Field in Expression I am using Fetch XML to get my results and cannot do the calculation on the query side. I need to take the difference on the SalesSum field and calculate based on the period and year.
Here is an example of my data
SalesSum    Period  Year
275000      1       2017
195000      2       2017
205000      3       2017
318000      1       2018
425250      2       2018
395000      3       2018

Difference = ((SalesSum period 1 year 2018) - (SalesSum period1 year
  2017))
Example: Difference = 318000-270888=43000 Period 1 Year

can this be accomplished using an SSRS expression?

A: Use tablix and select just Period as a row group.
And write this formula as the expression.
= Sum(iif(Max(Fields!Year.Value)=Fields!Year.Value,Fields!SalesSum.Value,0))
      -  Sum(iif(Min(Fields!Year.Value)=Fields!Year.Value,Fields!SalesSum.Value,0))


text:
Q: SSRS Parameter and Filter issue I have a SSRS 2014 report. I have few issues with the Vehicle List parameter:

*

*The Vehicle list parameter is not editable.  I set the data type to integer when I created the parameter. Can someone help me with making this filed editable? Also, it should be able to accept text as well.

*I want to filter the Vehicle List parameter with the below expression:
=Mid(Fields!VH_ID.Value,InStr(Fields!VH_ID.Value,"-")+ 1,2)

Can someone help me with filtering the parameter with the above expression?

A: It sounds like you want to filter your dataset by comparing the selected parameter value to a part of the vehicle ID column.
You can do this by adding a Filter expression to the dataset as shown here:

EDIT To handle multiple values

*

*Set the parameter to allow multiple values.

*Ideally, you would have a query that populates the Available Values for the parameter

*Change the dataset filter to use an In operator like this:

Note that the top Expression refers to the column in your dataset and the Value is your parameter. The Value expression should look like =Parameters!MyParam.Value with no "(0)" at the end of it.


text:
Q: Props are not passing to the test cases I have a simple component, but not able to pass props for my test cases, It was working fine without  - withRouter. what could be the reason
Component
const Plugins = ({pluginsData, history}) => {

    return (

 history.push(`/list/plugins`)}>Plugins

                {  pluginsData.length
                ? pluginsData.map((item, index) =>
{item.plugin}
)
                : " No Data" }

    )
}

export default withRouter(Plugins)
plugin.test.js
  const pluginsData= [
        {
            "plugin": "Apps (Coming soon)"
        }
    ]

const wrapper = shallow(<Plugins pluginsData={pluginsData}/>);

describe('test home page', () => {

    it('should render home page successfully', () => {
        expect(wrapper).toMatchSnapshot();
    });

    it('renders correct text in item', () => {
        expect(wrapper.find('.up-coming-text').get(0).props.children).toEqual('Apps (Coming soon)');
    });

    it('renders pluginsData length', () => {
        expect(wrapper.find('.up-coming-text')).toBeDefined();
        expect(wrapper.find('.up-coming-text').length).toEqual(pluginsData.length);
    });

});

Error
● test home page › renders pluginsData length
expect(received).toEqual(expected) // deep equality

Expected: 1
Received: 0

  28 |     it('renders pluginsData length', () => {
  29 |         expect(wrapper.find('.up-coming-text')).toBeDefined();
> 30 |         expect(wrapper.find('.up-coming-text').length).toEqual(pluginsData.length);
     |                                                        ^
  31 |     });
  32 |
  33 | });

  at Object.<anonymous> (ui/src/routes/Explorer/Plugins/plugins.test.js:30:56)

A: You didn't pass the pluginsData props correctly. It should be:
const wrapper = shallow(<Plugins pluginsData={pluginsData}/>);

source code: https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/66694262

A: You can use Component.WrappedComponent to test the component in isolation.
From the docs,

The wrapped component is exposed as the static property WrappedComponent on the returned component, which can be used for testing the component in isolation, among other things.

shallow(<Plugins.WrappedComponent pluginsData={pluginsData}/>)


text:
Q: Regex to append a word after the occurrence of any word from a list Recently I got this amazing answer on how to remove a word if it occurs after any word in word list1. I wanted to remove the word eat.
I was wondering if it is possible to do the reverse, add a particular word after the occurrence of any word from a given list.
list1 = ['duck', 'crow', 'hen', 'sparrow']
Input:[['Duck fish'], ['Crow veggies'], ['She lives there']]
Output:[['Duck eats fish'],['Crow eats veggies'],['She lives there']]
import re

list1 = ['duck', 'crow', 'hen', 'sparrow']

look_behinds = '|'.join(f'(?<=[{w[0].swapcase()}{w[0]}]{w[1:]})'
                        for w in list1)

EATS_RE = re.compile(rf'(?:{look_behinds})\s+eats?\b')

sentences = [['The crow eats'],
             ['Hen eats blue seeds'],
             ['the duck is cute'],
             ['she eats veggies']]

repl_sentences = [[EATS_RE.sub('', s, 1) for s in x] for x in sentences]
print(repl_sentences)

OUTPUT

[['The crow'], ['Hen blue seeds'], ['the duck is cute'], ['she eats veggies']]

Is there a way to change the code to perform the reverse task? What can be the regex for the problem?

A: What you're asking for is simple; just use the appropriate regex to match the particular words only, and replace it with the matched word which has "eats" appended to it:
>>> r = re.compile(r"\b([cC]row|[dD]uck)\b")
>>> r.sub('\\1 eats', "crow here") # '\\1' is the placeholder for the 1st group in our match, i.e. the bird names surrounded with capturing parentheses in our case
'crow eats here'

However, what you likely want is not to add the word if it already exists. For this to happen, we use negative lookahead for a more careful match for replacement:
>>> r = re.compile(r"\b([cC]row|[dD]uck)\b(?!\s+eats\b)")
>>> r.sub('\\1 eats', "crow here")
'crow eats here'
>>> r.sub('\\1 eats', "crow eats here") # should remain unaffected
'crow eats here'

To update (reverse) your code, it will be something like this:
import re

words = ['duck', 'crow', 'hen', 'sparrow']
captured_word = '|'.join(f'[{w[0].swapcase()}{w[0]}]{w[1:]}' for w in words)

EATS_RE = re.compile(rf'\b({captured_word})\b(?!\s+eats\b)')

sentences = ['The crow',
             'Hen blue seeds',
             'the duck eats too much',
             'she veggies']

[EATS_RE.sub("\\1 eats", s) for s in sentences]
# output: ['The crow eats', 'Hen eats blue seeds', 'the duck eats too much', 'she veggies']


text:
Q: Confusion with Terminal Velocity So I know that terminal velocity occurs when velocity becomes constant and the body is no longer accelerating.
However using our normal kinematics equation say a body in terminal velocity, the time it takes for say an object to fall $10000$m if the body reaches terminal velocity in between will imply $a = 0.$ So $10000 = \frac{1}{2}gt^2$. But our acceleration is now $0$ so the time is infinite?
Or do we use $10000 = v_Tt + \frac{1}{2}at^2?$ Where we now use the terminal velocity as our initial speed $u$ in the original equation $s = ut + \frac  {1}{2}at^2?$ ($s$ is displacement).
Where is my understanding wrong here?

A: The equations you have mentioned are derived for constant acceleration throughout the motion.If the acceleration changes in between, as in your case it suddenly changes to zero you have to apply the equation again for the new set of conditions(new acceleration is zero).But if the acceleration changes continuously with time, acceleration should be expressed as a function of time and integrated twice to get the displacement as a function of time.

A: The usual way to express the effect of air drag is an acceleration that is some function of velocity, and in the opposite direction to the velocity.  So an object falling in air, and choosing "down" as positive, you get this.
$$ a = g - D(v)$$
where $g$ is gravity, and $D(v)$ is the drag as a function of velocity. In some important situations it will simply be some constant times the square of the velocity. (But that is certainly not the only possible situation.)
https://en.wikipedia.org/wiki/Drag_equation
In that case you have the following.
$$ a = \frac{dv}{dt} = g - k v^2 $$
So if you have $v=0$ as your initial condition at $t=0$ you can do the integral.
$$ \int \frac{dv}{g-kv^2} = t  $$
Which will require some partial fractions to complete.
https://www.youtube.com/watch?v=m2M18p7gspM
The terminal velocity is such that this is zero. Meaning the following.
$$ kv^2 = g$$
Or, solving for $v$ you get this.
$$ v = \sqrt{\frac{g}{k}}  $$


text:
Q: maintain multiple session request over webservices in java I want to implement following solution (described in a image) using Java Web Services

When ever a user request with a valid credentials using web services , a session is created over server and that server (who receives the request ) creates a connection with  the other server i.e. Meta Trader's Server.
Here each user has a different session to maintain their connection and a state with meta trader server.
Note:
Currently i am not maintaining any session when a user request instead i am saving the connection object in a
  @javax.ws.rs.core.Context
  ServletContext servletContext;

  MyApplication application = new MyApplication();
  servletContext.setAttribute("application", application);

But this solution doesn't serve multiple users naturally. so please anyone has an idea how to solve the issue of serving multiple clients then please reply.
I am using Glassfish and JAX-RS ( Jersery 1.1 ) , JAXB

A: Simply use the annotation @javax.ws.rs.core.Context to get the HttpServletRequest and use its session within the container in which Jersey is deployed.
The code below is a simple example of a jersey resource that gets the session object and stores values in the session and retrieves them on subsequent calls.
@Path("/helloworld")
public class HelloWorld {

    @GET
    @Produces("text/plain")
    public String hello(@Context HttpServletRequest req) {

        HttpSession session= req.getSession(true);
        Object foo = session.getAttribute("foo");
        if (foo!=null) {
            System.out.println(foo.toString());
        } else {
            foo = "bar";
            session.setAttribute("foo", "bar");
        }
        return foo.toString();

    }
}

But you should NOT use RESTful API like this. It meant to be used as web service which is stateless, not web application. Check the following answers which I got the example and advice from
(jersey security and session management)
https://stackoverflow.com/a/922058
https://stackoverflow.com/a/7752250
(How to manage state in JAX-RS?)
https://stackoverflow.com/a/36713305
(Get ServletContext in JAX-RS resource)
https://stackoverflow.com/a/1814788


text:
Q: XPath contains to target specific type of link path I am having a lot of difficulty constructing an XPath query to return the kinds of URL's that I need. The XPath query below works for most cases however, I have been trying to tweak it so it only returns the URL where the actual page name contains 'about' and not the URL's where about is found in the directory name.
Current output (Bad):
https://www.domain.com/about/account.asp

Desired Output:
https://www.domain.com/about/about.asp

XPath
 (//a[contains(@href,'about')]/@href)[1]

NOTE: Because I am using a PHP XPath engine I can only utilize an XPath 1.0 solution.
I appreciate any suggestions!
Many thanks in advance!

A: XPath 1.0's string manipulation capabilities are very limited, you can only do this based on some assumptions.
Eg., if all URLs end with .asp, search for something like /about.asp, or a more general /about.. A very dirty hack would be to cut off everything starting at the first ?, only use the last few characters (to allow suffixes of different length like .xhtml or .pl) and search in there:
[
  contains(
    substring(substring-before(., '?'), string-length(substring-before(., '?')) - 10),
   'about'
  ) or (
    not(contains(., '?')) and
    contains(substring(., string-length(.) - 10), 'about')
  )
]

And this still should still be extended for hashes # in place of ? to fetch most cases, but there still will be enough it will fail at.
I would highly recommend to use some regular expression from PHP which will be much more robust and convenient. Or use an external XPath 2.0/XQuery processor like Saxon, BaseX, ...

A: The obvious solution:
//a[contains(@href, '/about.asp')]

But assuming you don't want to do that, I don't think it's possible to do what you need. The closest I got:
//a[contains(@href, 'about') and not(contains(substring-after(@href, 'about'), '/'))]

Explanation: "Select any <a> element that, in its @href attribute, does contain 'about' and does not contain any '/' after 'about'."
The problem is, that while it matches https://www.domain.com/account/about.asp and it (correctly) does not match https://www.domain.com/about/account.asp, it also does not match https://www.domain.com/about/about.asp, because there's an "about" substring succeeded by a '/'.
The best you can do, I think, is to simply select //a[contains(@href, 'about')] and then use your PHP to filter the results as needed.

A: Do you remember which browser you used? Internet Explorer counts element nodes beginning by 0.
about.asp obviously comes before account.asp, so I would use this :
(//a[contains(@href,'about')]/@href)[0]


text:
Q: Liskov Substitution Principle 4 questions I am finding it very difficult to understand this concept. I had a couple of questions in my mind about it. I've tried checking online but there's not much resources out there about it.
Does the subclass need to retain its distinctiveness throughtout its entire life?
I am pretty sure that LSP defines a contract between a super and a sub class, correct me if i am wrong.
What if a given function uses some object, can you replace the object with one of it's sub classes without breaking it's execution?
Will the program still work if there is a variable whose type is a super class. If I place an instance of that super class or any of the sub classes into that variable.
I am sorry if this didnt make sense. These 4 questions are bothering me about LSP.
Thank you very much

A: LSP:  If S is a subclass of T, then every instance of S is an instance of T.
That's it, really, but it has implications.
I don't know what you mean by subclasses "retaining their distinctiveness".
LSP does imply that subclass instances must adhere to the superclass contract, but it's really about what it means when you use S or T in other contracts.
For instance, if you write a function Number add(Number a, Number b) that is supposed to add two numbers, then LSP says that what this really means is that it can add any instance of Number to any other instance of Number, and that includes instances of any subclass.  LSP says that this function cannot be correct otherwise, because there is nothing it can know about every instance of Number that isn't true for Integers, Floats, BigDecimals, etc., because those are all instances of Number.

What if a given function uses some object, can you replace the object
  with one of it's sub classes without breaking it's execution?

If this is a parameter, and you cannot, then the function isn't correct, or the subclass isn't correct.

Will the program still work if there is a variable whose type is a
  super class. If I place an instance of that super class or any of the
  sub classes into that variable

Not necessarily.  Just because the variable is of type Integer, that doesn't mean you can set it to 625 arbitrarily and expect the program to continue working.  625 is an Integer just like every S is a T


text:
Q: EGit linked folder marked as dirty when its not A linked folder In one of my projects is constantly marked as dirty.
The project belongs to another project that it also in my workspace that also uses EGit and is fully commited to date - with no files or folders marked as dirty.
The below shows what I am seeing in project explorer or navigator (each project also has other files and subdirs). How can I get PrjA to be clean tracked?
>PrjA (dirty because of linked subdir)
 |
 L> PrjBSubDir(linked, dirty)

PrjB (tracked, no changes)
 |
 L PrjBSubDir(tracked, no changes)

NOTE: I have Egit installed, but not git git, so I cant run prompt commands...

A: Just updated EGit and the issue was resolved.


text:
Q: Protractor addMockModule for angular applications without ngApp The angular application on which I am running my e2e tests does not have ngApp directive and bootstraps manually. Is it not possible to insert mock modules via Protractor in this case?
//load angular mocks as a string here
var angularMocks = require('./angularMocks.module.js').mock;
            browser.addMockModule("ngMockE2E", angularMocks );
            browser.addMockModule('httpBackendMock', function httpBackendMock() {
                console.log('inside httpBackendMock');
                angular.module("httpBackendMock", ['ngMockE2E'])
                    .run(['$httpBackend', function ($httpBackend) {
                        console.log("Inside Run");
                        $httpBackend.whenGET(/.*employees.*/).respond(404, '');

                        $httpBackend.whenGET(/.*/).passThrough();
                        $httpBackend.whenPOST(/.*/).passThrough();
                        $httpBackend.whenPUT(/.*/).passThrough();
                                       }]);
            });
            browser.get(url);

This logs 'inside httpBackendMock' in the browser console but not 'Inside Run' indicating that the API calls are never intercepted.


text:
Q: Can't view Heroku logs - Cannot read property 'run' of undefined I am attempting to deploy a python3 app to heroku. The app has some kind of error and isn't rendering (I see the generic error message in the browser) so I'm trying to troubleshoot via Heroku logs,  but I get this error instead of the log output.
C:\Users\Kate\AppData\Local\heroku\tmp\heroku-script-182282411:14
cmd.run(ctx)
   ^

TypeError: Cannot read property 'run' of undefined
    at Object.<anonymous> (C:\Users\Kate\AppData\Local\heroku\tmp\heroku-script-
182282411:14:4)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:456:32)
    at tryModuleLoad (module.js:415:12)
    at Function.Module._load (module.js:407:3)
    at Function.Module.runMain (module.js:575:10)
    at startup (node.js:160:18)
    at node.js:445:3

This is on Windows 7 x86, I tried in both windows command prompt and Git Bash and got the same result. I installed the latest Heroku toolbelt with no change. Any thoughts on what to try next?

A: Hm. I fully uninstalled heroku toolbelt including deleting the c:...\Heroku folder then reinstalled it and now it is working again. So I guess the first install didn't take.


text:
Q: Symplectic structure on tensor products and duals Suppose $(V,\omega_V)$ and $(W,\omega_W)$ are two finite-dimensional real symplectic vector spaces. I want to know how I can define new symplectic structures.
I know $V\oplus W$ comes with a natural symplectic form $\omega_V \oplus \omega_W$. How can I define symplectic structures on tensor products and dual spaces?
I have been looking around and haven't found anything regarding this issue.


text:
Q: Axios.post returning :ERR_EMPTY_RESPONSE after API call I've made a axios post request in my react component, which makes a request to twilio to send a text message to my phone from a route on my server.
The text message and payload are transmitted successfully however when opening the network tab in the console I get this error in a minute or two.
POST http://localhost:8080/api/twilio net::ERR_EMPTY_RESPONSE
Any notion out there how to solve this?

This is the code from my react component:
import React, { Component } from 'react';
import axios from 'axios';
import { Grid, Segment, Form } from 'semantic-ui-react';
import './test.css';

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = { phonenumber: '' };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ phonenumber: event.target.value });
  }

  handleSubmit() {
    return axios
      .post('/api/twilio', {
        phonenumber: this.state.phonenumber,
      })
      .then(resp => resp.data)
      .catch(error => console.log(error));
  }

  render() {
    const { phonenumber } = this.state;
    console.log('phonenumber', phonenumber);

    return (
      <Grid columns={1} stackable textAlign="center">
        <Grid.Column width={1} />
        <Grid.Column width={14}>
          <Form onSubmit={this.handleSubmit}>
            <Segment stacked>
              <Form.Group id="form-group" inline>
                <label>Phone Number</label>
                <Form.Input onChange={this.handleChange} value={phonenumber} placeholder="+12223334444" />
              </Form.Group>
              <Form.Button id="form-group-button" content="Submit" />
            </Segment>
          </Form>
        </Grid.Column>
        <Grid.Column width={1} />
      </Grid>
    );
  }
}

export default Test;

Update:
This is the twilio route on the backend.
const router = require('express').Router();

module.exports = router;

router.post('/', (req, res) => {
  let SID = 'ACc5b16ad0cefc3b514e69bc30636726e2';
  let TOKEN = '3145fb41afe308f22b0b7c647e6a8e17';
  let SENDER = '+18622256079';

  if (!SID || !TOKEN) {
    return res.json({ message: 'add TWILIO_SID and TWILIO_TOKEN to .env file.' });
  }

  let client = require('twilio')(SID, TOKEN);

  client.messages
    .create({
      to: req.body.phonenumber,
      from: SENDER,
      body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
    })
    .then(message => console.log(message.sid));
});

A: In your route on the server, nothing will ever be returned to the client because SID and TOKEN are always defined (at least in your example). To make sure that the request will not fail, you will need to send at least some response back after the Twilio request, e.g.:
client.messages
  .create({
    to: req.body.phonenumber,
    from: SENDER,
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?'
  })
  .then(message => {
    console.log(message.sid);

    // Either just send an empty, successful response or some data (e.g. the `sid`)
    res.status(200).send(message.sid);
  })
  .catch(err => {
    console.log(err);

    // In case of an error, let the client know as well.
    res.status(500).send(err);
  });


text:
Q: Thread Safe Data and Thread Safe Containers Hi Guys I want to know what is the difference between thread safe Data and Thread Safe Containers

A: Thread safe data:

*

*Generally refers to data which is protected using mutexes, semaphores or other similar constructs.

*Data is considered thread safe if measures have been put in place to ensure that:

*

*It can be modified from multiple threads in a controlled manner, to ensure the resultant data structure doesn't becoming corrupt, or lead to race conditions in the code.

*It can be read in a reliable fashion without the data become corrupt during the read process.  This is especially important with STL-style containers which use iterators.

*Mutexes generally work by blocking access to other threads while one thread is modifying shared data. This is also known as a critical section, and RAII is a common design pattern used in conjunction with critical sections.

*Depending on the CPU type, some primitive data types (e.g. int) and operations (increment) might not need mutex protection (e.g. if they resolve down to an atomic instruction in machine language).  However:

*

*It is bad practice to make any assumptions about CPU architecture.

*You should always code defensively to ensure code will remain thread-safe regardless of the target platform.

Thread safe containers:

*

*Are containers which have measures in place to ensure that any changes made to them occur in a thread-safe manner.

*For example, a thread safe container may allow items to be inserted or removed using a specific set of public methods which ensure that any code which uses it is thread-safe.

*In other words, the container class provides the mutex protection as a service to the caller, and the user doesn't have to roll their own.


text:
Q: Replace element inside a DataTemplate I have a LongListSelector with a ItemTemplate like this:
<LongListSelector.ItemTemplate>
    <DataTemplate>
       <StackPanel>

          Here I have a lot of elements that are always the same.
          .
          .
          .
          and one that varies

       </StackPanel>
    </DataTemplate>
</LongListSelector.ItemTemplate>

I know how to use this TemplateSelector class to change all the content inside the ItemTemplate depending o the item type.
My question is, how can use the template selector to change only the one item that varies so I dont need to repeat the whole lot of other elements.
I have tried using a ContentControl and ContentPresenter inside de StackPanel with no success

A: You're going to want to create a data trigger in your XAML to check whether each item is the one you're looking for.
This SO question is relevant enough to get you on the right track. It'll end up looking something like this:
<Style TargetType="TabItem">
        <Style.Triggers>
            <!-- Styling for elements that are NOT the last item -->
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource LastItemConverter}}" Value="False">
                <Setter Property="Template">
                    <Setter.Value>
                        .
                        .
                        .
                    </Setter.Value>
                </Setter>
             </DataTrigger>
            <!-- Styling for elements that are the last item -->
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource LastItemConverter}}" Value="True">
                <Setter Property="Template">
                    <Setter.Value>
                        .
                        .
                        .
                    </Setter.Value>
                </Setter>
             </DataTrigger>

The Converter looks something like this - depending on what UI element you're binding.
public class IsLastItemInContainerConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        DependencyObject item = (DependencyObject)value;
        TabControl tc = (TabControl)TabControl.ItemsControlFromItemContainer(item);

        // Return true for the first and last element
        // (so they are similarly styled compared to other elements).
        if (tc.ItemContainerGenerator.IndexFromContainer(item) == tc.Items.Count - 1) {
            return true;
        }
        else if (tc.ItemContainerGenerator.IndexFromContainer(item) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

Hope that helps.


text:
Q: Add opacity on an image I'm going straight to the point here.
I want to create a simple window within an image.
outside the window will have a opacity like on the sample picture.
I'm not really good when it comes to css so please bear with me.

.section2{
 }

.section2 .row{
 margin: 0;
}
.the-container{
 position: relative;
 width: 100%;
 height: 450px;
}
.the-container .text-center{
 background: #fff;
 opacity: .9;
}

.img-canvas{
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
width: 100%;
height: 100%;
background-image: url(https://www.aman.com/sites/default/files/styles/1371x706/public/amanpulo-location-1200-x-825.jpg?itok=4BQy9j-X);
background-size: 100% 100%;
background-position: 50% 50%;
background-attachment: scroll;
z-index: -1;
}
.window{
position:absolute;
width:50%;
height:50%;
background-size: cover;
top:0;
left:25%;
z-index: -1;
opacity: 1;
}

something like this:

and here's a fiddle for you to manipulate the code:
https://jsfiddle.net/Lk21vL01/
thanks in advance.

A: You were very close, you just needed to apply similar styling to your .window element and use background-attachment:fixed
see this updated jsfiddle
.section2{
}

.section2 .row{
  margin: 0;
}
.the-container{
  position: relative;
  width: 100%;
  height: 450px;
}
.the-container .text-center{
    background: #fff;
    opacity: .9;
}
.window,
.img-canvas{
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    width: 100%;
    height: 100%;
    background-image: url(https://www.aman.com/sites/default/files/styles/1371x706/public/amanpulo-location-1200-x-825.jpg?itok=4BQy9j-X);
    background-size: 100% 100%;
    background-position: 50% 50%;
    background-attachment:fixed;
    z-index: -1;
    opacity: 0.5;
}
.window{
  position:absolute;
  width:50%;
  height:50%;
  top:0;
  left:25%;
  z-index: -1;
  opacity: 1;
}

A: Not the most proper way to achieve this, but you could use a box-shadow "hack" to create the effect you're looking for. Just set a box shadow around the window with 0 blur and a spread that will always bigger than the background (something like 1000, or even 5000 pixels).

#background {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: linear-gradient(to bottom, slategray, #333);
  overflow: hidden;
}

#window {
  position: absolute;
  width: 250px;
  height: 100px;
  top: 25%;
  left: 25%;
  box-shadow: 0 0 0 1000px rgba(255, 255, 255, 0.75);
}


text:
Q: SQL database design for bookmarking an item I have a web application in which each user is allowed to add its own items.
These items are not public or shared/visible accross the users. In other words, if user 1 creates an item, that item is only belongs to user 1.
[table: item]
id     title     content
1      ...       ...
2      ...       ...
3      ...       ...

[table: bookmark]
item_id   user_id
1         1
2         1
3         2

I need a "bookmarks" page which shows those items that the user has bookmarked. Does it make sense to use a separate table bookmark like I did above?

A: If you use create a new column named bookmark and bookmark_reference of the type uniqueidentifier for both tables, and your code simply puts a GUID (or the SQL function NEWID()) when a user does a bookmark.
Your bookmark table replace item_id with bookmark_reference and another varchar(100) column table_reference.
Thus making your bookmarking functionality generic for the whole system, any table, can be used for bookmarking or any other text the user would want to record against this particular record of this particular table.
Like custom 'notes' against a customer for just this user.
To make a "public" bookmark/note, just use either a zero or a null in user_id.
Just giving you basic ideas. The ERP Syteline from INFOR uses this type of functionality, but they use a guid (uniqueidentifer) for the user_id equivalent field, making the table unreadable without a INNER JOIN to the users table. So using user_id will make everyone's life easier down the road.
So the structure would be like this:
[table: item]
id     title     content     bookmark
1      ...       ...         {guid abc}
2      ...       ...
3      ...       ...

[table: bookmark]
bookmark_reference     table_reference   user_id
{guid abc}             item              1
{guid def}             item              1
{guid xyz}             customer          2
{guid 123}             user              1

Fun fact with this structure, a user could have a bookmark on a user!
Edit: Link to a StackOverflow article on using uniqueidentifier


text:
Q: Absolute centering does not work in FF I want to absolute a div the following way, but for some reason firefox is pushing the div to the very top, so it is centered horizontally, but vertically it is top. Chrome works fine
HTML:

ict recruit

Login

                                Password

                            Password

CSS:
#login{
    position: relative;

    text-align:center;
    width: 100%;
    height: 100%;
    display: block;
}
#header {
    position:relative;
    text-align: left;
    padding-left: 50px;
    width: 100%;
    height: 50px;
    border-bottom: 3px solid #dc0000;
    font-family: Leelawadee, sans-serif;
    font-size: 30px;
    line-height: 50px;
}
.redText {
    color: rgb(220,0,0);
}
#wrapper {
    margin: 0 auto;
    position: relative;
    width: 400px;
    height: 400px;
    top: 50%;
    left: 50%;
    margin-top: -200px;
    margin-left: -200px;
    text-align: left;
}
div.page-header h1 {
    font-family: Leelawadee, sans-serif;
    font-weight: 300;
    display: inline-block;
    padding-bottom: 10px;
    border-bottom: 3px solid #dc0000;
}
#loginBox {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 30px;
    background: #e5e5e5;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
    border-radius: 15px;

}

A: Get rid of the negative margins on your wrapper. Set the position to absolute. Adjust the top and left percentages.
jsfiddle
CSS
#wrapper {
   margin: 0 auto;
   position: absolute;
   width: 400px;
   height: 400px;
   top: 50%;
   left: 30%;
   text-align: left;

}

A: As a general rule, its a bad idea to use negative margins...particularly when they're effecting a major structural element in the DOM.  I would recommend you take a different approach to centering your #wrapper div like the one i've made in this fiddle http://jsfiddle.net/Uwsxu/2/
in short, remove your negative margins and your left:50% and top:50%
#wrapper {
    margin: 0 auto;
    position: relative;
    width: 400px;
    height: 400px;
    text-align: left;
}

A: Like Morpheus said: You do not have the position on the wrapper as absolute.
If you want to use this method:
    margin: 0 auto;
    position: relative;
    width: 400px;
    height: 400px;
    top: 50%;
    left: 50%;
    margin-top: -200px;
    margin-left: -200px;

then the position should be absolute or fixed, not relative.
So I suggest the following for centering the wrapper:
#wrapper {
    margin: 0 auto;
    position: relative;
    width: 400px;
    height: 400px;
    top: 150px; (+ the 50px for the header, since it is relative to the header as well)
    text-align: left;
}


text:
Q: How to prevent Mathematica from giving inexact answers Upon doing a simple subtraction 13.725 - 13.5 both Mathematica 11.3 and 12.0 beta version are giving me 0.22499999999999964 although both display the answer as 0.225. Is there a way to yield the answer in exact form. For now I can only use SetPrecision to address the issue:
SameQ[0.22499999999999964, 0.225] && Equal[0.22499999999999964, 0.225]
(*False*)
SameQ[SetPrecision[0.22499999999999964, 4], 0.225] && Equal[SetPrecision[0.22499999999999964, 4], 0.225]
(*True*)
I have a code with some degree of complexity and I am going to simplify the problem a bit here. lets say i have two points with (x,y,z) coordinates and i want to say that the translation of a point by a vector: {13.725, 0.8397114317029974, 0.46748599816306713} - {13.50, 0., 0.} = {0.22499999999999964, 0.8397114317029974, 0.46748599816306713} is equal to a point 'b' {0.225, 0.8397114317029974, 0.46748599816306713}. How can this be done easily?

A: With the numbers in your example, equality testing with Equal (i.e. ==) already works:
pointA = {13.725, 0.8397114317029974, 0.46748599816306713};
transVec = {13.50, 0., 0.};
pointB = {0.225, 0.8397114317029974, 0.46748599816306713};

pointA - transVec == pointB
(* True *)

This is because Equal considers approximate numbers with machine precision equal "if they differ in at most their last seven binary digits (roughly their last two decimal digits)" (from the Details section of its docs).
However, that threshold may not be appropriate for you, so you can use other methods. For instance, evaluate the distance between the two points (e.g. with Norm) and check whether it is less than an appropriate threshold:
Norm[(pointA - transVec) - pointB] < 10 $MachineEpsilon
(* True *)

Note, however, that the above will remain unevaluated if its truth value cannot be decided. For instance, imagine that, contrary to your expectation, a symbol does not have a numerical value (here I am using pointC without having assigned it a value):
Norm[(pointA - transVec) - pointC] < 10 $MachineEpsilon

Sqrt[Abs[0.22499999999999964 - pointC]^2 +
     Abs[0.46748599816306713 - pointC]^2 +
         Abs[0.8397114317029974 - pointC]^2] < 2.220446049250313*^-15

That may or may not be desirable (that's your design decision); if you want to avoid it, though, you can wrap the inequality in TrueQ:
TrueQ[Norm[(pointA - transVec) - pointC] < 10 $MachineEpsilon]
(* False *)


text:
Q: Finding the fixed points of a contraction Banach's fixed point theorem gives us a sufficient condition for a function in a complete metric space to have  a fixed point, namely it needs be a contraction.
I'm interested in how to calculate the limit of the sequence $x_0 = f(x), x_1 = f(x_0), \ldots, x_n = f(x_{n-1})$ for a fixed $x$. I couldn't figure out a way to do this limit with ordinary limits calculations.
The only thing I have at my disposal is the proof of the theorem, from which we see that the sequence $x_n$ is a Cauchy sequence; from this, I'm able to say, for example, that $\left|f(f(f(x))) - f(f(f(f(x))))\right| \leq \left|f(x_0)-f(x_1)\right| ( \frac{k^3}{1-k})$, where $k$ is the contraction constant, but I can't get any further in the calculations.
My question is: how should I procede to calculate this limit exactly? If there are non-numerical (read: analytical) way to do this.
Remark: I'm interested in functions $\mathbb{R} \rightarrow \mathbb{R}$ (as it can be seen from my use of the euclidean metric in $\mathbb{R}$)

A: The limit is the fixpoint, so you "just" need to solve the equation $x=f(x)$. Whether this can be done in closed form or not depends on what $f$ looks like.

A: @Andy (in reply to your comment/question "Could you provide some example that has a closed form and explain if (and how) it is possible to find the fixed point without solving x = f(x) but trying to calculate the limit of x_n?":
I believe that you would be hard-pressed to achieve this, since your function $f$ is a continuous function (being a contraction map in the first place); and if you then take limits of both sides of $x_n = f(x_{n-1})$, you will get:
$$\lim_{n \rightarrow \infty} x_n = \lim_{n \rightarrow \infty} f(x_{n-1})$$
which (by continuity) leads to:
$$\lim_{n \rightarrow \infty} x_n = f (\lim_{n \rightarrow \infty} x_{n-1})$$
or
$$l = f(l)$$
with $l = \lim_{n \rightarrow \infty} x_n$
This means that you will have to solve $l = f(l)$, which was what you wanted to avoid in the first place!

A: In addition to what Hans Lundmark has said about solving $x = f(x)$, you could also try writing a simple computer programme to read a number $n$ and a starting value $x_0$, and compute the result of applying f to $x_0$ $n$ times, thus delivering an approximation to the root that you are seeking. The value of $n$ may have to be fairly large in some cases.


text:
Q: Which is more efficient cooling? Cooling yourself from cold water from Referigerator or Airconditioning? Case a: You chill a glass of water in refrigerator to a certain temperature and drink it.. it lowers your body temperature by X degrees.
Case b: You switch on the a/c for a certain duration.. it lowers your body temperature by X degrees.
Which is more efficient method of cooling? (in terms of energy used and money spent respectively)

A: There is a whole bunch of factors that would go into calculating which would cool you most efficiently. In all honesty, in practice, this question is next to impossible to answer. You are attempting to maximizing cooling, while minimizing cost.
Do you factor into account the energy spent just having the fridge running? How big is the fridge? What kind of efficiency does the fridge have? Do you honestly believe you can make an accurate measurement on your temperature decreasing after consuming a glass of water? How efficient is the air conditioning model? What kind of circulation is occurring in the room? How hot is it outside? How hot is it inside? How big is the room? The questions go on and on and on. And they would all impact the answer.
My two bits is to just do both.


text:
Q: Datagridview row filter I am using DataView and RowFilter. Only one column is filtering,
but I want all columns to be filtered.
I would like to search for a word in the text box to make this filter.
DataView dv = dt.DefaultView;

if (e.KeyChar == (char)13)
{
    dv.RowFilter = string.Format("Name LIKE '%{0}%'" ,textBox1.Text );
    //  dv.RowFilter = string.Format("Date LIKE '%{0}%'", textBox1.Text);
}

The columns headers name = Name, Date, and so on.

A: Format should be like this for multiple columns;
dv.RowFilter = "Column1 = " + value1 + " AND Column2 = " + value2;

According to your scenario;
dv.RowFilter = string.Format("Name LIKE '%{0}%' AND Date = {1}" ,textBox1.Text, DateValue );

A: (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name = '{0}'", TextBoxForSearch.Text);

A: string query = textBox1.Text;
if(query == string.Empty)
{
    dataTable.DefaultView.RowFilter = string.Empty;
}
else
{
    (dgv.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name = {0}", textBox1.Text);
    (dgv.DataSource as DataTable).DefaultView.RowFilter = string.Format("Date = {1}", textBox1.Text);
}


text:
Q: How to save and execute a stored procedure in cosmos db through azure portal? I tried to do this from the Script Explorer->Stored Procedure view, but when I use the button Save & Execute there, it only gives results in the following error message:

Failed to save the script
Database Account: myaccountname, Script: HelloWorld, Message: {"code":500,"body":"{\"message\":\"An error has
  occurred.\"}"}

And the textbox under Results is unchanged.
Below is a screenshot of how it looks in azure portal:

A: @MichaelRätzel: I have just written a very simple CosmosDB Script and run it on Azure Portal.
function TestSample() {
    getContext().getResponse().setBody("Hello World");
}

And here is my result:

I got the same problem with you about the Failed to save the stored procedure. What I did to solve that problem is:

*

*Save the Stored Procedure first

*Left-click to the current SP on the left column

*Save & Execute the SP

I think this is a technical issue of Azure Portal. Try this and tell me the result.

A: If you want to test this function on Azure Portal, you can delete the parameter "prefix" and add a variable name "prefix" to your stored procedure.
The reason of this error is this function needs data from outside (via parameter), and you don't provide it on Azure Portal.
function upsertFans() {
    var prefix = "";
    var collection = getContext().getCollection();

    // Query documents and take 1st item.
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT * FROM root r',
        function (err, feed, options) {
            if (err) throw err;

            // Check the feed and if empty, set the body to 'no docs found',
            // else take 1st element from feed
            if (!feed || !feed.length)
                getContext().getResponse().setBody('no docs found');
            else
                getContext().getResponse().setBody(prefix + JSON.stringify(feed[0]));
        });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}


text:
Q: How to display string in the format ip1,ip2,ip3,ip4 etc I want to display a string in the format ip1,ip2,ip3,ip4 etc in 'N' number of times. Can any one help me to solve this c# programme.

A: I assume this is what you want:
int n = 10;
IEnumerable<String> ips =  Enumerable.Range(1, n).Select(i => "ip" + i);
String allIPs = String.Join(",", ips);

Result:
ip1,ip2,ip3,ip4,ip5,ip6,ip7,ip8,ip9,ip10

Demo

A: var myIps = String.Join(", ",(Enumerable.Range(1, 10).Select(i => "ip" + i)));

myIps will be ip1, ip2, ip3....ip10


text:
Q: What is so special about Paschen, Balmer and Lyman series? I'm reading McIntyre's QM book and I see the same diagram ever so often:

He goes on to say:

I don't understand what he is trying to say with the last sentence. It seems he is saying, that transitions to higher-levels higher than n = 5 requires absorption of photons. But every level requires the absorption of photons. For example, to go from 1 to 2, we need light absorption.

*

*What does he mean here?

*Perhaps I am missing the significance of the three series. Perhaps there is some other physics going on?

*What is the significance of the three series? Why are they always shown in textbooks?

A: 1 He is saying that, just as in the three series described above, the absorption of photons holds for any n.
2-3 The significance of these series is mainly historical, because they are of course related to the first energy levels. There is nothing particularly special about any of these series other than the experiments whence they come from. For instance, the Lyman series are important because they study the UV spectrum of the hydrogen gas, which by itself was a hot topic at the time.
You could benefit from reading about the history of these series, but just keep in mind that these transitions are no different from any others.


text:
Q: How to fix " Could not compile `user32-sys" error in Rust ;)
My file cargo.tml contains
...
[dependencies]
winapi = "0.2.7"
user32-sys = "0.2"

And my main.rs
extern crate winapi;
extern crate user32;

But, when i use cargo build. I have this error:
error: aborting due to previous error

error: Could not compile `user32-sys`.
warning: build failed, waiting for other jobs to finish...
error: build failed


text:
Q: Windows.Devices.Usb recieve delay I made simple C# program that talks to USB device. It works and I can send and receive data correctly.
Problem is that I observe about 100 delay.
I found place where that delay is and I have question how to get rid off it.
That bellow is only part of code:
using Windows.Devices.Usb;

UInt32 vid = 0x04D5;
UInt32 pid = 0x0A32;
string aqs    = UsbDevice.GetDeviceSelector(vid, pid);
var myDevices = await DeviceInformation.FindAllAsync(aqs, null);
UsbDevice device = await UsbDevice.FromIdAsync(myDevices[0].Id);
DataReader reader = new DataReader(device.DefaultInterface.BulkInPipes[0].InputStream);

Stopwatch stopwatch = Stopwatch.StartNew();
await reader.LoadAsync(num);
stopwatch.Stop();

Console.WriteLine(stopwatch.ElapsedMilliseconds);

stopwatch gives me about 100ms time.  How to make it smaller?  Or maybe different USB lib?
Regards,
Chris