text:
Q: Flutter pause Timer when on screen. Stop when I jump to another screen. Resume when I get back on that screen I have two pages in flutter app. Even when i move to secondpage (using navigator.push), the timer still runs in background. ( I know it because i am printing it in terminal also). Also, I already tried canceling my Timer in dispose method. it does not work. Also, If I use navigator.pushReplacement, it solves the problem of Timer being run in background, but i wont be able to go back to this page.
here is my full code:
    import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:provider_2_practice/controller/controller_file.dart';
import 'new_screen.dart';

class MyHomePageUI extends StatefulWidget {
  @override
  State<MyHomePageUI> createState() => _MyHomePageUIState();
}

class _MyHomePageUIState extends State<MyHomePageUI> {

  Timer? timer ;
  String abc ='df-1'; //default value: 'df-1'

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
      if(mounted){
        setState( () {
          abc = DateFormat('hh:mm:ss a').format(DateTime.now());
        } );
      }
      print(abc);
    });
  }

@override
  void dispose() {
    // TODO: implement dispose
  print('test \n if you are seeing this, maybe you used Navigator.pushReplacement()');
  timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue[900],
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          dispose();
          // Provider . of <MyController> (context, listen: false)  . addItemInList();
           Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));

          /*MyController con = MyController();
          con.addItemInList();*/
        },
        child: Icon(Icons.add,  color: Colors.white),
        backgroundColor: Colors.blue,
      ),

      body: Column(
        children: [
          SizedBox(height:100,),
          Text(abc, style: TextStyle(fontSize: 45, fontWeight: FontWeight.bold,color: Colors.white70),),
          Text('current time', style: TextStyle(  fontWeight: FontWeight.bold,color: Colors.white),),

        ],
      ),
    );
  }
}

A: dispose method is only called once the page is finished and ready to be removed from the WidgetTree, In the first case when you use Navigator.push to navigate to another page, It won't remove the previous page and Navigator.pushReplacement replaces the first page and removes it from widget tree thus calls the dispose method.
So, to pause and resume after coming back to the first page, then you need to cancel timer before the navigator.push and await till it completes and resume after async is done
        void goToSecondpage () async {
              timer?.cancel();
              await Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => SecondWidget()));
              initTimer();
            }

Full code here


text:
Q: Left and Right inverses - Proof by contradiction 1) If $F: A \rightarrow B$ has a left inverse then $F$ is injective.
2) If $F: A \rightarrow B$ has a right inverse then $F$ is surjective.
I've already proved those statements in an iff implication. Now I just want to check if it's possible to prove those claims by contradiction... Here's what I've got:

Let $G: B \rightarrow A$ be the left inverse of $F$  in (1) and right inverse of $F$ in (2)
1) Since $G$ is a left inverse, we have that:
$$
G(F(a)) = a \text{ is valid }\forall a \in A
$$
Now suppose that $F$ is not injective, therefore $\exists a_1,a_1 \in A$ such that $a_1 \neq a_2$ and $F(a_1) = F(a_2) = b' \in B$, therefore:
$$
G(F(a_1)) = a_1 \text{ and } G(F(a_2)) = a_2
$$
but since $F(a_1) = F(a_2) = b'$ it follows that
$$
G(b') = a_1 \text{ and } G(b') = a_2
$$
Since $G$ is a function, that is clearly a contradiction, therefore $F$ is injective.
2) Since $G$ is a right inverse, we have that:
$$
F(G(b)) = b \text{ is valid } \forall b \in B
$$
Now suppose $F$ is not surjective, therefore $\exists b' \in B$ where $b' \notin \text{Im}(F)$. Now see that
$$
F(G(b'))=b'
$$
hence $b' \in \text{Im}(F)$, which is a contradiction. Conclusion: $F$ is surjective.

Here is something that I'd like to mention before you post your comment:
As I've said, I've already proved those statements in an easier and more immediate way... The reason for this post is to check a different approach to the proof, using proof by contradiction. For you, what I've done is correct? If not, could you explain why and how would you do to prove it by contradiction?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adapter Pattern for ViewModels in Asp.net core MVC Currently I am converting ViewModels into model objects and also the other way round. I do this in the controller and sometimes it can be quite a big object with many properties. I was wondering if this is bad practice. Should I create adapter classes to convert them and then just use the adapter in the controller.
Below is an example of how I convert the ViewModel object to a Model object in the controller:
    public async Task<IActionResult> Register(RegisterViewModel registerModel)
    {
        if (ModelState.IsValid)
        {
            ApplicationUser user = new ApplicationUser
            {
                UserName = registerModel.Email,
                Email = registerModel.Email,
                FirstName = registerModel.FirstName,
                LastName = registerModel.LastName,
                AddressLine1 = registerModel.AddressLine1,
                AddressLine2 = registerModel.AddressLine2,
                City = registerModel.City,
                PostCode = registerModel.PostCode,
                PhoneNumber = registerModel.PhoneNumber,
                NotificationPreference = Enum.GetName(typeof(NotificationPreference), NotificationPreference.None)
            };
            await userManager.CreateAsync(user, registerModel.Password);
        }
        return View(registerModel);
    }

So should I create the ApplicationUser here or should I create it in an adapter class.

A: Short answer: It depends on number of things and certain personal preferences.
Long Answer:
We need to take into account a number of factors in order to answer this question:

*

*Whether some of the projects in our solution already use converters/adapters

*How big the solution is at the moment

*How big the solution will be in the future

*How many models/viewmodels there are (there will be)

*How precisely do we want to follow certain design patterns such as SOLID, separation of concerns etc

*Our personal preferences and experience

One simple option would be to add a ctor or overload the implicit casting operator for each ViewModel:
public class ApplicationUser
{
    // Properties

    public ApplicationUser(RegisterModel registerModel)
    {
         UserName = registerModel.Email;
         Email = registerModel.Email;
         FirstName = registerModel.FirstName;
         // etc
    }

    //    OR:
    //    public static implicit operator ApplicationUser(RegisterModel) =>
              new ApplicationUser { UserName = registerModel.Email, ... };
}

For bigger/enterprise projects we could utilize AutoMapper or even create our own converters for each pair model -> viewmodel however I'd think twice before doing so.

A: Use AutoMapper, it's not that complicated.
Startup.cs ConfigureServices:
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new RegisterViewModelProfile());

    });

    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);

Create the RegisterViewModelProfile class. (I usually put these in the corresponding viewmodel class file, in your case its the RegisterViewModel.cs file. Others create one MapperProfile.cs and put all Profile classes in that file, but ofc you can create separate files for each.)
public class RegisterViewModelProfile : Profile
    {
        public RegisterViewModelProfile()
        {
            CreateMap<RegisterViewModel, ApplicationUser>()
                .ForMember(dest=>dest.UserName, opt=>opt.MapFrom(src=>src.Email))
                .ForMember(dest=>dest.NotificationPreference , opt=>opt.MapFrom(src=> Enum.GetName(typeof(NotificationPreference), NotificationPreference.None) ));
                //you dont need to map the other attributes because they have the same name and type in VM and in Model so AutoMapper does it automagically

            //you can map the other way around too if you need to the same way, and you can even do conditional mapping and/or overwrite data etc
            CreateMap<ApplicationUser, RegisterViewModel>()
                .ForMember(dest => d.Email, opt => opt.MapFrom(src => "Masked because of GDPR"));

        }
    }

In your controller inject the mapper, and do the mapping when you need to do:
 public class JobsteplogsController : Controller
    {
        private readonly IMapper _mapper;

        public UserController(JobManagerContextCustom context, IMapper mapper)
        {
            _mapper = mapper;
        }
        public async Task<IActionResult> Register(RegisterViewModel registerModel)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = _mapper.Map<ApplicationUser>(registerModel);

                await userManager.CreateAsync(user, registerModel.Password);
            }
            return View(registerModel);
        }

    }


text:
Q: ¿Por qué me aparece este error en c sharp? Me aparece que se ha iniciado un System.NullReferenceException debido a que el objeto de referencia no se ha seleccionado como una instancia del objeto.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JuegoMatrizBinaria
{
  class Program
  {
        public static int[,] matriz = new int [4,4];

        static void Main(string[] args)
        {
            string[] intentosMatriz = new string[2];
            int intentos = 4;
            string intento = string.Empty;

            while (intentos > 0)
            {
                printMatriz(matriz);
                Console.WriteLine();
                Console.WriteLine("Escribe tu jugada(x,y) [Intento #" + intentos +
"]");
                intento = Console.ReadLine();
                Console.WriteLine();
                intentosMatriz = intento.Split(',');

                intentos--;
            }

            Console.ReadKey();
        }

        public static void setMatrizValue(int x,int y)
        {
            if (x<0 || x>3 || y<0 || y > 3)
            {
                Console.WriteLine("Jugada Inválida");
                return;
            }

            matriz[x, y] = 1;

            printMatriz(matriz);
        }

        public static void printMatriz(int[,] matriz)
        {
            for (int i = 0; i <= 3; i++)
            {
                for (int j = 0; j <= 3; j++)
                {
                    Console.Write(matriz[i, j]);
                }
                Console.WriteLine();
            }
        }
    }

}

¿Alguien sabe qué puede estar ocurriendo? Estoy tratando de hacer una matriz. El error me lo da exáctamente en intentosMatriz = intento.Split(','); No se si es porque no he declarado algún tipo de objeto más arriba o cuál puede ser el error. Gracias.

A: Debes escribir en la ejecución, cuando se ejecute el ReadLine lo siguiente:
intento1, intento2, intento3
Y luego saber que hace cada función, porque revisando tu codigo creo que estas un poco enredado con las funciones que estas ocupando o estas ocupandolas no para lo que se han escrito.
Prueba lo que te dije y te funcionará.
Saludos


text:
Q: C++/CX ^ versus & I'm learning C++/CX by building a windows store app. For the base of my viewmodels I use the standard BindableBase class and added a convenient SetProperty method to it (which I'm used to in my C# projects).
Now I expected I should write it like this:
public ref class BindableBase : Windows::UI::Xaml::DependencyObject, Windows::UI::Xaml::Data::INotifyPropertyChanged,
{
public:
    virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;

protected:
    virtual void OnPropertyChanged(Platform::String^ propertyName);

private protected:
    template <typename T>
    bool SetProperty(T^ storage, T^ value, String^ propertyName)
    {
        if (storage == value)
        {
            return false;
        }
        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }
};

But that doesn't work, the view won't update. But when I changed the signature of the SetProperty method to this:
bool SetProperty(T& storage, T& value, String^ propertyName)

It suddenly does work, but I can't figure out why the ^ syntax doesn't work.

A: The C++/Cx-isms here aren't the issue. You'll get the same behaviour if you use standard C++ variables as you do using C++/Cx handles (^).
The issue is value parameters vs. reference parameters. By default C++ passes arguments by value. Changes made to the argument are local to the called function and don't affect the caller. If you mark the parameter with an & then the parameter is passed by reference and changes do affect the caller.
This may be clearer if you rewrite the whitespace in your arguments:
bool SetProperty(T &storage, T &value, String ^propertyName)

When you don't use the & syntax you receive the caller's T storage (which must be a ref class, since you used ^) and then overwrite that locally. If you break in the debugger you'll see that storage gets set as you'd like, but step out and compare it in the caller to see the caller's storage is unchanged. Remove the ^s--SetProperty(T storage, T value, String^ propertyName)--and it will act the same with non-ref classes.
When you use the & syntax you receive a reference to the caller's T storage, so changes to storage store value in the caller's variable.


text:
Q: Pagnation with LINQ to entities I have a problem, I'm trying to use a helper-class for a MVC project. And I get error that I must use OrderBy somehow.
this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize))

What to do?
/M

A: EF is precious about this (although LINQ-to-SQL would let you do it); just add an explicit OrderBy:
source.OrderBy(x=>x.SomeId).Skip(PageIndex * PageSize).Take(PageSize)

(or order by name, or whatever else makes sense)


text:
Q: spawn is not able to launch global package in node.js I need to launch globally installed node package as a separate process through another global package called launcher. I want launcher to launch the another package and exit.
spawn is able to launch notepad as separate process. But not able to launch globally installed package.
I have written the below code:
//var child = moduleLauncher.spawn('notepad',[],{

var child = moduleLauncher.spawn('hrm_module C:/test.scanRequest',[],{

           detached: true,

           stdio: ['ignore', out, err]
});

child.unref();

Generated Error:
events.js:154

  throw er; // Unhandled 'error' event
  ^

Error: spawn hrm_module C:/test.scanRequest ENOENT
    at exports._errnoException (util.js:856:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at nextTickCallbackWith2Args (node.js:475:9)
    at process._tickCallback (node.js:389:17)
    at Function.Module.runMain (module.js:449:11)
    at startup (node.js:140:18)
    at node.js:1001:3

Note: the commond - hrm_module C:/test.scanRequest is working fine on command prompt of windows.
I want to run this command through a launcher.

A: spawn('hrm_module C:/test.scanRequest',[]

needs to be
spawn('hrm_module',['C:/test.scanRequest']

Pass the arguments in the argument array. Otherwise it will look for a file named hrm_module C:/test.scanRequest and not find one as you have found.

A: Let cmd to start the module for you:
const command = 'cmd';
const args = ['/C', 'hrm_module', 'C:/test.scanRequest']
const options = {/* your spawn options */ };
spawn(command, args, options);


text:
Q: How can I stop civilizations dying out and fortress abandonment? When generating worlds that are old (1k-10k years), I have a very hard time stopping civilizations dying out and every fortress I visit in Adventurer mode is abandoned.
What aspects of world generation effect fortress abandonment and creation? Can you have an old world without many abandoned fortresses, or are they just abandoned as time progresses.
What greatly effects civilizations dying out? How can I generate an old world that has a balanced amount of beasts to civilizations? (i.e. not end up without any beasts nor without any people)

A: The DF wiki has a page on world generation.
Relevant bits:

History
Higher values will also increase the number of abandoned (sacked) towns and fortresses
Maximum Number of Sites
This is the maximum number of sites such as towns, hamlets, elf retreats, etc. Turning this up is advised for adventure mode games.
Number of Beasts
Since beasts can attack civilizations, more beasts may reduce the population of the world a little bit.

And from the page on advanced world generation:

Population Cap After Civ Creation
Each race may have up to 100 civilizations each, and each civilization a maximum population of 10,000. This means that if you set this parameter to -1 ("No cap"), you can quickly be overrun by sites and population


text:
Q: What's the name of the differential equation Consider the ODE $$\frac{y''}{x}+\frac{y}{x}=0,$$ what do we call this equation at the point $x=0$?

A: I'd call it a trap! Your equation is equivalent to $y''+y=0$ on $(-\infty,0)$ and on $(0,+\infty)$. Is there any reason why you want to exclude the single point $x=0$?
In some sense, $x=0$ is a "removable singular point" for the equation.


text:
Q: Do I understand this "method" method right? While starting RubyMonk level 2, I see this:
class Calculator
  def add(a, b)
    return a + b
  end
end

addition_method = Calculator.new.method("add")
addition        = addition_method.to_proc

puts addition.call(5, 6)

and never having seen method before, I consulted the documentation
So the understanding I have now, is:
If you want to steal a method from a class, and make it into a proc (lambda?), you stick the method in there before the name of the class method you desire, which you then surround with quotes or write as a symbol.
Is this the correct way to think about it? Or is it at least the primary use of Object#method?

A: I think you have the right idea.  More generally, the method method is just a way of representing a Ruby method as a Method object, and that could be useful for many reasons because objects are useful.
There is some extraneous stuff in that example code.  Here is another example:
def add(a)
  a + a
end

m = method(:add)  # => #<Method: Object#add>
m.call(4)         # => 8

Here is another example where it is useful:
def good?(n)
  n > 5
end

[1, 4, 9].select(&method(:good?))   # => [9]

A: Essentially yes. The method method lets you "package up" the method and its receiver into a single object of class Method. The receiver is the object you called .method on. A Method object is also called a "bound" method because it's bound (attached) to a receiver.
Example:
class Car
  attr_accessor :make, :model

  def initialize(make, model)
    @make, @model = make, model
  end

  def drive(speed)
    puts "#{@make}-#{@model} drove with speed #{speed}"
  end
end

Create an instance:
car1 = Car.new('Toyota', 'Corolla')

Grab the method and call it:
car1drive = car1.method(:drive)
# Outputs "Toyota-Corolla drove with speed 5"
car1drive.call(5)

Note how we don't have to convert it to a proc in order to use call on it.
Receiver binding
To demonstrate how the method is still bound to its receiver, we modify the receiver. Notice how the Method still depends on the object it came from. I.e. creating the Method did not take a snapshot of the receiver's state, but consults the receiver every time it's called.
car1.model = 'Rav4'
# Outputs "Toyota-Rav4 drove with speed 5"
car1drive.call(5)

We can also retrieve the receiver:
car1drive.receiver == car1  # true

Usage as a block
It can be used in place of a block by using & (which implicitly calls to_proc). This works nicely because each yields one argument to the block, and our car1drive method also takes one argument.
# Outputs:
# Toyota-Rav4 drove with speed 1
# Toyota-Rav4 drove with speed 2
# Toyota-Rav4 drove with speed 3
[1,2,3].each(&car1drive)

Unbound methods
We can also get an unbound method and bind that to another Car.
unbind returns a brand new UnboundMethod; it doesn't change the bound method.
# This gives us an UnboundMethod.
# It can't be called; it's like a disembodied spirit.
# This doesn't change car1drive at all.
unbound_drive = car1drive.unbind

car2 = Car.new('Chevy', 'Cruze')
car2drive = unbound_drive.bind(car2)
# Outputs "Chevy-Cruze drove with speed 5"
car2drive.call(5)

You can also get the same UnboundMethod as the above by using the Car class directly:
unbound_drive = Car.instance_method(:drive)

Calling a superclass method that has been overridden in a subclass
Here's one nice trick you can do to call an overridden method. Let's say you have a subclass that overrides a method:
class Jalopy < Car
  def drive(speed)
    puts "The ailing #{@make}-#{@model} drove with speed #{speed}"
  end
end

jal1 = Jalopy.new('Toyota', 'Corolla')
# Outputs "The ailing Toyota-Corolla drove with speed 5"
jal1.drive(5)

# I don't like the overridden output, give me the original instead!
unbound_car_drive = Car.instance_method(:drive)
car_drive_on_jal1 = unbound_car_drive.bind(jal1)

# Outputs "Toyota-Corolla drove with speed 5"
car_drive_on_jal1.call(5)

We can only do this because jal1 is a Car (jal1.is_a?(Car) is true)
I don't recommend using the above in an actual application, because it makes code very hard to manage - but sometimes it helps with troubleshooting.


text:
Q: Reformat Beautiful Soup Output to include CSS I am trying to parse through the text of emails to expedite my workflow using Python. I first save the email has a .htm on my local drive. Then, I want to try pulling certain pieces of information out of a table within the email using Jupyter Notebook. Whenever I create the soup, the result is a spaced out text field. I am unable to use this soup to make proper HTML calls to pull data. How may I reformat the soup?
The .htm file is already text, but I would still like to use Beautiful Soup to help me parse through the text field. Should I be trying a different parse method?
from bs4 import BeautifulSoup
raw_file = open(r"C:\Users\Desktop\Example.htm").read()
soup = BeautifulSoup(raw_file, 'lxml')
print(soup)

I expected a nicely formatted soup file, instead, this is what the print statement returns:
<html><body>
<p>ÿþh t m l   x m l n s : v = " u r n : s c h e m a s - m i c r o s o f t - c o m : v m l "

 x m l n s : o = " u r n : s c h e m a s - m i c r o s o f t - c o m : o f f i c e : o f f i c e "

 x m l n s : w = " u r n : s c h e m a s - m i c r o s o f t - c o m : o f f i c e : w o r d "

 x m l n s : m = " h t t p : / / s c h e m a s . m i c r o s o f t . c o m / o f f i c e / 2 0 0 4 / 1 2 / o m m l "

 x m l n s = " h t t p : / / w w w . w 3 . o r g / T R / R E C - h t m l 4 0 " >

 h e a d >

 m e t a   h t t p - e q u i v = C o n t e n t - T y p e   c o n t e n t = " t e x t / h t m l ;   c h a r s e t = u n i c o d e " >

 m e t a   n a m e = P r o g I d   c o n t e n t = W o r d . D o c u m e n t >

 m e t a   n a m e = G e n e r a t o r   c o n t e n t = " M i c r o s o f t   W o r d   1 5 " >

 m e t a   n a m e = O r i g i n a t o r   c o n t e n t = " M i c r o s o f t   W o r d   1 5 " >

 b a s e

When I call -
print(raw_file)

the following returns:
ÿþ<html xmlns:v="urn:schemas-microsoft-com:vml"

xmlns:o="urn:schemas-microsoft-com:office:office"

xmlns:w="urn:schemas-microsoft-com:office:word"

xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"

xmlns="http://www.w3.org/TR/REC-html40">

<head>

<meta http-equiv=Content-Type content="text/html; charset=unicode">

<meta name=ProgId content=Word.Document>

<meta name=Generator content="Microsoft Word 15">

<meta name=Originator content="Microsoft Word 15">

<base


text:
Q: react-native-restart Package error I get the following error when I try to use this package: https://github.com/avishayil/react-native-restart

MainApplication.java :
package com.app;

import android.support.annotation.Nullable;

import com.avishayil.rnrestart.ReactNativeRestartPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.reactnativenavigation.NavigationApplication;
import com.avishayil.rnrestart.ReactNativeRestartPackage;

import java.util.Arrays;
import java.util.List;

import io.realm.react.RealmReactPackage;

public class MainApplication extends NavigationApplication {
    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean isDebug() {
            return BuildConfig.DEBUG;
        }

        @Nullable
        @Override
        public List<ReactPackage> createAdditionalReactPackages() {
            return Arrays.<ReactPackage>asList(
                    new RealmReactPackage(),
                    new ReactNativeRestartPackage()
            );
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }
}

build.gradle :
dependencies {
    compile project(':realm')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-navigation')
    compile project(':realm')
    compile project(':react-native-restart')
}

settings.gradle:
rootProject.name = 'App'
include ':realm'
project(':realm').projectDir = new File(rootProject.projectDir, '../node_modules/realm/android')

include ':app'

include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/android/app/')

include ':react-native-restart'
project(':react-native-restart').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-restart/android')

And here how I use it in my code:
import RNRestart from 'react-native-restart';

export default class ClassName extends Component{
...

render() {
    return (
      <View style={styles.container} accessible={true}>
          <TouchableOpacity onPress = {() => this.onPressButton()}
            <Text style={styles.button}> RESTART </Text>
          </TouchableOpacity>
      </View>
    );
  }

  onPressButton(){
    RNRestart.Restart();
  }
}

How can I solve this ?

A: Using automatic installation solved my pb, see github repo


text:
Q: Class C implements interface B which extends interface A, can you say C implements A? In case class C implements interface B and interface B extends interface A. Is it correct to say that class C implements interface A?

A: Yes. C can override the methods of A.
Example: (It's not a good example, but it's just to show that C/Chimpanzee can override the methods of A/Animal)
interface Animal
{
    void giveBirth();
}

interface Mammal extends Animal
{
    void walk();
}

class Chimpanzee implements Mammal
{

    @Override
    public void giveBirth()
    {
        System.out.println("Chimpanzee gives birth.");
    }

    @Override
    public void walk()
    {
        System.out.println("Chimpanzee walks.");

    }
}

A: Even if I agree with the accepted answer with respect to the first part ("Yes."), I don't agree with the second part "C can override the methods of A".
I believe the correct description is that C must implement the methods of both A and B.
For example, if interface A declares the method fooA() and B declares the method fooB(), then C must implement both fooA() and fooB(). In that sense, yes, you can say that C implements interface A (since it implements an interface that extends A).

A: The accepted answer is correct. Because of polymorphism in the Java language, this is possible. However, one must understand the performance impact of using the JVM instruction invokeDynamic instead of invokeVirtual. The latter on requires a simple lookup in the class's virtual table, whereas the former requires a much more in-depth recursive search through all of its implementor's virtual method tables.

A: Yes, you can say C implements A. The instanceof operator comes very handy here:
public interface B extends A {
    public void b();
}

public interface A {
    public void a();
}

public class C implements B {

@Override
public void a() {}

@Override
public void b() {}

public static void main(String[] args) {
    C c = new C();
    System.out.println("C is A? " + (c instanceof A));
    System.out.println("C is B? " + (c instanceof B));
}

}
The result will be:
C is A? true
C is B? true


text:
Q: Can't get objectForKey from NSDictionary I am using this code: https://github.com/valentinlietz/MySQL-Connect to use MySQL queries in objective c. I use Count(*) to check if this row already exists.
I used this code to NSLog(); this dictionary. Code:
for(NSArray *row in response.responseDictionary){

    NSLog(@"%@", row);

}

Result:
{
"" = "<null>";
"COUNT(*)" = 0;
}

But when I use [response.responseDictionary objectForKey:@"COUNT(*)"]; It's returning Unrecognized selector sent to instance.

Update:
Row:
Row: ( { "" = "<null>"; "COUNT()" = 0; } )

Dictionary:
Row: { "" = "<null>"; "COUNT()" = 0; }

A: I haven't worked with that project, but from https://github.com/valentinlietz/MySQL-Connect/blob/master/MySQL.m it looks to me that response.responseDictionary is the result
of converting the JSON response of the script https://github.com/valentinlietz/MySQL-Connect/blob/master/mysql.php to a Foundation object.
And the code
while($row = mysql_fetch_array($query))
{
for($i = 0; $i < 50; $i++) {
     $arr2[$fields[$i]] = $row[$fields[$i]];
}
 array_push($return_arr, $arr2);

}
echo json_encode($return_arr);

in that PHP script shows that the response is an array of dictionaries.
So if I am correct, the name and type of the responseDictionary property is badly chosen, because it is not an NSDictionary, but an NSArray where each object is an NSDictionary,
and the following should work:
NSArray *responseArray = (NSArray *)response.responseDictionary;
NSLog(@"count = %@", [[responseArray objectAtIndex:0] objectForKey:@"COUNT(*)"]);


text:
Q: Possible convert a llvm::FunctionType to C/C++ raw function pointer? Can we convert llvm::FunctionType's object into a C/C++-styled function raw pointer?
A example for a C/C++-styled function raw pointer: uint64_t (*funPtr)(uint64_t* args);

A: llvm::Function is represented as an abstract syntax tree. You can't call it, just like you can't call arrays, lists, or any other data structures.
Instead, you need to leverage LLVM's ExecutionEngine functionality to be able to call llvm::Functions. Internally, the engine will compile it into native executable code and return a void* (I don't remember the API details, but something like that) to that code. Then you will be able to cast this pointer to a function pointer and finally use it to call the function.

A: I'm not 100% sure with regards to the capabilities of llvm, but this text from n4659 may be helpful:

Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value.

I'm pretty sure that function pointers aren't like regular pointers, and so these conversions are problematic.  I think they discuss the issue at length in this stack overflow question.


text:
Q: Include Image from HTML in Markdown Presentation I am creating a markdown presentation and am generating a graph with the library data.tree. When I generate the presentation I get this error
Error: Functions that produce HTML output found in document targeting beamer output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:

always_allow_html: yes

Note however that the HTML output will not be visible in non-HTML formats.

If I include the always_allow_html: yes I just get the text output of my code chunk, like the error says.
How do I generate my graphics using data.tree and have it show up in my Markdown presentation?
Here's basically what my code looks like. I have change/removed nodes to make it easier to see.
----
output: beamer_presentation
---

```{r}
library(data.tree)
Parent = Node$new("Parent Node")
Child = Parent$AddChild("Child Node")

SetNodeStyle(Tree, fontsize = "24")
plot(Parent)
```

I also considered saving the html and loading it in from a local directory, but I wasn't able to find a way to do that.
Edit: Can you explain the down vote so I can fix any issues with this post? I do not believe it's a trivial answer. I did not find any similar posts or answers via google.

A: You may have been downvoted because this code
library(data.tree)
Parent = Node$new("Parent Node")
Child = Parent$AddChild("Child Node")

SetNodeStyle(Tree, fontsize = "24")
plot(Tree)

does not run, even outside the context of a markdown presentation.  This is because "Tree" has not been defined.  The tree object you're trying to refer to as "Tree" is what you've named "Parent".  For a reproducible example, try:
library(data.tree)
Tree = Node$new("Parent Node")
Child = Tree$AddChild("Child Node")

SetNodeStyle(Tree, fontsize = "24")
plot(Tree)

Now how to get that plot into a slide:
You're on the right track with

saving the html and loading it in from a local directory

except you need to actually export it as something TeX can understand, not just save it as html.  In RStudio, if you run the code above and produce the plot independently (not as part of the presentation), you have the option to "Export" > "Save as Image" directly from the viewer pane.
Supposing you've saved the plot in your working directory as "treeplot.png", you can then insert it into your presentation like so:
---
title: "Trees"
output: beamer_presentation
---

## Slide 1

![](treeplot.png)

This technique for inserting an image from a file is covered in the RMarkdown Reference Guide


text:
Q: Padding array elements by number multiplier in Python I have a large 1-Dimensional array full of string values and has characteristics like this:
import numpy as np

arr = np.array(['1000.70', '2*8020.80', '2008.97', '6880.10', '10*7230.96', '7778.0'])

I want to pad and replace the values containing a number multiplying another number (integer multiplying float/integer) for N(int)*number(float/int).
For example I'd like '2*8020.80' to expand to [8020.80, 8020.80] and '10*7230.96' to expand to [7230.96, 7230.96, 7230.96, 7230.96, 7230.96, 7230.96, 7230.96, 7230.96, 7230.96, 7230.96].
The output I would like would be:
expanded_arr = np.array(['1000.70', '8020.80', '8020.80', '2008.97', '6880.10',
'7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96',
'7230.96', '7230.96', '7778.0'])

Is there an easy way to accomplish this?
I've attempted np.tile() and converting to pd.DataFrame by first splitting on the '*' string but all those options force me to go back and forth from df to array.

A: You can do this in a python list way:
arr = ['1000.70', '2*8020.80', '2008.97', '6880.10', '10*7230.96', '7778.0']
temp = []

for x in arr:
    if "*" in x:
        a,b = x.split("*")
        for _ in range(int(a)):
            temp.append(b)
    else:
        temp.append(x)

print(temp)

Output:
['1000.70', '8020.80', '8020.80', '2008.97', '6880.10', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7230.96', '7778.0']

Then you can do:
import numpy as np

expanded_arr = np.array(temp)

A: Similar to Ruturaj's answer, but making the changes directly in the array using Numpy functions.
import numpy as np

arr = np.array(['1000.70', '2*8020.80', '2008.97', '6880.10', '10*7230.96', '7778.0'])

for x in range(len(arr)):
    if '*' in arr[x]:
        a, b = arr[x].split('*')
        arr = np.delete(arr, x, axis = 0) # Deletes the current element in the array
        arr = np.insert(arr, x, int(a)*(b, )) # Adds the new elements in the array
print(arr)

Output;
['1000.70' '8020.80' '8020.80' '2008.97' '6880.10' '7230.96' '7230.96'
 '7230.96' '7230.96' '7230.96' '7230.96' '7230.96' '7230.96' '7230.96'
 '7230.96' '7778.0']

A: r = []
for string in list(arr):
    if "*" in string:
        to_be_duplicated = string[string.find("*")+1:]
        multiple         = int(string[:string.find("*")])
        while multiple>0:
            r.append(to_be_duplicated)
            multiple = multiple-1

    else:
        r.append(string)


text:
Q: How to make Linq2Sql work with my models I work on a project where we was using SqlConnection, SqlCommand and plain SQL to access repository. Now, I am trying to migrate to Linq2Sql and I want to use the same models. How can I achieve this?
I will reduce the project structure to the minimal meaningful example.
Let's say I have the following classes:
namespace Model
{
    public class User
    {
        public int Id { get; set; }
    }
}

All models in Model namespace are one-in-one copy of database entities.
namespace Repository
{
    public class UserRepository
    {
        private _sqlConnectionHelper = new SqlConnectionHelper();

        public User GetUser()
        {
            var reader = _sqlConnectionHelper
                .ExecuteAndReturnReader("SELECT * FROM [dbo].[Users]");

            while (reader.Read())
            {
                return new User
                {
                    Id = (int)reader["Id"]
                };
            }

            return null;
        }
    }
}

Now I am trying to migrate to Linq2Sql. I have created a MyContext.dmbl file with User table in Repository project. It has generated the following class:
namespace Repository
{
    [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Users")]
    [global::System.Runtime.Serialization.DataContractAttribute()]
    public partial class User: INotifyPropertyChanging, INotifyPropertyChanged
    {
         private int _ID;

         public int ID
         {
            get
            {
                return this._ID;
            }
            set
            {
                if ((this._ID != value))
                {
                    this.OnIDChanging(value);
                    this.SendPropertyChanging();
                    this._ID = value;
                    this.SendPropertyChanged("ID");
                    this.OnIDChanged();
                }
            }
        }

        // Some other methods
    }
}

Now, the problem is that I have a lot of of entities, repositories, models etc. I don't want to change the whole project to use new generated models but not mine from Model namespace. How can I make Linq2Sql work with my models?
It also affects my architecture because in case of these models, the entity and the repository is the same object. I don't need my entities to be CRUD objects. I just want to make minimal changes to project and only use convenient LINQ requests instead of plain SQL like this:
namespace Repository
{
    public class UserRepository
    {
        private MyContextDataContext _myContext = new MyContextDataContext();

        public User GetUser()
        {
            return _myContext.Users.FirstOrDefault();
        }
    }
}

Or I just don't understand something about purpose and logic of Linq2Sql and it is how it only works like?
Of course, I can write converters or use reflection and make a copy of object property-by-property but it doesn't sound like a good solution.

A: Ok. Finally, I have found an answer which is pretty simple - Linq2Sql is not a library I was looking for.
There are different approaches for object-relational mapping: code-first, database-first, model-first.
Here is the good StackOverflow article about their differences.
Now, when I learned it, what I have described in my question could be easily rephrased as "how can I make Linq2Sql be code-first". The answer is simple - I cannot do this.
As a result of some investigations, I have understood that I was looking for Entity Framework which perfectly fit in my project.
Now, my repository looks like this:
namespace Repository
{
    public MyContextDataContext : DbContext
    {
        public DbSet<User> Users { get; set; }
    }

    public class UserRepository
    {
        private MyContextDataContext _myContext = new  MyContextDataContext();

        public User GetUser()
        {
            return _myContext.Users.FirstOrDefault();
        }
    }
}


text:
Q: Mongoengine - TypeError: Instantiating a document with positional arguments is not supported I have created Document Definition as -
class Post(Document):
    title = StringField(required=True, max_length=200)
    content = StringField(required=True)
    author = StringField(required=True, max_length=50)
    published = DateTimeField(default=datetime.datetime.now)

and I am inserting data from json file --
data_json = json.load(data_file)
post_1 = Post(data_file)
post_1.save()

I am getting error as -

TypeError: Instantiating a document with positional arguments is not
  supported. Please use field_name=value keyword arguments.

Is there no support to pass json file?

A: Need to unpack the dict--
 Post(**data)


text:
Q: Looking for vba code that will turn off OneDrive syncing Can anyone point me to code that will allow me to temporarily turn on/off the One Drive syncing of the files.
I am looking of Excel 2013 VBA or API Call.
Thanks,
Karen

A: ActiveWorkbook.AutoSaveOn = False


text:
Q: ¿Cómo seleccionar con Jquery un ID dentro de una etiqueta ej: body? tengo un elemento con el ID: #MyID que se encuentra en el Body y tengo que seleccionarla por el uso de un Plugin por ejemplo en el CSS:
body #MyId {
  display: none;
}

Entonces en el archivo .js tengo que cambiar el display a "block" y lo intento con el siguiente código pero no me funciona:
$("body #fullpage").css("display", "block");

¿me podrían por favor indicar la forma correcta de selección y cual es mi error?
De antemano muchas gracias!!

A: Puedes utilizar la instrucción:
$('body #fullpage').show(); Esto cambia directamente a display block.
Para ocultar utilizas: .hide()
Aunque no veo el por qué utilizar body. Pues si es un id, el nombre debe ser único.


text:
Q: How to get data from two table or two class in single view in mvc3 How to get data from two table or two class in single view in mvc3.
I want to show data from both the table.
I have one parent class and two child class.
i.e
      public class GetDocumentParent
            {enter code here
                public List getDocument { get; set; }
                public List getDocumentRevision { get; set; }
            }
View:

" %>

<% foreach (var item in Model.getDocument)
   { %>

             <%:Html.DisplayFor(ModelState => item.DOCUMENT_NAME)%>

              <%:Html.DisplayFor(ModelState => item.ActiveDate)%>

                <%:Html.DisplayFor(ModelState => item.Revision)%>

<% } %>

==>item.DOCUMENT_NAME and item.ActiveDate from Document Class.
item.Revision  from Document_Revision  class.
how to show both class's value at the same time in view.
Controller:
var model = new GetDocumentParent
             {
                 getDocument = db.Document.ToList(),
                 getDocumentRevision = db.DocumentRevisions.ToList()

             };
             return View(model);

Model:
 1.
public class DOCUMENTS
    {
     public string DOCUMENT_NAME
      {
        get;
        set;
      }
    public Nullable<System.DateTime> ActiveDate
      {
        get;
        set;
      }
}

2.
public class DOCUMENT_REVISIONS
 {
    public string REVISION
    {
        get;
        set;
    }
 }
Thanks in advance

A: Always remember that it is best to have a view model that represents your data that is sent to the view. The view will do what is needed with you view model. The code below can guide you, you must just change it to fit into your scenario.
Lets say that I have a customer and each customer has only 1 address.  I would create a view model called CustomerDetailsViewModel to represent this data:
public class CustomerDetailsViewModel
{
     public string FirstName { get; set; }

     public string Lastname { get; set; }

     public int Age { get; set; }

     public string AddressLine1 { get; set; }

     public string AddressLine2 { get; set; }

     public string City { get; set; }
}

Your action method to display the customer and customer address details:
public class CustomerController : Controller
{
     private readonly ICustomerRepository customerRepository;

     public CustomerController(ICustomerRepository customerRepository)
     {
          // Check customerRepository for nulls

          this.customerRepository = customerRepository;
     }

     public ActionResult Details(int id)
     {
          // Check that id is not zero or negative

          Customer customer = customerRepository.GetById(id);

          // Get the customer's address
          Address address = customerRepository.GetCustomerAddress(id);

          CustomerDetailsViewModel viewModel = new CustomerDetailsViewModel()
          {
               FirstName = customer.Firstname,
               LastName = customer.LastName,
               Age = customer.Age,
               AddressLine1 = address.AddressLine1,
               AddressLine2 = address.AddressLine2,
               City = address.City
          }

          return View(viewModel);
     }
}

id above represents your customer's unique identifier.  It is used to return a cusotmer:
Customer customer = customerRepository.GetById(id);

and also used to returned a specific customer's address:
Address address = customerRepository.GetCustomerAddress(id);

An ICustomerRepository instance is injected by an IoC container for example Autofac.
In your view you pass this view model as such and can display the data as you please:
@model MyProject.DomainModel.ViewModels.Customers.CustomerDetailsViewModel

First Name:

@Model.FirstName

Last Name:

@Model.LastName

Age:

@Model.Age

Address Line 1:

@Model.AddressLine1

Address Line 2:

@Model.AddressLine2

City:

@Model.City

I hope this helps.

A: What is the problem?
use in controller:
var model = new GetDocumentParent();
model.getDocument = ...//Code that initialize getDocument
model.getDocumentRevision =...//Code that initialize getDocumentRevision

in View:
@Html.EditorFor(m=>m.getDocument);
@Html.EditorFor(m=>m.getDocumentRevision);


text:
Q: How to write query for a php array? I have the following php array that gets all values from a form full of radios and check-boxes.
foreach(array('buss_type','anotherfield','anotherfield','...etc') as $index)
{
    if (isset($this->request->post[$index])) {
        $this->data[$index] = $this->request->post[$index];
    } else {
        $this->data[$index] = NULL;
    }
}

Now, I am wondering how to write the query to send those values to my database, to a new table I just created (retailer). Every radio/checkform value has its column in my retailer table, how do I write the query so that all the values contained in $index go to their specific column.
The following is an example of how my other queries look like...
public function addCustomer($data) {
    //this is the one I am trying to write, and this one works,
    //but I'd have to add every single checkbox/radio name to the
    //query, and I have 30!
    $this->db->query("INSERT INTO " . DB_PREFIX . "retailer SET buss_t = '" .
            (isset($data['buss_t']) ? (int)$data['buss_t'] : 0) .
            "', store_sft = '" .
            (isset($data['store_sft']) ? (int)$data['store_sft'] : 0) .
        "'");
    //Ends Here
    $this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" .
            (int)$this->config->get('config_store_id') . "', firstname = '" .
            $this->db->escape($data['firstname']) . "', lastname = '" .
            $this->db->escape($data['lastname']) . "', email = '" .
            $this->db->escape($data['email']) . "', telephone = '" .
            $this->db->escape($data['telephone']) . "', fax = '" .
            $this->db->escape($data['fax']) . "', password = '" .
            $this->db->escape(md5($data['password'])) . "', newsletter = '" .
            (isset($data['newsletter']) ? (int)$data['newsletter'] : 0) .
            "', customer_group_id = '" .
            (int)$this->config->get('config_customer_group_id') .
            "', status = '1', date_added = NOW()");

Thanks a lot for any insight you can provide.

A: the best way would be to create a function that accepts an array and table name as an argument and executes a insert query.
function insertArray($table, $array)
{
  $keys =""; $values = "";
  foreach($table as $k=>$v)
  {
      $keys.=($keys != "" ? ",":"").$k:
      $values .=($values != "" ? "," :"")."'".$v."'";
  }
  $this->db->query("INSERT INTO ".$table." (".$keys.") VALUES (".$values.");
}

The array has to be structured like this:
 array("db_attribute1"=>"value1","db_attribute2"=>"value2");

A: Store the column names and column values in separate arrays and use implode() to generate a comma-separated list of columns and values
$values = array();
$columns = array('buss_type','anotherfield','anotherfield','...etc');
foreach($columns as $index)
{
    if (isset($this->request->post[$index]))
    {
        $this->data[$index] = $this->request->post[$index];
        $values[] = $this->db->escape($this->request->post[$index]);
    }
    else
    {
        $this->data[$index] = NULL;
        $values[] = "''";
    }
}

$this->db->query("INSERT INTO table_name (" . implode(",", $columns) . ") VALUES (" . implode(",", $values) . ");


text:
Q: Can a library(.jar) that is implemented in your project be able to access user data? Say I have considered to use a library by adding in project's gradle:
     implementation fileTree(dir: 'libs', include: ['*.jar'])

Can the code running in that jar file access the user details such as device id, location, files, etc.. if the user has granted those in my application?
I'm worried because I'm using some of those .jar libraries, but I cannot verify how trustworthy those are. I'm just worried about these libraries accessing such information and storing it on their servers.

A: Yes. If you call into the library's code at any point (or even cause its classes to be loaded), it can execute code with the same permissions as if you had written the code yourself.
As for why this is, once the app is compiled, everything ends up (more or less) being combined into the same bytecode file(s).  This is usually desirable - apps probably want libraries to use their app's permissions most of the time.  But it does mean that there's no easy way to "sandbox" a library's code to prevent it from using permissions/accessing/transmitting data.


text:
Q: VBA Kill function not deleting file I have written VBA code for Microsoft Word to send an email when a button is clicked. When the button is clicked, and the macro is completed, I would like the file to be deleted from the Desktop.
When I run this macro now, Microsoft Word closes out, but the file is not deleted from my desktop.
Here is my code:
Private Sub CommandButton1_Click()
Dim OL              As Object
Dim EmailItem       As Object
Dim Doc             As Document
Dim FileName        As String
Dim FilePath        As String
Dim DeletePath      As String

Application.ScreenUpdating = False
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
myFileName = "Form"
FilePath = "C:\Users\" & Environ("Username") & "\desktop\"
Doc.SaveAs2 FileName:=FilePath & myFileName & ".docx", Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
With EmailItem
    .Subject = "Bid Award Form"
    .Body = "Please Review the attached Bid Award form"
    .To = "EMAILADDRESS@DOMAIN.COM"
    .Importance = olImportanceNormal 'Or olImprotanceHigh Or olImprotanceLow
    .Attachments.Add Doc.FullName
    .Send
End With

    'display a message using named arguments
MsgBox _
prompt:="Your email has been sent. Please check your Outlook sent mail for confirmation", _
Buttons:=vbOKOnly, _
Title:="Email Confirmation"

'Close the File
Doc.Close

Kill "C:\Users\" & Environ("Username") & "\desktop\form.docx"

'Close the Application of the document we are going to delete
Application.Quit

Application.ScreenUpdating = True

Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing

End Sub

Any help that you can provide will be very helpful!

A: Probably you are looking at the wrong file. Kill is a function, that makes no mistakes.
Simply try the following:
Sub KillTheFile
    Kill "C:\Users\" & Environ("Username") & "\desktop\form.docx"
End Sub

Then see if it works. Probably you are having a file frm.docx or similar.

A: Try it like this instead
On Error Goto 0
Dim sDocName as string
sDocName = Doc.FullName
Doc.Close
Kill sDocName


text:
Q: What is the best way for protecting sensitive data in react-native? I have more sensitive data in my react-native App. As you know AsyncStorage is not secure so I decided to encrypt my data with crypto-js lib, then store it with AsyncStorage.
But I dont know, what is the best ways to keep secure my App. Also there is a nice package: react-native-keychain, but I am not to use any third party libraries as it makes my release package larger and also makes slower the app launching.

A: It is much more secure to use iOS Keychain / Android Keystore in most cases, especially if you are not a professional information security specialist. It also keeps data even if the app was removed.
This package will hardly make your app noticeably larger or app launching slower.
If you afraid of 3-rd party libraries you can always investigate the sources.


text:
Q: Mock Models and Stubbing for RSpec Controller Tests I'm testing the create method on a controller for my Viewings model with RSpec. I am trying to create a mock viewing model to minimize calls to my database, stubbing out its new and save methods and returning the appropriate values to test whether the logic of my controller is working:
describe 'POST #create' do
    let(:office_listing) { create(:office_listing) }
    let(:viewing) { mock_model(Viewing).as_null_object }
····
    before do·
      Viewing.stub(:new).and_return(viewing)
    end

    describe 'with valid attributes' do
      it 'saves the viewing' do·
        Viewing.any_instance.stub(:save).and_return(true)
        viewing.should_receive(:save)
        post :create, office_listing_id: office_listing.id
      end
    end

    describe 'with invalid attributes' do
      it 'fails and renders a failure message' do
        Viewing.any_instance.stub(:save).and_return(false)
        viewing.should_receive(:save)
        post :create, :office_listing_id => office_listing.id
        assigns(:failure_message).should_not be_nil
      end
    end
  end
end

here is my controller code:
def create
    @viewing = Viewing.new(params[:viewing])
    @viewing.broker = current_broker
    @viewing.office_listing = params[:office_listing_id]

    p @viewing.save

    if @viewing && @viewing.save == true
      respond_to do |format|
        format.js
        format.html { redirect_to root_path }
      end
    else
      respond_to do |format|
        @failure_message = "Unable to create viewing."
        format.js
        format.html { redirect_to root_path }
      end
    end
  end
end

The problem is that, even though I have stubbed out save to return true or false depending on the test I am in, it always returns a viewing object, which leads me to believe that the stubbing isn't working and the controller is treating my mock object as a real object, making a database call when I call .save. Do I need to be using a class other than Viewing to stub out the method? Should I just be calling viewing.stub instead of Viewing.any_instance? Actually I think typing that may have answered my own question, but I'd still like to hear anyone's thoughts on the issue.

A: You can't use both
Viewing.any_instance.stub(:save)

and
viewing.should_receive(:save)

The first one is use for control flow, whereas the second one is used to test something.
You should do:
let!(:viewing) { Viewing.new } # no lazy load, executed right away, no need to mock

def action
  post :create, office_listing_id: office_listing.id
end

before do
  Viewing.stub(:new).and_return(viewing)
end

it "calls save" do
  expect(viewing).to receive(:save).and_return(true)
  action
end


text:
Q: Finding edge and corner values of an image in MATLAB I am tracing the outline of an image and plotting this to a DXF file. I would like to use the bwboundaries function to find the coordinates of the edges of the image, find the corner coordinates using the cornermetric function and then remove any edge coordinates that are not a corner.
The important thing I need to be able to do is keep the order of the corner elements obtained from bwboundaries, so that the section traces properly. The DXF function I have, that draws from the coordinates, draws lines between coordinates that are next to each other, so the line has to be drawn "around" the section rather than straight between the corner points.
The reason I am doing this is because there are less coordinates obtained this way, so it is easier to amend the DXF file (as there are less points to manipulate).
The code I have so far is:
%# Shape to be traced
bw = zeros(200);

bw(20:40,20:180) = 1;
bw(20:180,90:110) = 1;
bw(140:180,20:185) = 1;

%# Boundary finding section
[Boundary] = bwboundaries(bw); %Traces the boundary of each section.

figure, imshow(bw); hold on;
colors=['b' 'g' 'r' 'c' 'm' 'y'];

for k = 1:length(Boundary)
   perim = Boundary{k}; %Obtains perimeter coordinates (as a 2D matrix) from the cell array.
   cidx = mod(k,length(colors))+1;% Obtains colours for the plot
   plot(perim(:,2), perim(:,1),...
          colors(cidx),'LineWidth',2);
end

Coordmat = cell2mat(Boundary) %Converts the traced regions to a matrix.

X = Coordmat(:,1)
Y = Coordmat(:,2) % This gives the edge coordinates in matrix form.

%% Corner finding section (from Jonas' answer to a previous question.

%# Get corners
cornerProbability = cornermetric(bw);

cornerIdx = find(cornerProbability==max(cornerProbability(:)));

%# Label the image. bwlabel puts 1 for the first feature, 2 for the second, etc.
%# Since concave corners are placed just outside the feature, grow the features.
%# A little before labeling
bw2 = imdilate(bw,ones(3));
labeledImage = bwlabel(bw2);

%# Read the feature number associated with the corner.
cornerLabels = labeledImage(cornerIdx);

%# Find all corners that are associated with feature 1.
corners_1 = cornerIdx(cornerLabels==1)

[Xcorners, Ycorners] = ind2sub(200,corners_1) % Convert subscripts

The code I have is, to give a matrix, Xfin, for the final x coordinates (which are on the edge AND at a corner.
Xfin = zeros(length(X),1)

for i = Xcorners
    XFin(i) = Xcorners
    if i~= Xcorners
        XFin(i) = []
    end
end

However, this does not work correctly, because the values in the solution are sorted into order, and only one of each value remains. As I said, I would like the corner elements to be in the same order as obtained from bwboundaries, to allow the image to trace properly.
(This problem links to two other questions I've asked on here.)

A: Here's a piece of code that does what you want to do. For every corner, it finds the closest boundary pixel, and remembers the index of the coordinate.
For this to work, you have to get the boundary as 4-connected boundary (i.e. write Boundary = bwboundaries(bw,4);. If you cannot use 4-connected boundaries for some reason, the corner extraction becomes a bit more complicated, since in that case, concave corners are not part of the boundary (note that with 8-connected boundaries, the inside corners are 'round' when you look at your green line).
EDIT
Here's the full code that works for me
%# Shape to be traced
% bw = zeros(200);
%
% bw(20:40,20:180) = 1;
% bw(20:180,90:110) = 1;
% bw(140:180,20:185) = 1;

%# alternative shape
bw = zeros(100);
bw(40:80,40:80) = 1;

%# Boundary Finding Section
[Boundary] = bwboundaries(bw,4); %Traces the boundary of each section

figure, imshow(bw); hold on;
colors=['b' 'g' 'r' 'c' 'm' 'y'];

for k=1:length(Boundary)
 perim = Boundary{k}; %Obtains perimeter coordinates (as a 2D matrix) from the cell array
 cidx = mod(k,length(colors))+1;% Obtains colours for the plot
 plot(perim(:,2), perim(:,1),...
        colors(cidx),'LineWidth',2);

end

Coordmat = cell2mat(Boundary) %Converts the traced regions to a matrix

X = Coordmat(:,1)
Y = Coordmat(:,2) % This gives the edge coordinates in matrix form

%% Corner Finding Section (from Jonas' answer to a previous question
%# get corners
cornerProbability = cornermetric(bw);

cornerIdx = find(cornerProbability==max(cornerProbability(:)));

%# Label the image. bwlabel puts 1 for the first feature, 2 for the second, etc.
%# Since concave corners are placed just outside the feature, grow the features
%# a little before labeling
bw2 = imdilate(bw,ones(3));
labeledImage = bwlabel(bw2);

%# read the feature number associated with the corner
cornerLabels = labeledImage(cornerIdx);

%# find all corners that are associated with feature 1
corners_1 = cornerIdx(cornerLabels==1)

[Xcorners, Ycorners] = ind2sub(size(bw),corners_1) % Convert subscripts

%% Here comes the new part

%# count corners
nCorners = length(Xcorners);
%# corner2boundaryIdx will contain the index of the boundary pixel
%# corresponding to a given corner
corner2boundaryIdx = zeros(nCorners,1);

%# remove last entry of Coordmat, because the first and the last pixel are
%# repeated
Coordmat(end,:) = [];

%# loop since we need to tread convex and concave corners differently
for i = 1:nCorners
    %# find distance of corner to boundary
    dist = sqrt((Coordmat(:,1)-Xcorners(i)).^2 + (Coordmat(:,2)-Ycorners(i)).^2);
    %# find index of closest boundary pixel. Use find
    %# instead of 2nd output of min, because we need to know how
    %# many closest indices there are in order to distinguish
    %# concave and convex corners. Convex corners are directly
    %# on the boundary, thus there is one minimum distance (0).
    %# Concave corners are just outside the boundary, thus, there
    %# are two minimum distances (1)
    minDistIdx = find(dist == min(dist));

    %# count how many minimum distances we have
    switch length(minDistIdx)
        case 1
            %# convex corners. Everything is simple
            corner2boundaryIdx(i) = minDistIdx;
        case 2
            %# concave corners. Take the index right in the middle. Note
            %# for this to work, you need to have 4-connected boundaries,
            %# otherwise, the concave corner is not part of the boundary
            %# becasue the boundary jumps along the diagonal.
            %# If you have to use 8-connected boundaries, the 'good'
            %# difference is 1, and you need to calculate the coordinate of
            %# the concave corner from the "corner" and the two adjacent
            %# boundary pixels.
            if diff(minDistIdx) == 2
            corner2boundaryIdx(i) = mean(minDistIdx);
            else
                error('boundary starts/stops at concave corner - case not handled yet')
            end
        otherwise
            error('%i minDist found for corner # %i',length(minDistIdx),i)
    end
end

%# All that is left to do is read the boundary pixel coordinates in the
%# right order
corner2boundaryIdx = sort(corner2boundaryIdx);
orderedCorners = Coordmat(corner2boundaryIdx,:);

%# plot corner numbers for confirmation
hold on
for i = 1:nCorners
    text(orderedCorners(i,2),orderedCorners(i,1),num2str(i),'Color','r')
end


text:
Q: Why should I use version control? I was reading a blog where the writer said this

"Code doesn't exist unless it's checked into a version control system. Use version control for everything you do. Any version control, SVN, Git, even CVS, master it and use it."

I have never used any sort of version control and I do not find it that great. I have googled it and looked at it before, but I just need it put into children's terms if you will please.
As I understand it right now, things like SVN are for storing your code online for a group of users or other developers to have access to the same code. Once you update some code, you can submit the new version and the SVN will keep copies of old code as well as the new ones you update.
Is this the basic idea of it or am I getting it completely wrong?
If I am right, then it might not be much use if I:

*

*Do not have other people working on the code.

*Do not plan on letting others have the code.

A: Version control is almost impossible to live without after you start using it. It is indispensible if more than one developers are working on the same code base...but it also quite useful for a single developer.
It tracks the changes in your code and allows you to roll back to previous versions. It frees you to experiment with the knowledge that if anything breaks you can undo your changes.

A: Even if you work alone you can benefit from source control. Among others, for these reasons:

*

*You don't lose anything. I never again commented out code. I simply delete it. It doesn't clutter my screen, and it isn't lost. I can recover it by checking out an old commit.

*You can experiment at will. If it doesn't solve the problem, revert it.

*You can look at previous versions of the code to find out when and where bugs were introduced. git bisect is great in that regard.

*More "advanced" features like branching and merging let you have multiple parallel lines of development. You can work in two simultaneous features without interference and switch back and forth without much hassle.

*You can see "what changed". This may sound basic, but that's something I find myself checking a lot. I very often begin my one-man workflow with: what did I do yesterday?
Just go ahead and try it. Start slowly with basic features and learn others as you go. You will soon find that you won't ever want to go back to "the dark ages" of no VCS.
If you want a local VCS you can setup your own subversion server (what I did in the past), but today I would recommend using git. Much simpler. Simply cd to your code directory and run:
git init

Welcome to the club.

A: You gain security (in the sense of having a back-up of your code) and versioning of your code (assuming you get into a habit of committing your changes often). Both are very good things even if nobody else ends up ever working on the code with you...

A: Version control is great for checking previous versions, even if you're working alone. For example, if you accidentally delete code or a file you can get it back; or you can compare previous versions to see why a new bug has crept in. It's also good if you're one person working in multiple locations.
My personal favourite is git.

A: There are a number of reasons to use version control, even if you are the only person who will ever touch the code.

*

*Backup - what if your hard-drive crashes?  Do you have a copy anywhere?

*Revision history - Do you currently keep copies of code in different folders?  Version control gives you the ability to track your changes over time and easily diff different revisions, merge, roll back changes, etc. using tools.

*Branches - the ability to test out some changes, still track what you are doing, and then decide whether or not you want to keep it and merge into the main project or just throw it away.

If you keep your code under version control, then it makes it really easy to see which files you have changed (or have forgotten to add to the baseline).

A: Something that no one else seems to have explicitly mentioned is the tagging or labeling of releases. If you have a client using version 1 of your software and you're busy working on version 2 what do you do when the client reports a bug and you need to build version 1.1?
A source control system will let you label every release you make so you can go back to it later, make the fix (and merge that fix into the new version 2 code) and make a new release without worrying that you might accidentally deliver something that isn't ready.
Source control is a core part of modern software development. If you're not using it (even for personal projects as the more experience you have the better) you're doing something wrong.
Usually one of the first questions I ask when being interviewed for a job is "What do you use for source control?" So far only one place has said "Nothing" but they were planning to fix that "Real soon now..."

A: Have you ever:

*

*Made a change to code, realised it was a mistake and wanted to revert back?

*Lost code or had a backup that was too old?

*Had to maintain multiple versions of a product?

*Wanted to see the difference between two (or more) versions of your code?

*Wanted to prove that a particular change broke or fixed a piece of code?

*Wanted to review the history of some code?

*Wanted to submit a change to someone else's code?

*Wanted to share your code, or let other people work on your code?

*Wanted to see how much work is being done, and where, when and by whom?

*Wanted to experiment with a new feature without interfering with working code?

In these cases, and no doubt others, a version control system should make your life easier.
To misquote a friend: A civilised tool for a civilised age.

A: The fact that other developers participate or not is totally orthogonal to the need of a version control system.
You can be the only developer but still will benefit from:

*

*a history trail of all your changes

*ability to go back and forward on that history

*ability to experiment with the source and while still having a working version (branching)

*a backup copy (especially if you use a different machine as the source control server, and even more if that machine is regularly backed up)

Now, if you have a group developing on the same codebase version control is still more necessary so

*

*people can edit the same file at the same time (depending on the particular system, but most sane ones allow you to do this)

*you can tell who did what to the code when

When there is more people involved it is more relevant which version control tool you pick, depending on the style of development.

A: Version control is a rare tool that I would say is absolutely required, even if you are only using it as a solo developer. Some people say that it's a tool that you live and die by, I agree with that assertion.
You probably use version control right now, even if you don't know it. Do you have any folders that say "XXX Php Code (December)" or "XXX.php.bak.2"? These are forms of version control already. A good version control system will take care of this for you automatically. You will be able to roll back to any point in time (that you have data checked in) and be able to see an exact copy of that data.
Furthermore, if you adopt a system like subversion, and use a remote repository (such as one on a server you own), you will have a place to keep all of your code. Need a copy of your code somewhere else? No problem, just check it out. Hard drive crash at home? Not an issue (at least with your source code).
Even if you don't use version control now, you will likely use it at one point in time later in your career and you could benefit from becoming more comfortable with the principles now.

A: Even working alone, has this ever happened? You run your app, and something does not work and you say "that worked yesterday, and I swear I did not touch that class/method." If you are checking in code regularly, a quick version diff would show exactly what had changed in the last day.

A: Here's a scenario that may illustrate the usefulness of source control even if you work alone.

Your client asks you to implement an ambitious modification to the website.  It'll take you a couple of weeks, and involve edits to many pages.  You get to work.
You're 50% done with this task when the client calls and tells you to drop what you're doing to make an urgent but more minor change to the site.  You're not done with the larger task, so it's not ready to go live, and the client can't wait for the smaller change.  But he also wants the minor change to be merged into your work for the larger change.
Maybe you are working on the large task in a separate folder containing a copy of the website.  Now you have to figure out how to do the minor change in a way that can be deployed quickly.  You work furiously and get it done.  The client calls back with further refinement requests.  You do this too and deploy it.  All is well.
Now you have to merge it into the work in progress for the major change.  What did you change for the urgent work?  You were working too fast to keep notes.  And you can't just diff the two directories easily now that both have changes relative to the baseline you started from.

The above scenario shows that source control can be a great tool, even if you work solo.

*

*You can use branches to work on longer-term tasks and then merge the branch back into the main line when it's done.

*You can compare whole sets of files to other branches or to past revisions to see what's different.

*You can track work over time (which is great for reporting and invoicing by the way).

*You can recover any revision of any file based on date or on a milestone that you defined.

For solo work, Subversion or Git is recommended.  Anyone is free to prefer one or the other, but either is clearly better than not using any version control.  Good books are "Pragmatic Version Control using Subversion, 2nd Edition" by Mike Mason or "Pragmatic Version Control Using Git" by Travis Swicegood.

Original author: Bill Karwin

A: Even as a single developer source control offers a great benefit.  It allows you to store your code's history and revert back to previous versions of your software at any time.  This allows you fearless flexibility to experiment because you can always restore to another version of your source code that was working.
It's like having a giant "undo" button all the way back to your first line of code.

A: It is also about backing up old file that why it is called "Subversion". So you can manage multiple version of your work in which you can return back (revert) and manage the different implementation of it (branching).

A: You may find that you had a working version of your program.
You decide to add a few new features over a period of time and you release that.
You start getting bug reports affecting some code that you thought you didn't touch.
By using SVN, for example, you can move back to an older version, and check to see if the new bug exists.  Once you find a version that introduced the bug it will be easier to fix it as you can compare the version that worked to what didn't work and see what changed, then it will narrow down the search.
Source control has many uses, even if you are the only developer.

A: Sounds like you're looking for something a bit more light-weight. Check out Mercurial (awesome reference book). I use it for everything, from source code to personal correspondence.
Some benefits:

*

*Giant Undo button, so you can return the those halcyon days of last week when the code actually ran

*Throw-away code. Not sure if this is the best way to do something? Make a branch and experiment. Nobody but you ever has to know about it if you're using a DVCS like mercurial.

*Syncronized development. I develop on 4 different computers. I push and pull between them to keep the current, so no matter which one I'm at I've got the newest versions.

A: Even if you haven't been in a situation yet where you needed an older version of your program, having a source control gives you greater confidence to make major changes.
I found myself doing more aggressive refactoring after using source control because I always knew that a working version could be easily restored.

A: I have also only recently begun to get interested in version control.  In version control systems, you have the concept of a repository for your code.  A wealth of new shell commands get learned very quickly so that you can interact with this repository.
Once you save your code to a file, you can then commit this to your project's repository.  As you develop your code and commit your changes the repository develops a series of revisions.  You can access any of these by checking out a revision.  If you work alone it's unlikely that you'll be doing much checking out unless you lose your code files or want to work on a different machine.  In these cases you'll usually check out the latest revision of all files.
For my own part, i no longer keep files or folders named 'project_old' when I decide to refactor something.  Any changes I make are stored incrementally and I will always be able to step backwards to a project that worked as a whole.  I rarely use FTP to deploy now because I just checkout my code through ssh.  Only the files I've changed are downloaded and if I need to reload on the server the terminal is already there.
I found this talk on GIT to be really instructive; http://www.youtube.com/watch?v=4XpnKHJAok8
It's a google talk where Linus Torvalds makes an argument for using one version control system over another.  In doing so he explains how they work using concepts and then compares different ways of implementing them.

A: You'll probably want something like subversion even if you're working by yourself so that you have a history of all your changes.  You might want to see what a piece of code looked like once upon a time to remember why you made a change.
Having source control is also useful when you check in often.  If you check in often, you'll always be in a state to roll back often too.  Many times you could start going down one path to solve a problem and then realise it was the wrong path to go.  Many times you could just keep barking down the wrong path and end up building a terrible solution - only because you didn't want to lose all your work.  By checking in often, the last point of "happiness" is not far away so even if you go down the wrong path you can always roll back and try again and make a more elegant and simple solution.  Which is always a good thing so you can understand and maintain what you wrote in the future.

A: It depends on the size of the project and how often you change your mind about parts of it. For small projects where you're just getting something done in a linear fashion, version control is probably not going to be of much help (though if you accidentally delete or corrupt a file without version control, you'll be crying).
But a couple of weeks ago I met a friend who was writing an enormous hobby project on his own. He had ten or twenty copies of his code, with suffixes like "X1", "X2", "test", "faster" and so forth.
If you've made more than two copies of your code, you need version control. A good version control system lets you undo a change you made a while ago without undoing the stuff you did after making that change. It lets you see when certain changes were made. It lets you split your code into two "paths" (e.g. one for testing out a new idea, the other to keep your "tried and trusted" code safe until you've finished testing) and then merge them back together.

A: It is 2019. I am encountering objections, at this relative late date, to using Git; objections I see some raising here. This discussion has clarified greatly the imperative of using source control rather than simply making named back-up copies. One key point is source control use even where we've single developer projects. Nobody is perfect. You make mistakes. If you're exceptionally good and smart you're going to be developing more complex apps; but you're still gonna make some mistakes and this handles it.  Geez oh Pete! I never use Linux but I think we all respect the great technical intelligence of Linus Torvalds. He recognized the importance of source control and he made key contributions to the inception of Git. That's a summary point for all the reasons given here. Torvalds gets it: source control is very important: use source control.  Thanks to all who've commented on this long running topic.


text:
Q: Sync ajax without jquery? How to perform a sync ajax call without using jquery?
Clarification: because there is a need to load a remote JSON resource before any of remote js scripts are executed, and then continue page loading.

A: Yes you can:

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}

This question has been answered, I believe, here on how to do a non-ajax call: STACKOVERFLOW  and here is how to make in synchronous (where I got this answer from) MOZILLA


text:
Q: Which pronoun: 'them' or 'themselves'? Which would make a more suitable pronoun in the following sentence: them or themselves?
The boys wear sunglasses to shield them / themselves from the hot sun.

A: The boys shielded themselves from the hot sun with an umbrella.
The boys shielded their eyes from the sun with sunglasses.
If you are only shielding your eyes, you probably wouldn't say shield yourself but rather shield your eyes. If you are shielding your whole body, shield themselves is right.


text:
Q: Android SupportMapFragment can't see map inside a fragment I'm trying to add a SupportMapFragment into a FrameLayout in my code but i get a Null Pointer Exeption.
My Code:
MainFragment:
public class MainFragment extends FragmentActivity{

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft = getSupportFragmentManager().beginTransaction();
        SecondFragment second = new SecondFragment();
        ft.add(R.main_activity.frame, second);
        ft.addToBackStack(null);
        ft.commit();
    }
}

SecondFragment:
public class SecondFragment extends SupportMapFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_map, null);
    }
}

My XML:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <include
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        layout="@layout/header" />

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="7.06"
        android:id="@+main_activity/frame"
        android:background="@drawable/defaultbg"/>

    <include
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_gravity="bottom"
        android:layout_weight="1"
        layout="@layout/footer" />

</LinearLayout>

activity_map:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</FrameLayout>

My Logcat:
03-07 21:20:17.160: E/AndroidRuntime(1617): FATAL EXCEPTION: main
03-07 21:20:17.160: E/AndroidRuntime(1617): java.lang.RuntimeException: Unable to resume activity {com.WhosAround/com.WhosAround.MainFragment}: java.lang.NullPointerException
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2124)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2139)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1672)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.os.Looper.loop(Looper.java:130)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.ActivityThread.main(ActivityThread.java:3691)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at java.lang.reflect.Method.invoke(Method.java:507)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at dalvik.system.NativeStart.main(Native Method)
03-07 21:20:17.160: E/AndroidRuntime(1617): Caused by: java.lang.NullPointerException
03-07 21:20:17.160: E/AndroidRuntime(1617):     at maps.z.r.onResume(Unknown Source)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.google.android.gms.maps.internal.IMapFragmentDelegate$Stub.onTransact(IMapFragmentDelegate.java:115)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.os.Binder.transact(Binder.java:279)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.google.android.gms.maps.internal.IMapFragmentDelegate$a$a.onResume(Unknown Source)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.google.android.gms.maps.SupportMapFragment$a.onResume(Unknown Source)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.google.android.gms.internal.e$1.a(Unknown Source)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.google.android.gms.internal.e.a(Unknown Source)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.google.android.gms.internal.e.onResume(Unknown Source)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at com.google.android.gms.maps.SupportMapFragment.onResume(Unknown Source)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.support.v4.app.Fragment.performResume(Fragment.java:1503)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.support.v4.app.FragmentManagerImpl.dispatchResume(FragmentManager.java:1871)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.support.v4.app.FragmentActivity.onResumeFragments(FragmentActivity.java:455)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:444)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.Activity.performResume(Activity.java:3867)
03-07 21:20:17.160: E/AndroidRuntime(1617):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2114)
03-07 21:20:17.160: E/AndroidRuntime(1617):     ... 12 more

A: Your simply forgetting to call super.onCreateView(); in your SecondFragment.
If you override onCreateView() of SupportMapFragment you need to remember to call the super method as this is where all the "action" happens.

A: I have same problem too, so my temporary solution is don't use SupportMapFragment to change using MapFragment.
hope this can help you.


text:
Q: Unitary matrices and preservation of inner product - necessary and sufficient? Suppose we have two vector functions, $\vec{a}(z):\mathbb{R}\rightarrow\mathbb{C}^n$, and $\vec{b}(z):\mathbb{R}\rightarrow\mathbb{C}^n$. Suppose also that the following equation holds:
(1) $$\langle\vec{a}(x),\vec{a}(y)\rangle=\langle\vec{b}(x),\vec{b}(y)\rangle,\forall(x,y)\in\mathbb{R},$$
where $\langle\cdot,\cdot\rangle$ indicates the Hermitian inner product. Clearly it is sufficient that there exists a unitary matrix $\mathbf{U}$ which is independent of $z$ such that
(2) $$\vec{a}(z)=\mathbf{U}\vec{b}(z), \forall z \in \mathbb{R}.$$ In other words, $(2)\Rightarrow(1)$. Is this condition also necessary? That is, $$(1)\overset{?}{\Rightarrow}(2).$$
If not, can we find a counter-example?

Indeed, for $n=1$ this would mean $$a(x)a^\ast(y)=b(x)b^\ast(y),\forall(x,y)\in\mathbb{R}\Rightarrow a(z)=e^{i\phi}b(z),\phi\in\mathbb{R}.$$ This case can be easily shown: We have $$\frac{a^\ast(y)}{b^\ast(y)}a(x)=b(x),\forall(x,y)\in\mathbb{R}\\ \Rightarrow \frac{a^\ast(y)}{b^\ast(y)}=k\in\mathbb{C} \\
\Rightarrow a(x)a^\ast(y)=|k|^2a(x)a^\ast(y)\\
\Rightarrow k=e^{i\phi}\\ \Rightarrow a(z)=e^{i\phi}b(z)$$

A: We assume that, for every $x,y$: $(a(x),a(y))=(b(x),b(y))$ for the standard hermitian product and we construct a unitary matrix $U$ s.t. $a=Ub$.
Assume that $span(im(a))=\mathbb{C}^n$ ; let $(x_i)_{i\leq n}$ s.t. $(a(x_i))_i$ is a basis of $\mathbb{C}^n$. Since $(a(x_i),a(x_j))=(b(x_i),b(x_j))$, $(b(x_i))_i$ is also a basis and there is a unitary matrix $U$ s.t., for every $i\leq n$, $a(x_i)=Ub(x_i)$.
Thus, for every $i$, $(a(x),a(x_i))=(b(x),b(x_i))=(a(x),Ub(x_i))$, that is $(b(x),b(x_i))=(U^{-1}a(x),b(x_i))$. Finally $U^{-1}a(x)=b(x)$, that is $a=Ub$.
EDIT: if $E=span(im(a))$ is not $\mathbb{C}^n$, then we show, in the same way that there is $V$, unitary on $E$ s.t. $a=Vb$. There is $U$ unitary on $\mathbb{C}^n$ s.t. $U_{|E}=V$.


text: Q: synchronize all users in keycloak I have insatlled the Keycloak server and the 389-ds on an ubuntuserver20.04 on a virtualbox . For testing the connection and the authentication i have added some users and groups in 389-ds . On the server console management on keycloak works the ,, test connection,, without any error message . The ,, test authentication ,, is also working properley . But when i click on the ,, synchronize all users ,, on the keycloak under the user federation , i get the message ,, success ! sync of users finished successfully . 0 imported users , 0 updated users ,, . The users on 389-ds dont have any email or password , they are just simple users with uid and ou to test . Could you please give me any tips ? thanks :))


text:
Q: mastermind, cannot get distinct characters in a String. Booolean Method does not execute. I am trying to create a Mastermind game in which colors are numbers [] and one number can never repeat itself in the String. The string should be made of 4 characters. I cannot figure out why my code keeps on printing strings with repeated characters.
import java.util.Random;
import java.util.Scanner;
public class Question1

{
public static void main(String[] args)
{
    String toGuess="";

    while(!IsValidNumber(toGuess));
    {
        for(int i=0; i<4; i++)
        {
            Random rando= new Random();
            int rd=rando.nextInt(9);

            toGuess=toGuess+rd;

        }
    }
    System.out.println(toGuess);
}

public static boolean IsValidNumber(String s) // boolean
{
    boolean noRepetition = true;
    for(int i = 0; i < s.length(); i++)
    {
        for(int j = 0; j < i; j++)
        {
            if(i == j)
            {
                continue;
            }
            else if(s.charAt(i) == s.charAt(j))
            {
                noRepetition = false;
                return false;
            }
        }

    }
    return noRepetition;
}
}

The boolean IsValidNumber never operates, I tried to print simple check words at different levels of it, and nothing ever prints but the String.
Thanks in advance, cheers

A: You've got a stray semicolon after the while() declaration, which causes the loop to immediately end. Consequently, your for loop constructs a number, and whatever number it constructs is immediately printed.
Consider the following instead:
public static void main(String[] args)
{
   String toGuess="";

   do { // Always try to generate at least one number.
       toGuess = ""; //Reset each time we loop.

       for(int i=0; i<4; i++) {
            Random rando= new Random();
            int rd=rando.nextInt(9);
            toGuess=toGuess+rd;
        }
    } while(!IsValidNumber(toGuess));

    System.out.println(toGuess);
}

That might work better.
Basically, while (exp); is equivalent to while(exp) {} or an empty while loop. Only put a semicolon after your while(exp) when using the do...while construct I illustrate here.


text:
Q: How to check if app is updated or fresh install in Windows Phone 8? I am developing an app in Windows phone 8. Can I determine through some App data if its a fresh install or an updated app on that device?

A: string currentAppVer = string.Empty;
var xmlReaderSettings = new XmlReaderSettings { XmlResolver = new XmlXapResolver() };
using (var xmlReader = XmlReader.Create("WMAppManifest.xml", xmlReaderSettings))
{
     xmlReader.ReadToDescendant("App");
     currentAppVer = xmlReader.GetAttribute("Version").Replace(".", "");
}

try
{
     if ((Convert.ToInt32(currentAppVer)) < (Convert.ToInt32(response.appVersion)))
     {
          MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
          marketplaceDetailTask.ContentIdentifier = App.appContentIdentifier;
          marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;
          marketplaceDetailTask.Show();
          Application.Current.Terminate();
     }
}
catch (Exception ex)
{ }

Where response.appVersion is the Application Version that you can maintain in IsolatedStorageSettings OR in Database...


text:
Q: MySQL count distinct and show its label Hello I have a sample table called tblapplicants
and there is referral column on that table. Where all records contains different referral values with duplicated referral values like this
ID | referral
 1 | Internet
 2 | Internet
 3 | News
 4 | News
 5 | News

and I wanna get something like this
referral | count
Internet | 2
News     | 3

to select referral column and count distinctly all the records and declare count column

A: you should use count and group by in sql
SELECT
  referral
  , count(referral) as count
FROM
  tblapplicants
GROUP BY
  referral;


text:
Q: Multiplayer movement in JavaScript this is my client: http://pastebin.com/C9PHzTQg
this is my server: http://pastebin.com/j2dfL84d
Now is "multiplayer" rect's, but how to do movement?
I am send to 'b' - "UP", "LEFT", "RIGHT", "DOWN" and how to handle ant move player?
Sorry for my bad english language.

A: First, you need to learn prototypical inheritance! As it is, each Player will have it's own copy of the draw method, so put draw on Player.prototype instead:
var Player = function(context, x, y) {
    this.context = context;
    this.x = x;
    this.y = y;
};

Player.prototype = {
    draw: function() {
        this.context.fillRect(this.x, this.y, 16, 16);
    }
};

Then, I suggest you add a move method to Player:
Player.prototype = {
    draw: function() {
        this.context.fillRect(this.x, this.y, 16, 16);
    },

    move: function(direction) {
        // direction is "UP", "DOWN", "LEFT" or "RIGHT"
        switch(direction) {
            case "UP":
                this.y += 16;
                break;
            // ...
        }
    }
};

Then, in your message handler, you just have to:
socket.on('b', function(data) {
    players[data.player].move(data.direction);
    draw();
});

In the server, you would emit('b', { player: playerId, direction: "UP" }, for example.
Update: Instead of draw inside socket.on('b', ... above, you could have something like:
setInterval(draw, 100);

To redraw every 100 ms. It depends on the type of game, I guess.