Q:

Error in Types for the reducers in TypeScript in React-Redux

I am using TypeScript for my React-Redux app. I have followed the TypeScript React Starter, however, the example mentioned there does not have any action methods that has some arguments/payload.
I have a simple requirement -

Show a list of names and when a button is clicked a new name is added. When another button is clicked 2 names are added.

The entry point for the app index.tsx looks like this -
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import { createStore } from 'redux';
import { StoreState } from './types';
import { listUsers } from './reducers';
import { Provider } from 'react-redux';
import ListUsers from './containers/ListUsers';

const store = createStore<StoreState>(listUsers, {
  'users': [
    {
      'id': 0,
      'firstName': 'Aniyah',
      'lastName': 'Luettgen',
      'phone': '861-332-5113',
      'email': 'Danika.Ryan84@yahoo.com',
      'role': 'admin'
    },
    {
      'id': 1,
      'firstName': 'Alisa',
      'lastName': 'Pacocha',
      'phone': '085-056-3901',
      'email': 'Eusebio68@yahoo.com',
      'role': 'admin'
    }
  ]
});

ReactDOM.render(
  <Provider store={store}>
    <ListUsers/>
  </Provider>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();

The constants file (constants/index.tsx) looks like this -
export const LIST_USERS = 'LIST_USERS';
export type LIST_USERS = typeof LIST_USERS;

export const ADD_USER = 'ADD_USER';
export type ADD_USER = typeof ADD_USER;

export const ADD_USERS = 'ADD_USERS';
export type ADD_USERS = typeof ADD_USERS;

The types (types/index.tsx) are -
export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export interface Action<T> {
  type: string;
  payload?: T;
}

My Component (components/ListUsers.tsx) looks like this -
import * as React from 'react';
import { DispatchProps, ListUsersProps } from '../containers/ListUsers';
import { User } from '../types';

interface ListState {
  counter: number;
}

class ListUsers extends React.Component<ListUsersProps & DispatchProps, ListState> {

  constructor(props: ListUsersProps & DispatchProps) {
    super(props);

    this.addUser = this.addUser.bind(this);
    this.addMultipleUser = this.addMultipleUser.bind(this);

    this.state = {
      counter: 0
    };
  }

  render() {
    return (

        <button onClick={() => this.addUser()}>Add User</button>
        <button onClick={() => this.addMultipleUser()}>Add User</button>
        {this.props.users.map((user: User) => (

{user.firstName}

        ))}

    );
  }

  private addUser() {
    this.props.addUser({
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    });
    this.setState({
      ...this.state,
      counter: this.state.counter + 1
    });
  }

  private addMultipleUser() {
    this.props.addUsers([{
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }, {
      id: this.state.counter,
      firstName: 'ijkl',
      lastName: 'mnop',
      email: 'ijkl@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }]);
    this.setState({
      ...this.state,
      counter: this.state.counter + 2
    });
  }
}

export default ListUsers;

My container component (containers/ListUsers.tsx) looks like this -
import { connect, Dispatch } from 'react-redux';
import { Action, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): Action<User>;
  addUsers(users: Array<User>): Action<Array<User>>;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps, {}>(mapStateToProps, mapDispatchToProps)(ListUsers);

Now here is the reducer where I am facing issues (reducers/index.tsx) -
import { Action, StoreState, User } from '../types';
import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export const listUsers = (state: StoreState, action: Action<User>): StoreState => {
  switch (action.type) {
    case LIST_USERS:
      return state;
    case ADD_USER:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, action.payload]
      };
    case ADD_USERS:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
      };
    default:
      return state;
  }
};

Here the compiler says that in the reducers/index.tsx in
case ADD_USERS:
  return {
    ...state,
    users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
  };

that action.payload is User and not Array<User> which is right (I have declared the reducer with type (state: StoreState, action: Action<User>)).
How do I work with this? If there isn't an alternative, I will have to write separate reducers for every ACTION that has a different payload which I think is bad.
The way I am using the DispatchProps type also looks very odd to me. I am trying to follow this for the types of mapStateToProps and mapDispatchToProps.
Is there any work around for this?
PS: I am using react, redux and react-redux libraries.

A:

I found a solution for this. I am not sure if it is right way to do this.

Instead of making the Action Type generic like so -
interface Action<T> {
  type: string;
  payload?: T;
}

I created a Separate Action Type for each Action and then the Action Type accepted by the Reducer would be the | of them.

So, the types look like this (types/index.tsx) -
import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export type ListUsersAction = {type: typeof LIST_USERS};
export type AddUserAction = {type: typeof ADD_USER, payload: User};
export type AddUsersAction = {type: typeof ADD_USERS, payload: Array<User>};

export type Actions = ListUsersAction | AddUserAction | AddUsersAction;

and the Container Component (containers/ListUsers.tsx) looks like this -
import { connect, Dispatch } from 'react-redux';
import { AddUserAction, AddUsersAction, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): AddUserAction;
  addUsers(users: Array<User>): AddUsersAction;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps>(mapStateToProps, mapDispatchToProps)(ListUsers);

There are no compilation errors any more, and payload for both ADD_USER and ADD_USERS is received properly.

There is a recommendation to reduce the Action Type boilerplate here.


Q:

How to evaluate all derivatives of a polynomial at a point with FFT?

I found this problem:

Evaluating all derivatives of a polynomial at a point
Given a polynomial A(x) of degree-bound n, its tth derivative is
  defined by

From the coefficient representation $(a_0, a_1, . . . , a_{n-1})$ of A(x) and
  a given point $x_0$, we wish to determine A(t) ($x_0$) for t = 0, 1, . . . ,
  n - 1.

I know the vector of the coefficients has to be used and I also know that the derivative of a term $ax^n$ is $a*n*x^{n-1}$, but where do I go from there?
I can only think of the naïve scheme to evaluate this: Find the first derivative ($O(n)$), evaluate it using Horner's method ($O(n)$). Repeat this for all deterivaties, giving $(O(n^2)$).

A:

Hint: Taking the derivative has a certain, simple diagonal effect on the Fourier transform, that hopefully was covered in class. Hence if you compute the Fourier transform of the original function, you "know" the Fourier transform of all its derivatives as well. Given the Fourier transform, there is a formula for the value of the actual function. In your case, in order to compute the value of all derivatives of the function at a point, you multiply some matrix by the vector of Fourier coefficients. This matrix looks suspiciously similar to the DFT matrix, so hopefully you can compute the matrix-vector product in time $O(n\log n)$.


Q:

Как заставить группу setInterval работать синхронно?

 this.fade = function (t, f){
    var t = t || 500;
    var f = f || 50;
    var steps = t / (1000 / f);
    var op = 1;
    var d0 = 1 / steps;
    this.elements.forEach((e)=>{var timer = setInterval(function(){
        var current = timer;
        op -= d0;
        // устанавливаем opacity элементу DOM
        e.style.opacity = op;
        // уменьшаем количество оставшихся шагов анимации
        steps--;

        // если анимация окончена
        if(e.style.opacity <= 0){
        // убираем интервал выполнения
            clearInterval(current);
            // и убираем элемент из потока документа
            e.style.display = 'none';
        }

    }, 1000)});

};

код аналогичен fade jquery, только вот работает асинхронно(элементы исчезают не одновременно). Как задать setInterval чтобы они все работали синхронно?

A:

Попробуйте так:
this.fade = function (t, f){
    var t = t || 500;
    var f = f || 50;
    var steps = t / (1000 / f);
    var op = 1;
    var d0 = 1 / steps;

    var timer = setInterval(() => {
        op -= d0;

        this.elements.forEach((element) => {
            e.style.opacity = op;

            if(op <= 0){
                clearInterval(timer);
                e.style.display = 'none';
            }
        });
    }, 1000);
};


Q:

How to count the number of digits of an integer in python3 with recursion.Cannot convert int to str and cannot use loops

Needs to return the number of digits in an integer using recursion.NO LOOPS and cannot use str function either.I have the general case but i need help with the base case:
    def count(x):
       x=abs(x)
      #general case
      if x<10:
       return 1
      #base case

    x=123
    print(count(x))

A:

you are on the right track, so when its less than 10 you know that its a single digit so you can return 1, otherwise its greater than 10 so return 1 + the result of the function passing in x // 10
def count(x):
    if abs(x) > 10:
        return 1 + count(x // 10)
    return 1

for i in (1, 23, 345, 454564, 34, -345, -98):
    print(f'There are {count(i)} digits in the number {i}')

OUTPUT
There are 1 digits in the number 1
There are 2 digits in the number 23
There are 3 digits in the number 345
There are 6 digits in the number 454564
There are 2 digits in the number 34
There are 3 digits in the number -345
There are 2 digits in the number -98


Q:

Do all ultimates charge at the same speed?

Lately I have been playing a lot as Tracer and noticed my ultimate charges faster than other characters. Do all ultimates charge at the same speed, what exactly effects it?

A:

Most of the time, the primary role of the hero, and is he fulfilling  it, is the main ultimate charge booster.
For instance, if you're a Mercy and stay at your spawn your Ultimate will charge quite slowly. if, on the other had you're healing someone who's taking alot of damage, your ultimate will charge much faster.
Also check this thread out. To summarise:
Passive charge rate (from fastest to slowest)

5% charge in approx 4 seconds (mech-less D.VA)
5% charge in approx 7.5 seconds (Symmetra)
5% charge in approx 8.5 seconds (Tracer)
5% charge in approx 9 seconds (Mei, Widowmaker, Mercy)
5% charge in approx 10 seconds (Roadhog, Reinhardt)
5% charge in approx 12 seconds(Genji, McCree, Hanzo, Junkrat, Torbjorn, D.VA, Reinhardt, Winston)
5% charge in approx 15 seconds (Pharah, Reaper, Soldier 76, Bastion,
Zarya, Lucio, Zenyatta)

And now for how much heroes charge for damaging enemies (from highest to lowest):

60% charge for 200 damage (mech-less D.VA)
25% charge for 200 damage (Symmetra)
22% charge for 200 damage (Tracer) 20% charge for 200 damage (Mei, Widowmaker)
18% charge for 200 damage (Winston, Roadhog, Reinhardt)
16% charge for 200 damage (Genji, McCree, Hanzo, Junkrat, Torbjorn, D.VA)
14% charge for 200 damage (Pharah, Reaper, Soldier 76, Bastion, Zarya)
12% charge for 200 damage (Zenyatta)
10% charge for 200 damage (Lucio)


Q:

Can Java system clipboard copy a file?

I've used Java system clipboard to transfer text and image, but I wonder if it can copy and paste files ? If so where can I find some sample code ?
I found a similar question at : How can I copy a file and paste it to the clipboard using Java?
But nowhere in it can I find the word "clipboard", and I don't know how to use it.
The methods I use to copy image look like this :
  public static void setClipboard(Image image)                                           // This method writes a image to the system clipboard : from exampledepot.com
  {
    ImageSelection imgSel=new ImageSelection(image);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel,null);
  }

  public Image getImageFromClipboard()                                                   // Get an image off the system clipboard
  {
    Transferable transferable=Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    if (transferable!=null&&transferable.isDataFlavorSupported(DataFlavor.imageFlavor))
    {
      try { return (Image)transferable.getTransferData(DataFlavor.imageFlavor); }
      catch (UnsupportedFlavorException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
    }
    else System.err.println("getImageFromClipboard: That wasn't an image!");
    return null;
  }

How to modify the above code to transfer files ?

A:

Essentially, yes.  You need to remember that both the drag'n'drop API and the clipboard API use the same concept of a Transferable, which wraps the data into DataFlavors, so you can transfer the data differently based on the flavor the target system would like to use
Generally, when transferring files, Java uses a java.util.List and a DataFlavor.javaFileListFlavor.  Unfourtantly, there's no nice "wrapper" class available for this, so you'll need to provide your own, for example...
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        File file = new File("/path/to/your/file");
        List listOfFiles = new ArrayList();
        listOfFiles.add(file);

        FileTransferable ft = new FileTransferable(listOfFiles);

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ft, new ClipboardOwner() {
            @Override
            public void lostOwnership(Clipboard clipboard, Transferable contents) {
                System.out.println("Lost ownership");
            }
        });
    }

    public static class FileTransferable implements Transferable {

        private List listOfFiles;

        public FileTransferable(List listOfFiles) {
            this.listOfFiles = listOfFiles;
        }

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.javaFileListFlavor};
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return DataFlavor.javaFileListFlavor.equals(flavor);
        }

        @Override
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            return listOfFiles;
        }
    }

}

In my tests, I was able to place a File in the List, wrap into a Transferable, pass it to the Clipboard and was able to paste the file through the system (Windows Explorer)


Q:

java URLConnection - how to read data from URLs containing uppercase?

https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html has an example with:
URL oracle = new URL("http://www.oracle.com/");

that works fine, but if the URL has uppercase, like https://file-examples.com/wp-content/uploads/2017/08/file_example_PPT_250kB.ppt
then get error about URL not exists (and there is https://file-examples.com/wp-content/uploads/2017/08/file_example_ppt_250kb.ppt in the stack trace)

A:

URL/filename.fileformate in this filename is case sensitive you have to manage tolowercase  when you create it


Q:

Does someone destroyed by a God of Destruction leave a ghost?

If someone gets destroyed by a Hakai, does he/she leave a ghost or is that obliterated alongside him/her?

A:

I think this is already in its wikia page.

As Gods of Destruction, they possess the power to destroy almost anything with little effort, even intangible beings such as souls. People destroyed by Hakai do not go to Other World and simply cease to exist. However, in the manga, Beerus admits that Hakai does not work against people who are immortal.

Since the Other World is their equivalent to our afterlife where presumably, our ghost or spirit goes after death, then yes, Hakai can destroy someone including his/her ghost/spirit.
The technique however,

can be controlled by the user in moderation to not fully destroying the victim.

There are also a lot of variations of the said technique.


Q:

How to balance a character that stole enemy pets?

Me and my players are running Hoard of the Dragon Queen and we just reached the dragon hatchery. One of my dragonborn players reached the Drake Nursery. Through some Animal Handling check, the ability to speak Draconic, and two natural 20s, he was able to convince the Guard Drakes that he was an ally of theirs, and now he has two pet guard drakes.
And in short, I have no idea how to run what are essentially animal companions for a rogue.
How am I supposed to run the creatures in terms of initiative? What action should my player take to command them? What type of commands can he/can't he make? What check should he make to keep them inline? And most importantly, should he even have these "animal companions" despite the fact that he's a rogue?

A:

Good for your player -- he's recruited some temporary NPCs to help the group out!
Your header question asks how to "balance" this, but there's not a need for balance considerations since these NPCs are temporary.  Your player will need to keep making checks to keep the guard drakes on his side.
You should have the guard drakes act on your rogue player's turn, for simplicity.  You might assign your rogue player to run the guard drakes, or you might run them yourself to emphasize to the group that the guard drakes are temporary allies who make decisions for themselves and don't blindly obey.
At the start of each battle, your player might need to make an Animal Handling check to convince the guard drakes to attack.  If the opponent is something the guard drakes would naturally want to attack, the check might be very easy, or no check might be required; if the opponent is something the guard drakes consider an ally, the check might be very difficult, and failure would likely mean the guard drakes attack your player.
Unfortunately for your player, most of the creatures in this area are creatures the guard drakes might consider to be allies.  Kobolds are tending to the dragon eggs in this area, and the guard drakes know that the kobolds are their allies.  Cultists are humans, but they're members of a dragon cult and they speak draconic, so the guard drakes probably won't attack those without some persuasion.  The guard drakes might be willing to attack some of the human guards and berserkers in the area, though.
For the long term, it's probably best if you rule that the guard drakes won't leave this cave.  Their job is to guard those dragon eggs, after all.  And they're going to want to sleep in their nest, not on a bunch of dirt in the forest.  This will ensure that the guard drakes don't somehow become permanent allies of the group.

A:

You Don't.
Why balance something that is already balanced? Even with a Nat20, these Guard Drake "pets" aren't going to be 100% loyal to your Rogue. I recommend treating them somewhat like an Awakened animal/plant.

The awakened beast or plant is Charmed by you for 30 days or until you and your companions do anything harmful to it. When the Charmed condition ends, the awakened creature chooses whether to remain friendly to you, based on how you treated it while it was Charmed.

The key difference you should consider is this: the Guard Drake is NOT Awakened, which means it is not Charmed. Since it is not Charmed, during the 30 Day period, you should have your player roll Animal Handling every time the Guard Drakes would have reason to suspect the party was not actually their ally. These events could be anything from treating the Guard Drakes poorly, doing something the Drakes would vehemently oppose, and so forth. After 30 days, if they can keep the Guard Drakes believing they are allies, I'd say your party earned the new allies. Treat them as you would an animal companion under the authority of your Rogue. If they want to try and specialize for better control, all power to them, but as things are, there is no reason why the Guard Drakes can't walk off or even become hostile if the ruse isn't well-maintained.


Q:

Only rendering 3 items inside FlatList

I want to render only 3 of my items inside a FlatList. Latter when I click the text new item will be rendered.
here is the example code:
export default class FlatListBasics extends Component {
renderNewItem = () => {
// do something here
}
      render() {
        return (
          <View style={styles.container}>
            <FlatList
              data={[
                {key: 'Devin'},
                {key: 'Jackson'},
                {key: 'James'},
                {key: 'Joel'},
                {key: 'John'},
                {key: 'Jillian'},
                {key: 'Jimmy'},
                {key: 'Julie'},
              ]}
              renderItem={({item}) => <Text onPress={this.renderNewItem}>{item.key}</Text>}
            />
          </View>
        );
      }

So how I can achieve this?
        }

A:

You can use Array.prototype.slice() to control amount of the data rendered. Set a count in your state and then add 1 to it every time you pressed the button. This way you are not dependent on how do you load your data. You can either use a local data source or a remote one with an API. Another key point is to add a keyExtractor so the re-render will be more performance.
Example
const data = [
  {key: 'Devin'},
  {key: 'Jackson'},
  {key: 'James'},
  {key: 'Joel'},
  {key: 'John'},
  {key: 'Jillian'},
  {key: 'Jimmy'},
  {key: 'Julie'},
];
class FlatListBasics extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemsCount: 3
    };
  }
  renderNewItem = () => {
    if (this.state.itemsCount < data.length) {
      this.setState((prevState) => ({ itemsCount: (prevState.itemsCount + 1) }));
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={data.slice(0, this.state.itemsCount)}
          keyExtractor={(item, index) => item.key;}
          renderItem={({ item }) => <Text onPress={this.renderNewItem}>{item.key}</Text>}
        />
      </View>
    );
  }
}


Q:

Qual a diferença em usar ModelAndView e ResponseEntity?

Me deparei com essas duas classe, achei a função delas bem iguais.
Quais são as diferenças entre elas e quando é o momento de usar uma específica?

A:

ResponseEntity: significa representar toda a resposta HTTP. Você pode controlar qualquer coisa que aconteça: código de status, cabeçalhos e corpo.

Trabalhando com microservice, ResponseEntity para enviar resposta
  completa, com status, com cabeçalho e corpo.

ModelAndView: essa classe é utilizada para especificar a view que será renderizada e quais os dados ela utilizará para isso.

ModelAndView padrão MVC.

Espero ter ajudado


Q:

Play Framework Json Serialization Failure

I have an implicit Json reads and writes as below:
  implicit val userJsonWrites = new Writes[User] {
    override def writes(user: User): JsValue = Json.obj(
      idKey -> Json.toJson(user._id),
      firstNameKey -> Json.toJson(user.firstName),
      lastNameKey -> Json.toJson(user.lastName),
      emailKey -> Json.toJson(user.email),
      //passKey -> Json.toJson(user.pass),
      addressKey -> Json.toJson(user.address),
      createDateKey  -> Json.toJson(user.createDate),
      activateDateKey  -> Json.toJson(user.activateDate),
      isUserActivatedKey -> Json.toJson(user.isUserActivated),
      verificationDateKey  -> Json.toJson(user.verificationDate)
    )
  }

  implicit val userJsonReads = new Reads[User] {
    override def reads(json: JsValue): JsResult[User] = {
      val user = User(
        _id = (json \ idKey).as[Option[String]],
        firstName =  (json \ firstNameKey).as[String],
        lastName =  (json \ lastNameKey).as[String],
        email =  (json \ emailKey).as[String],
        pass =  (json \ passKey).as[String],
        address = (json \ addressKey).as[Address],
        createDate =  (json \ createDateKey).as[DateTime],
        activateDate =  (json \ activateDateKey).as[Option[DateTime]],
        verificationDate =  (json \ verificationDateKey).as[Option[DateTime]],
        isUserActivated = (json \ isUserActivatedKey).as[Boolean]
      )

      JsSuccess(user)
    }
  }

When I compile, I get the following failures:
Error:(84, 32) not enough arguments for method as: (implicit fjs: play.api.libs.json.Reads[Option[String]])Option[String].
Unspecified value parameter fjs.
        _id = (json \ idKey).as[Option[String]],
                               ^
Error:(84, 32) No Json deserializer found for type Option[String]. Try to implement an implicit Reads or Format for this type.
        _id = (json \ idKey).as[Option[String]],
                           ^

My User object looks like this:
case class User(
  _id: Option[String],
  createDate: DateTime,
  activateDate: Option[DateTime],
  verificationDate: Option[DateTime],
  email: String,
  pass: String,
  firstName: String,
  lastName: String,
  isUserActivated: Boolean,
  address: Address
)

The _id is actually the MongoDB's ObjectId which I had to have as an Option!

A:

Use asOpt, see documentation
It should look like;
...
_id = (json \ idKey).asOpt[String]


Q:

foreach loop highlight cells from database

I'm wondering if my code could be easier with a foreach loop. my code thusfar:
the purpose is to read the values in the MYSQL table, and if the anwser is "NEE" display the background color in RED. my code works but it is very long..
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is
the password
mysql_select_db('heijsDB');

$query = "SELECT * FROM hygieneaanvoer"; //You don't need a ; like you do in
SQL
$result = mysql_query($query);

//List the Columns for the Report
if(! $result ) {
           die('Could display data: ' . mysql_error());
        }

echo "

<fieldset>hygiëne/GMP aduit Aanvoer</fieldset>

Datum
Controleur
controleur
Revisie
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

";
while($row = mysql_fetch_array($result))
{
 echo "
";
echo "" . $row['datum'] . "	";
 echo "" . $row['controleur'] . "	";
  echo "" . $row['codering'] . "	";
 echo "" . $row['revisie'] . "	";
 if($row['q1']=='NEE') // [val1] can be 'approved'
     echo "".$row['q1']."	";
else echo "".$row['q1']."	";
    if($row['q2']=='NEE') // [val1] can be 'approved'
     echo "".$row['q2']."	";
else echo "".$row['q2']."	";
if($row['q3']=='NEE') // [val1] can be 'approved'
     echo "".$row['q3']."	";
else echo "".$row['q3']."	";
if($row['q4']=='NEE') // [val1] can be 'approved'
     echo "".$row['q4']."	";
else echo "".$row['q4']."	";
if($row['q5']=='NEE') // [val1] can be 'approved'
     echo "".$row['q5']."	";
else echo "".$row['q5']."	";
if($row['q6']=='NEE') // [val1] can be 'approved'
     echo "".$row['q6']."	";
else echo "".$row['q6']."	";
if($row['q7']=='NEE') // [val1] can be 'approved'
     echo "".$row['q7']."	";
else echo "".$row['q7']."	";
if($row['q8']=='NEE') // [val1] can be 'approved'
     echo "".$row['q8']."	";
else echo "".$row['q8']."	";
if($row['q9']=='NEE') // [val1] can be 'approved'
     echo "".$row['q9']."	";
else echo "".$row['q9']."	";
if($row['q10']=='NEE') // [val1] can be 'approved'
     echo "".$row['q10']."	";
else echo "".$row['q10']."	";
if($row['q11']=='NEE') // [val1] can be 'approved'
     echo "".$row['q11']."	";
else echo "".$row['q11']."	";
if($row['q12']=='NEE') // [val1] can be 'approved'
     echo "".$row['q12']."	";
else echo "".$row['q12']."	";
if($row['q13']=='NEE') // [val1] can be 'approved'
     echo "".$row['q13']."	";
else echo "".$row['q13']."	";
if($row['q14']=='NEE') // [val1] can be 'approved'
     echo "".$row['q14']."	";
else echo "".$row['q14']."	";
if($row['q15']=='NEE') // [val1] can be 'approved'
     echo "".$row['q15']."	";
else echo "".$row['q15']."	";
 echo "
";
 }
echo "
";

   ?>

A:

Here is solution

$result = mysql_query("SELECT * FROM hygieneaanvoer")or die('Could display data: ' . mysql_error());;

echo "

<fieldset>hygiëne/GMP aduit Aanvoer</fieldset>

Datum
Controleur
controleur
Revisie	";

for ($i=1;$i<=15;$i++){
    echo ''.$i.'	';
}
echo "
";
while($row = mysql_fetch_array($result))  {
    echo "
";
    echo "" . $row['datum'] . "	";
    echo "" . $row['controleur'] . "	";
    echo "" . $row['codering'] . "	";
    echo "" . $row['revisie'] . "	";
    for ($j=1;$j<=15;$j++){
        echo "".$row['q'.$j]."	";
    }
    echo "
";
}
echo "
";

?>


Q:

What kind of hash function can give me a 32 bit value from a string?

I'm using the QT framework so if there is something like this implemented in that, I would use it, but I couldn't find it.
I would like to get random color values for variable length strings.

A:

If you include <QHash>, then you get overloads of the function qHash(), one of which is:
uint qHash(const QString & key)


Q:

Prevent Listbox Duplicates

Okay, newbie question here. I'm creating a random key generator which will generate keys from a string, and add each key combination to a Listbox. My question is how would I be able to prevent duplicates from appearing/being added to the listbox thus preventing duplicate keys. Currently the key is generated into 5 separate sections and is then (crudely) brought together into an invisible textbox for temp storage before it's added into the listbox1.
  generatetextonlycode = strName

    TextBox1.Text = Key1.Text & "-" & Key2.Text & "-" & Key3.Text & "-" & Key4.Text & "-" & Key5.Text`

I know this is a really bad way to go about it, but it's easy and works -- Only it is prone to duplicates ;( This code obviously will go into a Loop statement once it works. Here's the full thing:
Private Sub Generatebtn_Click(sender As Object, e As EventArgs) Handles Generatebtn.Click
    Key2.Text = generatetextonlycode()
    Key3.Text = generatetextonlycode()
    Key4.Text = generatetextonlycode()
    Key5.Text = generatetextonlycode()
End Sub

Public Function generatetextonlycode() As Object
    Dim intRnd As Object
    Dim strName As Object
    Dim intNameLength As Object
    Dim intLenght As Object
    Dim strInputString As Object
    Dim inStep As Object

    strInputString = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    intLenght = Len(strInputString)

    intNameLength = 5

    Randomize()

    strName = ""

    For inStep = 1 To intNameLength

        intRnd = Int((intLenght * Rnd()) + 1)

        strName = strName & Mid(strInputString, intRnd, 1)

    Next

    generatetextonlycode = strName

    TextBox1.Text = Key1.Text & "-" & Key2.Text & "-" & Key3.Text & "-" & Key4.Text & "-" & Key5.Text

    '
    '
    'THIS IS WHERE I'D LIKE TO ADD THE CONTENTS OF Textbox1 INTO Listbox1 IF THE LISTBOX DOESNT ALREADY CONTAIN THE KEY!
    '
    '

End Function

(Note that Key1.text contains a static value so that all keys start of the same. I'm using visual basic with .net 4.5)

A:

Use the list box's Contains() method to test if the value is already in the list box or not, like this:
If Not listBox1.Items.Contains(TextBox1.Text) Then
    ' It is not already in the list box so add it
    ListBox1.Items.Add(TextBox1.Text)
End If

A more efficient approach is to use a .NET collection that does not allow duplicates (i.e. HashSet<T>).
Per MSDN:

The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

Note: HashSet<T>.Add() method returns a Boolean (True if the item was added to the collection and False if the item is already present).
So your code could be this:
Dim theValues As New HashSet(Of String)
Dim success As Boolean = theValues.Add(TextBox1.Text)

' Was the addition of the string successful or not?
If success Then
    ' Yes, so re-bind the list box
End If


Q:

Photo Upload in ASP.NET

I have an image box and a Photo Upload control with a Save button. I need to upload an image into the Image Box.
When I click the Upload button, it should show the Image in the Image Box.
When I click the Save button, the path of the uploaded image should be saved in the database.
My issue is the photo gets uploaded, but only after I click the Upload button for the second time.
P.S. I use a Client side function for uploading the photo.
Following are my codes.
CLIENT SIDE FUNCTION FOR UPLOADING THE PHOTO
function ajaxPhotoUpload() {

        var FileFolder = $('#hdnPhotoFolder').val();
        var fileToUpload = getNameFromPath($('#uplPhoto').val());

        var filename = fileToUpload.substr(0, (fileToUpload.lastIndexOf('.')));
        alert(filename);
        if (checkFileExtension(fileToUpload)) {

            var flag = true;
            var counter = $('#hdnCountPhotos').val();

            if (filename != "" && filename != null && FileFolder != "0") {
                //Check duplicate file entry
                for (var i = 1; i <= counter; i++) {
                    var hdnPhotoId = "#hdnPhotoId_" + i;

                    if ($(hdnPhotoId).length > 0) {
                        var mFileName = "#Image1_" + i;

                        if ($(mFileName).html() == filename) {
                            flag = false;
                            break;
                        }

                    }
                }
                if (flag == true) {
                    $("#loading").ajaxStart(function () {
                        $(this).show();
                    }).ajaxComplete(function () {
                        $(this).hide();
                        return false;
                    });

                    $.ajaxFileUpload({
                        url: 'FileUpload.ashx?id=' + FileFolder + '&Mainfolder=Photos' + '&parentfolder=Student',
                        secureuri: false,
                        fileElementId: 'uplPhoto',
                        dataType: 'json',
                        success: function (data, status) {

                            if (typeof (data.error) != 'undefined') {
                                if (data.error != '') {
                                    alert(data.error);
                                } else {

                                    $('#hdnFullPhotoPath').val(data.upfile);
                                    $('#uplPhoto').val("");
                                    $('#<%= lblPhotoName.ClientID%>').text('Photo uploaded successfully')
                                }
                            }

                        },
                        error: function (data, status, e) {
                            alert(e);
                        }
                    });
                }

                else {
                    alert('The photo ' + filename + ' already exists');
                    return false;
                }
            }
        }
        else {
            alert('You can upload only jpg,jpeg,pdf,doc,docx,txt,zip,rar extensions files.');
        }
        return false;

    }

PHOTO UPLOAD CONTROL WITH SAVE BUTTON AND IMAGE BOX

    <asp:Image ID="Image1" runat="server" Height="100px" Width="100px" ClientIDMode="Static" />
                <asp:FileUpload ID="uplPhoto" runat="server" ClientIDMode="Static"/>
                <asp:Label ID="lblPhotoName" runat="server" Text="" ForeColor ="Green" ClientIDMode="Static"></asp:Label>
<asp:Button id="btnSave" runat="server" Text="Upload Photograph" onClick="btnSave_Click"  OnClientClick="return ajaxPhotoUpload();"/>

SAVE BUTTON CLICK EVENT IN SERVER SIDE (to show the uploaded image in the image box)
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
    Image1.ImageUrl = hdnFullPhotoPath.Value

End Sub

A:

All, thanks for your time and help.! The tilde(~) symbol was the issue - the file's path wasn't recognized. So I modified my code to replace it with empty space.
var orgpath = data.upfile;
var photopath = orgpath.replace('~/', '');
$('#<%= ImgFacultyPhoto.ClientID%>').attr('src', photopath);


Q:

How can I parse a Date from a string and keep it in its format?

I have this code to convert a string to a date. but the resulting date is always in another format.
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        try {
            String dateString  = "18/01/2013 11:59";
            dateTest = format.parse(dateString);
            System.out.println(dateTest); //output: Tue Jan 18 11:59:00 GMT 2013
           }

How can I make it so that dateTest is in the same format as the original?

A:

Format the date using the same SimpleDateFormat you used to parse it.

A:

This
System.out.println(format.format(dateTest));

will do the job. You can use the format() method of your SimpleDateFormat to format the output the same way your input should be.


Q:

Xcode Designer: How Do I Create 2 Sliding Selector Controls?

Hi,I want to list for ex. speechers in an organization. Let's say a schedule. I've seen a couple apps in AppStore and liked this most. How do we create such controls? Like select the date then the place of speech. Those two don't have to be dependent.I couldn't see a control like this in Xcode designer.Thanks in advance.

A:

You would have to write your own control. Something like that could be a UIScrollView set to paging mode that gets its 3D effect from some neatly positioned gradients. Interface Builder won't help you much (if at all) with this task.


Q:

iPhone UIScroll Fixed Background Not Working

I have an iPhone app where I have a view and following hierarchy.
View
   ImageView
   ScrollView
      OtherItems

I have ImageView background set to an image and ScrollView color to clearColor but still the background is white in simulator and iphone both. Why is that so? Although I can see the background in the IB.

A:

I restarted XCode and it worked!


Q:

MySQL Query for finding distinct values in columns and getting the sum

I am having few Movie DVDs and want to create a simple database in MySQL. PF the DB structure. Am having a MySQL query which actually doesn't list out the exact no. of movies I am having. The query below is -
SELECT SUM(Total) as total
FROM (
SELECT COUNT(DISTINCT(Movie1)) AS Total FROM tbl_movie
      WHERE Movie1 !='' AND Movie1 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie2)) FROM tbl_movie
       WHERE Movie2 !='' AND Movie2 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie3)) FROM tbl_movie
       WHERE Movie3 !='' AND Movie3 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie4)) FROM tbl_movie
       WHERE Movie4 !='' AND Movie4 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie5)) FROM tbl_movie
       WHERE Movie5 !='' AND Movie5 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie6)) FROM tbl_movie
       WHERE Movie6 !='' AND Movie6 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie7)) FROM tbl_movie
       WHERE Movie7 !='' AND Movie7 IS NOT NULL AND DVDCategory='Movie'
) AS Total;

DB Structure -
ID DVD Movie1   Movie2   Movie3      Movie4          Movie5   Movie6   Movie7
__________________________________________________________________
1  1  IronMan  Movie11   MindHunters  300            Jumper   7
2  2  IronMan2 Movie22   Grey         Blood Diamond
3  3  Movie33  Red Eye   Departed     300
4  4  Movie44  Gladiator King Kong
5  5  Movie55  Hitman

It shows 13 results instead of 18 movies in DB. I searched your list of questions, but didn't find any suitable answer. Could you convey where am I going wrong or is there any better way I can arrange this query?

A:

Update -
You are going wrong with the UNION. It removes duplicates. Your inner queries are returning (5,5,4,2,1,1,0) but the union turns them into (5,4,2,1,0) after removing duplicates.
You need to use UNION ALL to count everything. Just replace all UNIONs with UNION ALL
When you do, you will notice that if there are movies across columns i.e. if movie 300 was in column Movie4 and Movie5 for different users, it will count twice.
If you need to just get the distinct movies across all columns, get distinct movies from individual columns first, UNION them to remove duplicates and then count movies.
SELECT COUNT(movie) as total
FROM (
SELECT DISTINCT Movie1 AS movie FROM tbl_movie
    WHERE Movie1 !='' AND Movie1 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie2 FROM tbl_movie
    WHERE Movie2 !='' AND Movie2 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie3 FROM tbl_movie
     WHERE Movie3 !='' AND Movie3 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie4 FROM tbl_movie
     WHERE Movie4 !='' AND Movie4 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie5 FROM tbl_movie
     WHERE Movie5 !='' AND Movie5 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie6 FROM tbl_movie
     WHERE Movie6 !='' AND Movie6 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie7 FROM tbl_movie
     WHERE Movie7 !='' AND Movie7 IS NOT NULL AND DVDCategory='Movie'
) AS AllDistinctMovies;


Q:

how to bind ArrayList to JList

i have a JList and an ArrayList.How to bind the datas in arraylist to the jlist.Are the any alternative methods?
    ArrayList arl = new ArrayList();
    arl.add("1asdsd");
    arl.add("2asdsd");
    arl.add("3asdsd");
    Object obj = arl.clone();
    JList list = new JList(obj);

how to bind the above code.Now the code give an error.

A:

You don't need to clone the ArrayList. Just call toArray()
JList list = new JList(arl.toArray());

A:

ArrayList<String> aList = new ArrayList<String>();
aList.add("blabla");
aList.add("blublu");
aList.add("blibli");
aList.add("bleble");
DefaultListModel<String> model = new DefaultListModel<String>();
for(String s:aList){
    model.addElement(s);
}
JList<String> contactList = new JList<String>(model);

Advantage of this is that you can later add/remove elements to already instantiated JList by adding elements to model using methods addElement(Obj o) and removeElement(Obj o).

A:

JList jList = new JList(arrayList.toArray());


Q:

Trying to Sort in Java 8 with Nulls in the Data

I am trying to sort a list that I get by the comparator given. I am passing the comparator through the NullsLast method to get a Null-Friendly version of my comparator like the JavaDoc states. However, when I run the code I am still getting a Null Pointer Exception when I pass a String comparator to the method.
private <T> void sortWithDirection(List<T> details, boolean isAscending, Comparator<T> comparator){

    if(isAscending){
        details.sort(Comparator.nullsLast(comparator));
    } else {
        details.sort(Comparator.nullsLast(comparator.reversed()));
    }
}

List<UserDTO> users = new ArrayList<>();
sortWithDirection(users, false, Comparator.comparing(UserDTO::getName));

Am I using this method wrong? Is there a different way that I can prevent NPEs without removing them from the result set?

A:

nullsLast will handle the case of UserDTO being null.  It will not save you from getName returning null.  To handle null names, you would need to apply nullsLast before comparing:
details.sort(comparing(
    UserDTO::getName,
    nullsLast(naturalOrder())
));

or, for reverse order:
details.sort(comparing(
    UserDTO::getName,
    nullsLast(reverseOrder())
));


Q:

Replacing inner div content?

I'd like to replace the following inner div content:

$37

with this:
$37 $19

The $37 gets striked through and the new price is displayed next to it.  The above
 is generated dynamically.
I have tried the following but it isn't doing anything:
$( "div.price" ).replaceWith("$37 $19");

I'm trying this in jquery but is there a way to do it in angular?  I guess the issue with angular is that I can't add directives to the above code.

A:

run the code on document ready
// Code goes here
$(function(){
$( "div.price" ).html("$37 $19")
});


Q:

Serial import python

I"m trying to use pyserial.  When I do the following script.
import serial
ser= serial.serial("COM5", 9600)
ser.write("Hello worldn")
x = ser.readline()
print(x)

Error code:
c:\Python27>python com.py
Traceback (most recent call last):
  File "com.py", line 2, in <module>
    ser= serial.serial("COM5", 9600)
AttributeError: 'module' object has no attribute 'serial'

I read a suggestion and changed it to:
from serial import serial
ser= serial.serial("COM5", 9600)
ser.write("Hello worldn
x = ser.readline()
print(x)

I now get the error
c:\Python27>python com.py
Traceback (most recent call last):
  File "com.py", line 1, in <module>
    from serial import serial
ImportError: cannot import name serial

I read that this can be from having ini in your module, but dont' know anyting about this.
I printed my sys.path and pyserial is in there.
['C:\\Users\\Jeff\\Desktop', 'C:\\Python27\\lib\\site-packages\\distribute-0.6.4
9-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\pyserial-2.7-py2.7.egg', 'C:\\W
indows\\SYSTEM32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\
\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Pyt
hon27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11
-py2.7.egg-info']

Getting kind of annoyed :(...  Thanks for help.

A:

It should be:
import serial
ser = serial.Serial("COM5", 9600)

Note the capital 'S' in serial.Serial


Q:

Example in Measure theory about Borel Measures

I need to show that there are distinct $\sigma$-finite measures in $B(\mathbb{R})$ that are the same in the open sets. Im not really seeing a good example cause every open set is a countable union of compact sets, so the sum has to be the same , but they have to interchange themselves. Any help is appreciated.

A:

For a real number $x\in\mathbb R$ take $\mu_x(A)=\int_{A}\frac{\mathrm dt}{t^2}+x\delta_0(A)$
Then, $\mathbb R=\{0\}\cup \bigcup_n\left(]-\infty,-\frac1n[\cup]\frac1n,+\infty[\right)$ and each subset has finite measure so $\mu_x$ is $\sigma$-finite.
Also it is clear that every $\mu_x$ has the same value on an open set which does not contain $0$, and is infinite as soon as $0$ is in the open set, so that all $\mu_x$ coincide on all open subsets but are not equal.
Thank you Kavi Rama Murthy for noticing me that my former answer was wrong.

A:

I think i found an example.
If we consider $\mu(A) = \# (\mathbb{Q} \cap A)$ and $\nu(A) = \# (A \cap(\mathbb{Q}\cup  \sqrt{2}))$.


Q:

Can only send email via Outlook if Outlook is open

I want to use send emails via Outlook as described here. It works fine as long as I have already opened Outlook. So for example if Outlook is minimized and I execute my code, then I can send an email just fine. But if Outlook is closed, then I get an exception:
{System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
   at Microsoft.Office.Interop.Outlook._MailItem.get_Recipients()
   at OutlookExample.Form1.btnSendEmail_Click(Object sender, EventArgs e) in C:\Users\abc\Documents\Visual Studio 2008\Projects\OutlookExample\OutlookExample\Form1.cs:line 28}

Here is the code:
using Outlook = Microsoft.Office.Interop.Outlook;

...

private void btnSendEmail_Click(object sender, EventArgs e)
{
    try
    {
        Outlook.Application oApp = new Outlook.Application();
        Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
            oMsg.HTMLBody = "Hello, here is your message!";
            oMsg.Subject = "This is a test message";
            Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
            Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("rhr@sonlinc.dk");
            oRecip.Resolve();
            oMsg.Send();
            oRecip = null;
            oRecips = null;
            oMsg = null;
            oApp = null;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Why doesn't this work?
Edit: Here is the solution
using Outlook = Microsoft.Office.Interop.Outlook;

...

private void btnSendEmail_Click(object sender, EventArgs e)
{
    try
    {
        Outlook.Application oApp = new Outlook.Application();

        // These 3 lines solved the problem
        Outlook.NameSpace ns = oApp.GetNamespace("MAPI");
        Outlook.MAPIFolder f = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
        System.Threading.Thread.Sleep(5000); // test

        Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
            oMsg.HTMLBody = "Hello, here is your message!";
            oMsg.Subject = "This is a test message";
            Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
            Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("rhr@sonlinc.dk");
            oRecip.Resolve();
            oMsg.Send();
            oRecip = null;
            oRecips = null;
            oMsg = null;
            oApp = null;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

A:

The following code has reliably worked for months for me:
            app = new Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI");
            f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
            Thread.Sleep(5000); // a bit of startup grace time.

if outlook was open it uses it, if not its opened it. Of course, if your outlook requires you to login, your code wont allow for that. Some systems make it difficult for you to auto login.

A:

I didn't like the idea to use Thread.Sleep for 5 seconds, so I've found another solution, that worked for me:
All you need is get Inspector object for newly created MailItem
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMsg.GetInspector;

Answer was published in Google groups originally for Outlook 2007 (but it worked for me with Outlook 2010)


Q:

Manual focus in Nikon Coolpix P7100

Is it possible to focus manually with Nikon Coolpix P7100?
I put my camera on a tripod and tried to make photos of full moon this night, however the camera is unable to find focus on the Moon and all my photos off-focus.

A:

According to the manual, page 2 of the reference section (heading: 'Taking Pictures with Manual Focus') this is possible.
This is the relevant page from the manual:


Q:

How to listen for HTTP events in backbone

A complete backbone noob question.
I was wondering, is there a way to listen to HTTP-POST events in backbone?
Lets say, when an API user does a POST request using wget from the command line I would like to update my view. I looked at the API docs and I tried the request option but had no luck. Basically in my view I am trying something like this:
this.listenTo(this.collection, 'request', this.render);
PS: I have the function definition of this.render in my code

A:

I'm just going to extend on @Yaroslav's answer. His answer is totally correct; you cannot explicitly do what you want. Your workflow would have to go something like this:

Client does some action from outside of your webapp (such as a command line POST)
Your server does whatever it was asked to do, but then notifies your client.
Your Backbone view accepts the notification and re-renders (with this.render)

In terms of your server push technology, you have a few different options.

Polling w/ AJAX
Long-polling w/ AJAX
Websockets
Server-Sent Events

All of these are touched upon and explained in this blog post.
A brief summary:
Polling
Polling is when your web app asks your server for new information at a given interval. Ie, every 10 seconds your Backbone application asks if anything new has happened. This can give a max latency of your interval time, and can lead to alot of unnecessary requests
Long polling
Your client always maintains an open request to the server, which is not returned until something happens. At that time, your client can act on the new information, and then makes a new request, which again stays open until new information.
Websockets
Websockets are a bidirectional transport mechanism which enables server->client and client->server messages.
Server Sent Events
Server sent events are a uni-directional transport and part of the HTML5 spec. They allow server->client messages.


Q:

What is the `Cd` command?

I was writing some code, navigating my computer (OSX 10.11.6) via the command line, like I always do, and I made a typo! Instead of typing:
cd USB

I typed
Cd USB

Nothing happened, but it didn't register as an invalid command. Perplexed by this, I did some investigating: I checked the man entry. There was no entry. I found the source file (/usr/bin/Cd) using which Cd, and then cated it:
#!/bin/sh
# $FreeBSD: src/usr.bin/alias/generic.sh,v 1.2 2005/10/24 22:32:19 cperciva Exp $
# This file is in the public domain.
builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}

What is this, and why is it here? How does it relate to freeBSD?
Any help would be amazing, thanks!

A:

macOS uses a case-insensitive filesystem by default[1]
, which can be misleading at times:
which Cd is effectively the same as which cd and which CD in terms of returning the (effectively) same file path.
Confusingly, even though all 3 command refer to the same file, they do so in a case-preserving manner, misleadingly suggesting that the actual case of the filename is whatever you specified.
As a workaround, you can see the true case of the filename if you employ globbing (filename expansion):
$ ls "$(which Cd)"*  # could match additional files, but the one of interest is among them
/usr/bin/cd  # true case of the filename

Bash (the macOS default shell) is internally case-sensitive.
That is, it recognizes cd as builtin cd (its built-in directory-changing command).
By contrast, it does NOT recognize Cd as that, due to the difference in case.
Given that it doesn't recognize Cd as a builtin, it goes looking for an external utility (in the $PATH), and that is when it finds /usr/bin/cd.

/usr/bin/cd is implemented as a shell script, which is mostly useless, because as an external utility it cannot affect the shell's state, so its attempts to change the directory are simply quietly ignored.
(Keith Thompson points out in a comment that you can use it as test whether a given directory can be changed to, because the script's exit code will reflect that).
Matt's answer provides history behind the inclusion of the script in FreeBSD and OSX (which mostly builds on FreeBSD), but it's worth taking a closer look at the rationale (emphasis mine):
From the POSIX spec:

However, all of the standard utilities, including the regular built-ins in the table, but not the special built-ins described in Special Built-In Utilities, shall be implemented in a manner so that they can be accessed via the exec family of functions as defined in the System Interfaces volume of POSIX.1-2008 and can be invoked directly by those standard utilities that require it (env, find, nice, nohup, time, xargs).

In essence, the above means: regular built-ins must (also) be callable stand-alone, as executables (whether as scripts or binaries), nut just as built-ins from within the shell.
The cited regular built-ins table comprises these utilities:
alias bg cd command false fc fg getopts jobs kill newgrp pwd read true umask unalias wait
Note: special built-in utilities are by definition shell-internal only, and their behavior differs from regular built-in utilities.
As such, to be formally POSIX-compliant an OS must indeed provide cd as an external utility.
At the same time, the POSIX spec. does have awareness that at least some of these regular built-ins - notably cd - only makes sense as a built-in:
"Since cd affects the current shell execution environment, it is always provided as a shell regular built-in." - http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cd.html
Among the regular built-in utilities listed, some make sense both as a built-in and as an external utility:
For instance kill needs to be a built-in in order to kill jobs (which are a shell-internal concept), but it is also useful as an external utility, so as to kill processes by PID.
However, among the regular built-in utilities listed, the following never make sense as external utilities, as far as I can tell Do tell me if you disagree
, even though POSIX mandates their presence:
alias bg cd command fc fg getopts jobs read umask unalias
Tip of the hat to Matt for helping to complete the list; he also points that the hash built-in, even though it's not a POSIX utility, also has a pointless script implementation.

[1] As Dave Newton points out in a comment, it is possible to format HFS+, the macOS filesystem, in a case-sensitive manner (even though most people stick with the case-insensitive default). Based on the answer Dave links to, the following command will tell you whether your macOS filesystem is case-insensitive or not:
diskutil info / | grep -iq '^\s*Name.*case-sensitive*' && echo "case-SENSITIVE" || echo "case-INsensitive"

A:

What is this?
The script itself is a portable way to convert a command, even with random upper casing, into the equivalent shell builtin based on the exec paths file name, that is any part of the string after the final / in the $0 variable). The script then runs the builtin command with the same arguments.
As OSX file systems are case insensitive by default, /usr/bin/cd converts running Cd, CD, cD and any form of cd with a / fs path (like /usr/bin/cd) back to the shell builtin command cd. This is largely useless in  a script as cd only affects the current shell it is running in, which immediately closes when the script ends.
How does it relate to freeBSD?
A similar file exists in FreeBSD, which Apple adapted to do case conversion. Mac file systems by default are case insensitive (but case preserving).
The $FreeBSD: src/usr.bin/alias/generic.sh,v 1.2 2005/10/24 22:32:19 cperciva Exp $ header is the source information in the file.
Most of the underlying OSX system comes directly from FreeBSD or was based on it. The Windowing system on top of this and the Cocoa app layer is where OSX becomes truly Apple. Some of the lower level Apple bits have even made it back into FreeBSD like Clang and LLVM compiler.
Why is it here?
The earlier FreeBSD svn commits shed a bit of light:

A little bit more thought has resulted in a generic script which can
  implement any of the useless POSIX-required ``regular shell builtin''
  utilities...

Although most builtins aren't very useful when run in a new shell via a script, this compliance script was used for the commands alias bg cd command fc fg getopts hash jobs read type ulimit umask unalias wait. POSIX compliance is fun!


Q:

When aren't Christoffel symbols symmetrical with respect to bottom indices, and why?

When aren't Christoffel symbols symmetrical with respect to the bottom indices? Why isn't the symmetry of second derivatives true in this case?

A:

Let $\pi:E\rightarrow M$ be an arbitrary vector bundle, not necessarily the tangent bundle $TM$ of $M$. Locally, say over an open subset $U\subset M$, one can choose a family of point-wise linearly independent sections $\{E_i:U\rightarrow E\}$, which is called a local frame in $E$ (over $U$). Then each section $X:U\rightarrow E$ can be uniquely represented in terms of $\{E_i\}$
$$
X=X^i E_i \quad \mbox{(Einstien summation assumed)}
$$
In presence of a connection $\nabla$ in $E$ the covariant derivatives can be computed in terms of the Christoffel symbols of $\nabla$ with respect to the local frame $\{E_i\}$ defined as
$$
\nabla_{E_i}{E_j} = \Gamma^k_{ij} E_k
$$
In general, the Christoffel symbols need not to be symmetric since torsion may not vanish, as noted by the commenters.
For the case of Riemannian manifolds, the Riemannian metric $g$ induces a preferred connection in the tangent bundle which is called the Levi-Civita connection. We prefer this one because it is torsion-free (the torsion tensor $T(X,Y)=\nabla_X Y - \nabla_Y X -[X,Y]$ vanishes) and the metric tensor is parallel w.r.t. to it: $\nabla g =0$.
Connections in the tangent bundle are sometimes termed linear.
In a coordinate patch $(U,x^i)$ we have the standard coordinate frame $\{ \partial_i \}$ (of the tangent bundle) where vector fields $\partial_i$ act as partial derivatives on functions. This implies that a linear connection is torsion-free if and only if the Christoffel symbols with respect to any coordinate frame (!) are symmetric  w.r.t the bottom indices (see J.Lee, Riemannian manifolds. An introduction to curvature, Springer 1987, p.63) (Hint: $[\partial_i, \partial_j]=0)$


Q:

Continue processing in spite of unavailable WCF Service

I have the following code courtesy of an answer posted by Jean-Michel Bezeau
bool isAlive = false;
string fixedAddress = "http://localhost:8732/Design_Time_Addresses/WCFService/mex";
System.ServiceModel.Description.ServiceEndpointCollection availableBindings = System.ServiceModel.Description.MetadataResolver.Resolve(typeof(WCFService.IAlive), new EndpointAddress(fixedAddress));
ChannelFactory<WCFService.IAlive> factoryService = new ChannelFactory<WCFService.IAlive>(availableBindings[0]);
WCFService.IAlive accesService = factoryService.CreateChannel();
isAlive = accesService.IsAlive();

I would like my program to continue even if the WCF Service can't be reached so that I can notify someone via email and add it to a log. I thought of doing it like this:
bool isAlive = false;
try
{
    string fixedAddress = "http://localhost:8732/Design_Time_Addresses/WCFService/mex";
    System.ServiceModel.Description.ServiceEndpointCollection availableBindings = System.ServiceModel.Description.MetadataResolver.Resolve(typeof(WCFService.IAlive), new EndpointAddress(fixedAddress));
    ChannelFactory<WCFService.IAlive> factoryService = new ChannelFactory<WCFService.IAlive>(availableBindings[0]);
    WCFService.IAlive accesService = factoryService.CreateChannel();
    isAlive = accesService.IsAlive();
}
catch {}
finally
{
    if (isAlive)
    {
        //add success message to log
    }
    else
    {
        //add warning message to log
        //send email notification
    }
}

However, I don't like catching all exceptions like that (I know it's bad practice). What's the best way to go about this?
Are there particular exceptions I should be catching? Or, is this a good time to implement a using statement (if so can I have some help with how)?

A:

The exception could be lots of things - it might be just a timeout, or a 404 error, a 500 error, a connection reset error... so there's probably a bunch of exceptions that can be thrown. In this particular case I wouldn't have a problem with a global catch.
You might want to consider retries as well, if it fails the first time try again, in case it was just a timeout.
Alternatively if you already have global error handling on your app, you might not want to  swallow the exception, so you could just use the finally block without the catch:
try
{
    ....
}
finally
{
    ....
}

But you'd only want to do this if it was a genuine error that the app couldn't handle or resolve by itself.


Q:

Display image while dragging

How can i put an image in corner or center of cursor while user dragging an item in ListView or other controls like that?
When you dragging an image or text in Firefox; same thing occurs.

A:

The most effective way I've found is to use the Adorner Layer.
This post shows how: http://blogs.msdn.com/b/marcelolr/archive/2006/03/03/showing-drag-drop-feedback-on-the-wpf-adorner-layer.aspx


Q:

Memory leak in Core Data fetch request with Swift

I've come across a memory leak when I make a Core Data fetch request using Swift. However, I make an almost identical fetch request in a different part of the app, but it doesn't cause a leak. In both cases, the fetch requests are made in viewDidLoad of a view controller, and the results of the fetch request are assigned to an optional property of the view controller.
Here's the method for the fetch request that does not cause any leaks:
class LocationFilter {
    //Lots of other code...
    class func getAllPlacesOfRegionType<T: Region>(regionType: RegionType) -> [T] {
        let fetchRequest = NSFetchRequest(entityName: regionType.rawValue)

        var places: [T]
        do {
            places = try CoreDataStack.sharedInstance.context.executeFetchRequest(
                fetchRequest) as! [T]
        } catch let error as NSError {
            NSLog("Fetch request failed: %@", error.localizedDescription)
            places = [T]()
        }

        places.sortInPlace({ (firstPlace, nextPlace) -> Bool in
            //Ingenious sorting code...
        })

        return places
    }
}

This method is called in viewDidLoad of a viewController, and the result is assigned to the property var allRegions: [Region]? without any leaks. Here's the code:
class PlacesTableViewController: UITableViewController {
    var allRegions: [Region]?
    @IBOutlet weak var segmentedRegions: UISegmentedControl!

    @IBAction func selectRegionSegment(sender: UISegmentedControl) {
        // When the segmented control is tapped, the appropriate list will be loaded.
        switch sender.selectedSegmentIndex {
        case 0:  //Country Segment
            allRegions = LocationFilter.getAllPlacesOfRegionType(RegionType.Country)
        case 1:  //States segment
            allRegions = LocationFilter.getAllPlacesOfRegionType(RegionType.Province)
        case 2:  //Cities segment
            allRegions = LocationFilter.getAllPlacesOfRegionType(RegionType.City)
        case 3:  //Addresses segment
            allRegions = LocationFilter.getAllPlacesOfRegionType(RegionType.Address)
        default:
            break
        }

        // Then reload the cells with animations.
        let index = NSIndexSet(index: 0)
        tableView.reloadSections(index, withRowAnimation: UITableViewRowAnimation.Automatic)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        selectRegionSegment(segmentedRegions)
    }
}

The following method is called in viewDidLoad of a different viewController to set the property var allDays: [Day]!.
class DateFilter {
    //Lots of other code in the class...
    class func getAllDays() -> [Day] {
        let fetchRequest = NSFetchRequest(entityName: "Day")

        let days: [Day]
        do {
            days = try CoreDataStack.sharedInstance.context.executeFetchRequest(
                fetchRequest) as! [Day]
        } catch let error as NSError {
            NSLog("Fetch request failed: %@", error.localizedDescription)
            days = [Day]()
        }

        return days
    }
}

This is where it is called:
class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var allDays: [Day]!

    override func viewDidLoad() {
        super.viewDidLoad()

        allDays = DateFilter.getAllDays()

        let backgroundView = UIView(frame: CGRectZero)
        tableView.tableFooterView = backgroundView
        tableView.backgroundColor = UIColor.groupTableViewBackgroundColor()
    }
}

Xcode instruments detect a memory leak when this is called. Supposedly the responsible library is libswiftFoundation.dylib, and the responsible frame is static Array<A>._forceBridgeFromObjectiveC<A>(NSArray, result:inout [A]?) -> (). When I look at Cycles & Roots, it shows an NSArray at the root, with +16 list: (null) and +24 [no ivar]: (null) branching off.
Am I doing something wrong with how I store the results of my fetch request? Or is this a bug in how Swift interacts with Core Data?
Edit: Tidied up code in accordance with Mundi's suggestion.
Edit 2: Added code that calls the fetch request functions.

A:

After trying lots of things, I'm pretty sure it's a bug in how Core Data converts NSArray to Swift Arrays when fetching my Day entities. Perhaps it has to do with the relationships or attributes of the Day entities. I'll continue to look into it.
For now, I found a work around. Instruments kept pointing back to the libswiftFoundation method for converting NSArray to Array, and the Cycles & Roots kept showing an NSArray with no ivar. Based on my research this has to do with the initialization of the NSArray created by the fetch request, which is converted behind the scenes to a Swift array. Since I can't change this, I made a new Array from the fetch results:
override func viewDidLoad() {
    super.viewDidLoad()

    let fetchResults: [Day] = DateFilter.getAllDays()
    allDays = fetchResults.map({$0})

    let backgroundView = UIView(frame: CGRectZero)
    tableView.tableFooterView = backgroundView
    tableView.backgroundColor = UIColor.groupTableViewBackgroundColor()
}

And magically, the memory leak is gone! I'm not entirely sure why the fetchResults array is leaky, but that seems to be the source of the problem.


Q:

How can I return a query in ResultProxy format when using SQLAlchemy ORM?

I find ResultProxy more convenient to use than ORM results in some cases (by the docs I understand that I could iterate the columns in a full table). I tried this:
query = session.query(Table1)
results = [ResultProxy(a) for a in query]

... but fails with:
AttributeError: 'Table1' object has no attribute 'dialect'

A:

Quick answer:
conn = engine.connect()
result_proxy = conn.execute(query.selectable)

Docs here.
You can also get a column index by its name...
col_index = query.selectable.columns.keys().index(id_column_name)

... and then get the result by its index:
first_row_col_content = query.all()[0][col_index]


Q:

Add stars rating to rating menu item title in Woocommerce product tab section

I'm trying to add the 5 stars rating for a product in Woocommerce next to the rating tab name.

I added in my function.php file this code :
add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {

    $tabs['reviews']['title'] = __('Ratings');

    return $tabs;

}

This give me the chance to change the name of the tab. It's not exactly what I want to do but I thought I could use this function and add the 5 stars rating next to the reviews tab title by adding $average to it
$average      = $product->get_average_rating();

So I'm stuck there. I don't know how to add $average next to the title. I tried this :
$tabs['reviews']['title'] = __('Ratings', $average);

But doesn't work. I'm still a newby with PHP. If you can point me into the right direction, I will appreciate.

A:

It's possible to add stars rating to reviews menu item label using the following (but some CSS styling will be necessary to get something clean and inline):
add_filter( 'woocommerce_product_reviews_tab_title', 'add_stars_to_reviews_tab_item', 98 );
function add_stars_to_reviews_tab_item( $title ) {
    global $product;

    $average_rating = $product->get_average_rating();

    if( ! empty($average_rating) && $average_rating > 0 )
        $title = '
' . $title . '

' . wc_get_rating_html($average_rating) . '
';

    return $title;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


Q:

Sign of integral with increasing power

Maybe a trivial question. I think it is true, but I do not succeed in proving.
Suppose $h(x)$ is such that for all $a\geq 0$
$$
\int_a^\infty h(x) dx\geq0
$$
Prove for all $a\geq 0$
$$
\int_a^\infty x h(x) dx\geq0
$$
If needed, one may assume $\lim_{x\rightarrow\infty}h(x)=0$ and/or continuity of $h$.

A:

Introduce $H(s)=\displaystyle\int_s^\infty h(x) \mathrm dx$ for every $s$. Then $\displaystyle\int_a^\infty xh(x) \mathrm dx=aH(a)+\int_a^\infty H(s)\mathrm ds$ hence $\displaystyle\int_a^\infty xh(x) \mathrm dx\geqslant0$ for every $a$ as soon as $H(s)\geqslant0$ for every $s$.
More generally, $\displaystyle\int_a^\infty u(x)h(x) \mathrm dx=u(a)H(a)+\int_a^\infty u'(s)H(s)\mathrm ds\geqslant0$ for every nonnegative nondecreasing function $u$ as soon as $H(s)\geqslant0$ for every $s$.


Q:

How to save code doing it with OOP?

I'm writing a program to extract some data from txt files with regular expressions.
I'm new in OOP and want to save reiterative code. I want to retrieve about 15 data in each txt file, so I wrote a Class definition for each data.  The patters to match can come in several formats, so I'll need to try several regex patters.  By now, I only implements one regex patterns by data, but in future I need to try more in order to match the specific format used in that txt file, I plan to use a list with de patterns for each data.
I've just wrote 3 classes, but I've realized that I'm repeating too much code.  So, I believe that I'm doing something wrong.
import re
import os
import glob
import csv

class PropertyNumber(object):
    pattern_text = "(?<=FINCA Nº: )\w{3,6}"
    regex_pattern = re.compile(pattern_text)

    def __init__(self, str):
        self.text_to_search = str
        self.text_found = ""

    def search_p_number(self):
        matched_p_number = PropertyNumber.regex_pattern.search(self.text_to_search)
        print(matched_p_number)
        self.text_found = matched_p_number.group()
        return self.text_found

class PropertyCoefficient(object):
    pattern_text = "(?<=Participación: )[0-9,]{1,8}"
    regex_pattern = re.compile(pattern_text)

    def __init__(self, str):
        self.text_to_search = str
        self.text_found = ""

    def search_p_coefficient(self):
        matched_p_coefficient = PropertyCoefficient.regex_pattern.search(self.text_to_search)
        print(matched_p_coefficient)
        self.text_found = matched_p_coefficient.group()
        return self.text_found

class PropertyTaxIDNumber(object):
    pattern_text = "(?<=Referencia Catastral: )\d{7}[A-Z]{2}\d{4}[A-Z]\d{4}[A-Z]{2}"
    regex_pattern = re.compile(pattern_text)

    def __init__(self, str):
        self.text_to_search = str
        self.text_found = ""

    def search_tax_id(self):
        matched_p_taxidnumber = PropertyTaxIDNumber.regex_pattern.search(self.text_to_search)
        print(matched_p_taxidnumber)
        self.text_found = matched_p_taxidnumber.group()
        return self.text_found

def scan_txt_report(fli):
    data_retrieved = []
    file_input = open(fli, mode='r', encoding='utf-8')
    property_report = file_input.read()
    property_number = PropertyNumber(property_report)
    data_retrieved.append(property_number.search_p_number())
    property_coefficient = PropertyCoefficient(property_report)
    data_retrieved.append(property_coefficient.search_p_coefficient())
    property_tax_id_number = PropertyTaxIDNumber(property_report)
    data_retrieved.append(property_tax_id_number.search_tax_id())

    return data_retrieved

def main():
    if os.path.exists("./notas_simples/ns_txt"):
        os.chdir("./notas_simples/ns_txt")
        list_txt_files = glob.glob("*.txt")
        print(list_txt_files)
        with open("..\..\listado_de_fincas.csv", mode='w', newline='') as fiout:
            file_writer = csv.writer(fiout, delimiter=';')
            for file_name_input in list_txt_files:
                data_line = scan_txt_report(file_name_input)
                file_writer.writerow(data_line)

if __name__ == '__main__':
    main()

# TODO Idufir: "(?<=IDUFIR: )\d{14}"
# TODO calle: "(?<=Calle ).*"   Break down in street name and number of address
# TODO piso: "(?<=piso ).*,"    Break down in floor number and door number (or letter), without boundaries
# TODO titularidad: "(?<=TITULARIDAD\n\n).*"    Break down in owner name, VAT number, % and domai type.

As you can see above, the 3 classes I've already wrote: PropertyNumber(object), PropertyCoefficient(object) and PropertyTaxIDNumber(object), has a lot of repeated code.  Thus, when I add some regex patterns to each class will be worse.

A:

Yes, you are repeating much of your code, and yes, it is a sign of a weak design. I'll take this as an OOP exercise, because this is an overkill.
First, we can see that the only difference between the different classes is their essence, and their regex pattern. So we can have a base class which handles all the repetitive code. Now each subclass simply handles the different pattern:
class BaseProperty(object):
    def __init__(self, search_str, pattern):
        self.text_to_search = search_str
        self.text_found = ""
        self.regex_pattern = re.compile(pattern)

    def search_property(self):
        matched_property = self.regex_pattern.search(self.text_to_search)
        print(matched_property)
        self.text_found = matched_property.group()
        return self.text_found

class PropertyNumber(BaseProperty):
    def __init__(self, search_str):
        super(PropertyNumber, self).__init__(search_str, "(?<=FINCA Nº: )\w{3,6}")

class PropertyCoefficient(BaseProperty):
    def __init__(self, search_str):
        super(PropertyCoefficient, self).__init__(search_str, "(?<=Participación: )[0-9,]{1,8}")

Second, it doesn't appear that you're actually using the self.text_found field, so why store it? Now you can init all the properties in a single place, and make your scan_txt_report much simpler.
class BaseProperty(object):
    def __init__(self, pattern):
        self.regex_pattern = re.compile(pattern)

    def search_property(self, search_str):
        matched_property = self.regex_pattern.search(search_str)
        print(matched_property)
        return matched_property.group()

...
class PropertyCoefficient(BaseProperty):
    def __init__(self):
        super(PropertyCoefficient, self).__init__("(?<=Participación: )[0-9,]{1,8}")

properties = [PropertyNumber(), PropertyCoefficient(), ...]

def scan_txt_report(fli):
    file_input = open(fli, mode='r', encoding='utf-8')
    property_report = file_input.read()
    data_retrieved = [prop.search_property(property_report) for prop in properties]
    return data_retrieved

And unless you add some specific functionality for each subclass, you can even let go of the specific properties classes, and just do like this:
properties = [BaseProperty("(?<=FINCA Nº: )\w{3,6}"), BaseProperty("(?<=Participación: )[0-9,]{1,8}")]

And one last thing - please see the comment by @JonClements - it's a bad idea to use reserved words (such as str) as variable names.


Q:

jqGrid toolbar search and Django

i'm using jqGrid to add Toolbar Search like the example in the Toolbar Search Example
and already implemented basics and advanced examples like site tutorials and my page is like this
but i don't know how to use this feature in Django !!! what's the name of those input types on the top of my grid !??
the example is not clear  ! can you help me ??
[here's my source code on github][4]
{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Index Page</title>

    <link rel="stylesheet" type="text/css" media="all" href="{% static "css/bootstrap.min.css?id=1" %}"/>

    <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/ui.jqgrid.css" %}" />
    <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/ui-lightness/jquery-ui.min.css" %}" />

models.py:
from django.db import models
from datetime import datetime

class room_type(models.Model):
    id = models.IntegerField(primary_key = True)
    code = models.CharField(max_length = 40)
    name = models.CharField(max_length= 40 )
    title = models.CharField(max_length = 40)
    english_title = models.CharField(max_length=40)
    capacity = models.IntegerField()
    extra_capacity = models.IntegerField()
    description = models.CharField(max_length=255)

    class Meta:
        db_table = 'room_types'
    def __unicode__(self):
        return u'%d' % (self.id)

class room_icon(models.Model):
    id = models.IntegerField(primary_key = True)
    status  =  models.IntegerField()
    color_of_icon =  models.CharField(max_length=40)
    path_of_icon  =  models.CharField(max_length=255)

    #foreign_key : a room has only one icon
    rt_id = models.ForeignKey(room_type)
    class Meta:
        db_table = 'room_icons'
    def __unicode__(self):
        return u'%d' % (self.id)

class attachment(models.Model):

    id = models.IntegerField(primary_key = True)
    path_of_pic = models.CharField(max_length=255)

    #foreign key : a room has many images
    rt_id = models.ForeignKey(room_type)
    class Meta:
        db_table = 'attachments'
    def __unicode__(self):
        return u'%d' % (self.id)

views.py:
from django.shortcuts import render
from django.utils import simplejson
from django.http import HttpResponse
from rooms.models import *
from django.db.models import Q
from django.core import serializers

def index(request):
    return render(request, 'index.html')

def getdata(request):
    data=room_type.objects.all()
    json=[]
    for o in data:
        json.append({'id':o.id, 'name':o.name, 'english_title':o.english_title, 'capacity':o.capacity})

    return HttpResponse(simplejson.dumps(json), mimetype='application/json',content_type='application/json' )

def getpricelist(request):

    requested_room_id = request.GET.get('id', '')

    room = room_type.objects.get(id = requested_room_id)
    price_list_set = room.price_list_set.all()

    json=[]
    for price_list in price_list_set:
        json.append({'from':price_list.from_date, 'to':price_list.to_date, 'price':price_list.price})

    return HttpResponse(simplejson.dumps(json), mimetype='application/json',content_type='application/json' )

    class price_list(models.Model):

        id = models.IntegerField(primary_key = True)
        from_date = models.CharField(max_length=10)
        to_date   = models.CharField(max_length=10)
        price = models.IntegerField()
        #foreign key : a room has a pricee list
        rt_id = models.ForeignKey(room_type)
        class Meta:
            db_table = 'price_lists'
        def __unicode__(self):
            return u'%d' % (self.id)

Final Edit :
if I've edited the html file , and now all the files are correct , if you need django source code for jqGrid examples(toolbar search , advanced master detail , and load json data) you can use mine , just work fine ;) !!
Tnx again @Oleg for great help ;)

A:

I'm not Django developer, but the server side code looks like it returns the array of all unsorted items. In the case you should use loadonce: true option of jqGrid. In the case jqGrid saves all data in internal parameters data and _index and change datatype option to "local" after the first load. After that the searching works on the client side and you don't need to make any changes in the server code.
If you use loadonce: true option and you need reload the data from the server (for example after changing url) then you have to reset datatype to its original value datatype: "json":
$("#list_d").jqGrid("setGridParam", {
    url: "getpricelist?q=1&id=" + encodeURIComponent(ids),
    page: 1,
    datatype: "json"
}).trigger("reloadGrid");

I would recommend to consider to use additionally datatype: "local" in the second (details grid). The current code use url:'getpricelist?q=1&id=2', datatype: "json". So the second grid will be filled before a row in the first grid selected. Using datatype: "local" prevents the loading.
I recommend you to use gridview: true and autoencode: true options in the both grids and to add key: true property to the definition of "id" column in the first grid. If you do this then id of
 elements (the rows of the grid) will be assign to the values from id column. It can simplify editing operations.
The last remark: jqGrid assign always id attribute (known as rowid) to every row of the grids. id have to be unique over the whole page. If you have more as one grid you could have id conflicts in the grids. To be sure that you don't have the problem you can consider to use different idPrefix parameters (for example idPrefix: "g1_" and idPrefix: "g2_") for different grids (of for one from the grids). In the case the rowid values will be build from the idPrefix and the id assigned from your data (for example id column in the first grid). If you need to cut the prefix (for example to use it as a parameter in the URL) you can use $.jgrid.stripPref method. For example you can use $.jgrid.stripPref($(this).jqGrid("getGridParam", "idPrefix"), ids) instead of id during building url of detailed grid.


Q:

Rails 5: ActiveRecord OR query

How do you do an or query in Rails 5 ActiveRecord? Also, is it possible to chain or with where in ActiveRecord queries?

A:

The ability to chain or clause along with where clause in ActiveRecord query will be available in Rails 5. See the related discussion and the pull request.
So, you will be able to do the following things in Rails 5:
To get a post with id 1 or 2:
Post.where('id = 1').or(Post.where('id = 2'))

Some other examples:
(A && B) || C:
    Post.where(a).where(b).or(Post.where(c))

(A || B) && C:
    Post.where(a).or(Post.where(b)).where(c)

A:

We don't need to wait for rails 5 to use this OR query. We can also used it with rails 4.2.3. There is a backport here.
Thank to Eric-Guo for gem where-or, Now we can add this OR functionality in >= rails 4.2.3 also using this gem.

A:

(Just an addition to the answer by K M Rakibul Islam.)
Using scopes, the code can become prettier (depending on the eyes looking):
scope a,      -> { where(a) }
scope b,      -> { where(b) }

scope a_or_b, -> { a.or(b) }


Q:

Different signatures

I was working out the christoffel symbols, once where the metric that I am using has (+---) signature and another time where it has (-+++) signature because two books had different signatures and I had to check for any inconsistencies. I had the christoffel symbols the same for both but the curvatures $(R_{\mu\nu})$ has opposite signs. Why is that?

A:

If you stick to one convention out of many other conventions, you should have same results regardless of signature of metric. Here I follow Carroll's conventions: http://amzn.com/0805387323 or http://arxiv.org/abs/gr-qc/9712019.
For Christoffel symbol, we have
\begin{equation}
\Gamma^\lambda_{\mu\nu}=\frac{1}{2}g^{\lambda\rho}(\partial_\mu g_{\nu\rho}+\partial_\nu g_{\rho\mu}-\partial_\rho g_{\mu\nu})\,.
\end{equation}
So if you change signature of the metric $g_{\mu\nu}\to -g_{\mu\nu}$, you have same Christoffel symbol. As a same argument, the definition of Ricci curvature is
$$
R_{\mu\nu}=R^\lambda_{\phantom{a}\mu\lambda\nu}
$$
where Riemann curvature only depends on Christoffel symbol and its derivative. Therefore we have same Ricci curvature, even if we change the signature of metric.


Q:

RecyclerView item touch to highlight

I am using a RecyclerView and I am not able to see any feedback when I touch on the item of the RecyclerView. How do I achieve it?
I am trying to show a feedback to the user when they are touching the row of RecyclerView. Something like a ripple effect.
I want to know how to achieve it in a specific row of the RecyclerView.
This is the recycler view's custom row layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/drawer_row"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_toEndOf="@+id/navigation_image"
        android:layout_toRightOf="@+id/navigation_image"
        android:textSize="17sp" />

    <ImageView
        android:id="@+id/navigation_image"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp" />

    <TextView
        android:id="@+id/horizontal_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentBottom="true"
        android:background="#F1F1F1" />

</RelativeLayout>

This is the layout of the Activity having the RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/windowBackground">

    <RelativeLayout
        android:id="@+id/nav_header_container"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/ic_drawer_header">

        <ImageView
            android:id="@+id/circle_imageview"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/profile_pic"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="John Doe"
            android:textSize="20sp"
            android:textColor="#ffffff"
            android:layout_below="@+id/circle_imageview"
            android:layout_alignLeft="@+id/circle_imageview"
            android:layout_alignStart="@+id/circle_imageview"
            android:layout_marginTop="5dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Transaction Technologies"
            android:layout_below="@+id/textView"
            android:layout_alignLeft="@+id/textView"
            android:layout_alignStart="@+id/textView"
            android:textColor="#ffffff"
            android:layout_marginTop="5dp" />

    </RelativeLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/drawerList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/nav_header_container" />

</RelativeLayout>

I just need to highlight/give feedback of the row which is being touched by the user. How do I achieve it?
Thanks in advance.

A:

You need to add android:focusable="true" in your custom row item for RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/drawer_row"
    android:background="?android:selectableItemBackground"
    android:focusable="true"
    android:clickable="true" >
</RelativeLayout>


Q:

Call jquery in a subcontext again in jquery command chain

Is it possible to do something like this?
jQuery(selector).jQuery(subselector).command(....)

My code is like this:
$(' .species')
.filter(function () { return !$(this).data('hidden_code_ready'); }
.wrapInner('')
.append('')
.data('hidden_code_ready', true)

Now for each of these matched elements (.species) I want to install click handler to the .show_species. I know I can probably do something like:
$('.show_species',
    $(' .species')
    .filter(function () { return !$(this).data('hidden_code_ready'); }
    .wrapInner('')
    .append('')
    .data('hidden_code_ready', true)
).click(...);

but this is really awkward. Is there any possibility to do something like:
$(' .species')
.filter(function () { return !$(this).data('hidden_code_ready'); }
.wrapInner('')
.append('')
.data('hidden_code_ready', true)
.jQuery('.show_species').click(....);

???
Preferably working in jQuery 1.3.2 too. Thanks!

A:

Close! The function is called .find(), not jQuery:
$('.species')
    .filter(function () { return !$(this).data('hidden_code_ready'); }
    .wrapInner('')
    .append('')
    .data('hidden_code_ready', true)
    .find('.show_species').click(....);