text:
Q: How to use useState with {}? given this..
const [question, setQuestion] = useState({})
and question can contain a title and a description.
I.E.
{
  title: 'How to use useState with {}?',
  decription: 'given this..`const [question, setQuestion] = useState({})`and `question` can contain a title and a description. I.E.    {       title: 'How to use useState with {}?',       decription: ''     }How can the title and description be set independently with `setQuestion`?'
 }

How can the title and description be set independently with setQuestion?

A: The setter function you get from useState() expects to be passed argument which will entirely replace the old state. So you can't use it to update just the title, without also passing in all other properties.
But you can derive a new state object from the existing one and then pass that whole object to setQuestion()
setQuestion({
   ...question,
   title: "New title",
})

A: One thing that I like to do in this situation is to use the React.useReducer hook instead:
function App() {
  const initialState = {
    title: 'My title',
    description: 'My description'
  }
  const [state, setState] = React.useReducer(
    (p, n) => ({ ...p, ...n }),
    initialState
  )
  return (

{state.title}

{state.description}

      <button onClick={() => setState({ description: 'New description' })}>
        Set new description
      </button>

  )
}

This way, you're only changing the properties that you want and don't have to deal with copying the old state object and creating a new one based on old and new values.
Also, it will probably look more familiar to you if you're just starting with hooks because of the similarity to the this.setState() calls inside class components.
Here's a little example that shows this approach in action:

*

*example

A: If this is a common pattern you use then I'd suggest writing your own hook to implement the functionality you want.
If it's a one-off thing then you can use the object spread operator to do it fairly cleanly:
setQuestion({
  ...question,
  title: 'updated title',
});

Here is what it would look like pulled out into a separate hook:
const useMergeState = (initial) => {
  const [state, setState] = React.useState(initial);
  const mergeState = React.useCallback((update) => setState({...state, ...update}));
  return [state, mergeState];
};

A: The official Docs says:

Both putting all state in a single useState call, and having a
  useState call per each field can work. However, components tend to be most
  readable when you find a balance between these two extremes, and group
  related state into a few independent state variables.

Eg:
  const [position, setPosition] = useState({ left: 0, top: 0 });
  const [size, setSize] = useState({ width: 100, height: 100 });

In case the state logic becomes complex, we recommend managing it with a reducer or a custom Hook.

Also, remember in case you are using any state object in the useState({}) hook, that unlike the classic this.setState, updating a state variable always replaces it instead of merging it, so you need to spread the previous state in order not to lose some of his properties eg:  setResource(…resource, name: 'newName');

A: setQuestion({
  title: 'YOUR_TITLE',
  description: 'YOUR_DESCRIPTION',
  id: '13516',
})

State cannot be edited. You need to set new value always. Thus, it can be replaced with spread operator as below.
setQuestion({
  ...question,
  title: 'new title'
})

or
const newQuestion = { ...question, title: 'new title }
setQuestion(newQuestion)


text:
Q: Java JOptionPane with LIFO stack's I'm taking a course in java and now I got stuck in a problem which is probably very obvious and clear, but I cant find any answer on the internet so i decided to come here and personally ask you guys.
So.. JOpitionPane to display LIFO (Last In First Out) stack.
In my code below I'm using System.out.println as an example to show what I want it to do. What I need it to do is to display it in a JOptionPane.showMessageDialog box.
I somehow cant figure it out, creating an array to stack the amount you want to display is my guess, but I don't know how to move forward from here.
Many thanks to whoever could answer my question.
Here's my simplified code-text for this question.
import java.util.Stack;
import javax.swing.JOptionPane;

public class Test1 {
public static void main(String args[]) {
    new Test1();

}

public Test1() {

    boolean status = false;

    Stack<String> lifo = new Stack<>();

    while (!status) {
        String s = (JOptionPane.showInputDialog("Write something"));

        if (s == null) {

            status = true;

        } else {
            lifo.add(s);
        }

    }
    if (status == true) {
        Double num = Double.parseDouble(JOptionPane.showInputDialog("How many of latest Input would you like to see?"));
        for (int i = 0; i < num; i++) {
            System.out.println(lifo.pop()); //Here is where i would want
            System.out.print(',');          //JOptionPane.showMessageDialog instead.
        }

A: You would build the string in memory and then use it as the message for showMessageDialog.  Something like:
String msg = "";
for (int i = 0; i < num; i++) {
    if (i > 0)
       msg += ",";  // could replace this with a newline to have the numbers stacked
    msg += lifo.pop();
}
JOptionPane.showMessageDialog("title", msg, ....);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Erro em alguns computadores ao tentar capturar a tensão do processador pelo WMI Em apenas alguns computadores ao executar o meu programa de especificação de hardware ele acusa um erro na linha 155.
public static String voltage()
            {
                String Ic = String.Empty;
                foreach (var item in new ManagementObjectSearcher("Select from Win32_Processor").Get())
            {
                   Ic = (decimal.Parse(item["CurrentVoltage"].ToString()) / 10).ToString() + " v";
                    if(Ic == "0")
                    {
                        return "~";
                    }
                }
                return Ic;
            }

Linha 155 abaixo.

Ic = (decimal.Parse(item["CurrentVoltage"].ToString()) / 10).ToString() + " v";

E impede que meu programa continue rodando normalmente mas é apenas em alguns computadores, no geral o programa roda sem erros.


text:
Q: Why is the alert not displayed in a new window I am creating a new window with some variable as follow:
var setScript = "<script>alert('test');<//script>";
var w = window.open();
var createBody = $(w.document.body);
var createHead = $(w.document.head);
createBody.html("");
createBody.html(p);
createHead.html(setStyle);
createHead.append(setScript);

I am not seeing the alert in the new window.
How can I resolve the issue.
F12:

A: Here's what you should do :
<script>
  (function(){
     var body=document.getElementsByTagName('body')[0],
         head=document.getElementsByTagName('head')[0],
         script=document.createElement('script');

     //Do stuff with body

     script.onload = function() {
      alert("foo");
     };

     head.appendChild(script);
   })();
</script>

A: something like this?  http://jsfiddle.net/swm53ran/222/
use document.write on the new window
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    var myWindow = window.open();
    myWindow.document.write("<script>alert('test');<\/script>");
}
</script>

A: Have you check your error console?
Firebug give me this:
SyntaxError: expected expression, got '<'

alert('test');<//script>

And like @j08691's comments you should change your first line code to this:
var setScript = "<script>alert('test');<\/script>";


text:
Q: Best way to get around web crawl throttling for Amazon.com I have a process that runs daily that crawls a list of movie prices on Amazon. Because Amazon doesn't expose all prices in their product search API, web crawling is the only way to get the ASINs, then based on the ASINs use their product search API to get the price.
However, after a few thousand web crawls, Amazon starts throttling and throwing a capcha page which I can no longer parse the ASIN from.
I'm thinking that a good solution would be to switch IPs to get around the throttling. My service runs rails on Heroku, is there a good way to implement IP switching?

A: Found a few solutions with proxies:
https://www.ruby-forum.com/topic/510798
Get past request limit in crawling a web site


text:
Q: reassignment python modules's variable, but function use that var as default don't change there is example code:
# b.py
c = False
def d(i=c):
    print(i, c)

I want to write a.py to let the output of b.d to be True, True:
# a.py
import b
b.c = True
b.d()

but the output is False, True.
so, why and how to get it?

write after answer
to why:
# `inspect` may be useful
import inspect
v = True
def f(i=v):
    print(i, v)

s = inspect.signature(f)
s.parameters
Out[6]: mappingproxy({'i': <Parameter "i=True">})

A: This is unnecessarily complicated -- we can boil down your question to a few lines:
default = "Before"

def foo(bar=default):
    print(bar)

foo()              # "Before"
default = "After"
foo()              # "Before"

The behavior it seems you expect is that after default = "After", calling foo() will print "After".  But it continues to print "Before".
Python will evaluate the default argument for a function once and "lock it in".  Reassigning the name of default to something else later has no effect (as we see in the snippet above).
Instead, you can use an approach that's commonly suggested when people want lists as default arguments:
default = "Before"

def foo(bar=None):
    if bar is None:
        bar = default
    print(bar)

foo()              # "Before"
default = "After"
foo()              # "After"

In this case, you're not trying to change the default argument, but rather change what is assigned to bar when no argument is specified.  Each time you call foo() with no argument, it'll be assigned None and then the logic inside the function will look up and use the value of the global default.

A: That's because the default value is evaluated once at the creation of the function.
def d(i=c):
    print(i, c)

Here, after the import b line, the d function becomes
def d(i=False):
    print(i, c)

So changing c has no effect on the default value of i in d.


text:
Q: NOPCommerce AD integration I'm setting up an intranet ecommerce site with NOPCommerce 2.5 and I want the user to be automatically logged on to the site. Everybody on the network is authorized to be customer. Is there an active directory integration for NOPCommerce or does anybody have tips & tricks on how to move forward?

A: I know that nopCommerce uses their own implementation of the ASP.net Membership Provider. So yes, it is possible to edit that, and have it automatically generate a nopCommerce user via the Network Credentials.
I'm not aware of anything that already exists for this functionality.


text:
Q: Programmatically configure Eclipse Installed JREs I want to configure my Eclipse environment to use the JDK instead of the standard JRE. I'm doing this because I use m2eclipse, which requires tools.jar from the JDK to run.
I'm running Eclipse 3.5.1 on Windows 7 32-bit with JDK 1.6.0_16.
On my system, I have the JDK installed to "C:\Program Files\Java\jdk" (symlink to the latest install).
I add the -vm option to eclipse.ini to point to the JDK
-vm
C:/Program Files/Java/jdk/bin

I've confirmed that eclipse is in fact starting with the desired JVM. In the configuration details
eclipse.vm=c:/Program Files/Java/jdk/bin\..\jre\bin\client\jvm.dll

Additionally, in my environment,
JAVA_HOME=c:\Program Files\Java\jdk

However, in Window | Preferences | Java | Installed JREs, the only JRE listed is the one in "C:\Program Files\Java\jre6". This JRE ends up being the one under which Maven is run, and so my maven builds fail.
I know I can manually change the Installed JRE to point to the JDK, and this is what I've done in the past. However, I'd like to find a way to script this change so that I can automate the installation of a dev environment.
Where is this setting stored? What is the best way to automatically configure Eclipse to use the JDK as the only Installed JRE?

A: The setting is stored in
<workspace>\.metadata\.plugins\org.eclipse.core.runtime\.settings\org.eclipse.jdt.launching.prefs

I would recommend setting your JDK manually in Preferences / Java / Installed JRE, as well as  Preferences / Java / Installed JRE / Execution Environment.
Then, whenever you need an eclipse with that exact configuration, just copy over this file with your preset config file, and launch that eclipse.
Extract from that config file:
org.eclipse.jdt.launching.PREF_DEFAULT_ENVIRONMENTS_XML=
  <?xml version\="1.0" encoding\="UTF-8" standalone\="no"?>
  <defaultEnvironments>
      <defaultEnvironment environmentId\="JavaSE-1.6"
                          vmId\="57,org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType13,1255369536255"/>
  </defaultEnvironments>

 eclipse.preferences.version=1
 org.eclipse.jdt.launching.PREF_VM_XML=
   <?xml version\="1.0" encoding\="UTF-8" standalone\="no"?>
       <vmSettings defaultVM\="57,org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType13,1255369536255">
            <vmType id\="org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType">
                <vm id\="1255369536255"
                    javadocURL\="http\://java.sun.com/javase/6/docs/api/"
                    name\="jdk1.6.0_16" path\="C\:\\Prog\\Java\\jdk1.6.0_16">
                <libraryLocations>
                    <libraryLocation jreJar\="C\:/Prog/Java/jdk1.6.0_16/jre/lib/resources.jar"
                                     jreJavadoc\="http\://java.sun.com/javase/6/docs/api/"
                                     jreSrc\="C\:/Prog/Java/jdk1.6.0_16/src.zip"
                                     pkgRoot\=""/>


text:
Q: amqplib nodejs to consume rabbitmq this is how i consume the queue in rabbit, i wonder why this promise still hangs and return no result. i am trying to hit an endpoint that call this promise and expect it to return just ok to make sure it gives me a 200 OK status. now it acts like it somehow does not get any return from this service, i wonder what i did wrong. thanks
return new Promise((resolve,reject) => {
            try{
                rabbit.then(conn => {
                  return conn.createChannel();
                })
                .then(ch => {
                  let shit = ch.assertQueue(USER_LOG_QUEUE)
                  .then(ok => {
                    if(ok.messageCount > 0){
                        return ch.consume(USER_LOG_QUEUE, function(msg) {
                            if (msg !== null) {
                                ch.ack(msg);
                                writeToFile(msg.content.toString())
                                .then(rs => {
                                    console.log(rs);
                                })
                                .catch(err => reject(err));
                            }
                            console.log('finished');
                            ch.close();
                            resolve(ok);
                        })
                    }else{
                        console.log('empty list : finished');
                        ch.close();
                        resolve(ok);
                    }
                })
                .then(ok => {
                    console.log('empty list2 : finished');
                    resolve(ok)
                })
                .catch(err => reject(err));
            }catch(err){
                reject(err);
            }
        });


text:
Q: Суть проблемы исключающего или Недавно я стал интересоваться нейронными сетями и машинным обучением. В какой то статье прочитал, что нейронная сеть, которая решает проблему XOR, это своего рода "Hello world"-программа в машинном обучении.
Вопрос такой. В чем суть проблемы XOR?
В гугле есть информация как ее решить и я понимаю что выполняет оператор XOR, но я все равно не могу понять саму суть задачи и что нужно решить.

A: Суть проблемы XOR в том, что простейшая нейроная сеть, Перцептрон, представляет из себя одну разделяющую черту, а представление оператора XOR:
1 |1    0
  |
0 |0____1
  0     1

Как видите, нельзя разделить одной линией на два класса - нули и единицы.
Подробный разбор по ссылке.


text:
Q: How to use .byCharWrapping for a specific character? How would I do something similar to .byCharWrapping for a label where the text is in the form of "soccer", "basketball", "hockey", "volleyball" and I want to wrap by commas so that the displayed text would be e.g. "soccer", "basketball", "hockey" if "volleyball" doesn't fit within the label.

A: I think you can fit your text with another solution , you can also fit your text in label with font size : like below line and you can put it on if conditions :
label.font = UIFont.systemFont(ofSize: 17)

A: You can determine the actual width of string with font, then do whatever you want if that width is less than labels width.
See here size(withAttributes:)


text:
Q: JavaScript - Finding all combinations including individual and dual combinations? I have an array of objects I am trying to find all the combinations for. I have got some code that finds all the combinations, however it only find the number of combinations based on the length of the input array.
For example if I use the below array and with the function below I get 27 potential combinations, however that doesn't include elements on their own or in twos.
[
[{ optionName: "red" },{ optionName: "blue"  },{ optionName: "green" }],
[{ optionName: "S" },{ optionName: "L" },{ optionName: "XL" }],
[{ optionName: "spotted" },{ optionName: "striped" },{ optionName: "lined" }],
]

For example I get combinations that look like this:
[{ optionName: "red" },{ optionName: "L"  },{ optionName: "spotted" }]
[{ optionName: "red" },{ optionName: "S"  },{ optionName: "spotted" }]
[{ optionName: "red" },{ optionName: "S"  },{ optionName: "lined" }]

However I want to also include combinations like:
[{ optionName: "red" }]
[{ optionName: "red" },{ optionName: "S"  }]
[{ optionName: "red" },{ optionName: "L"  }]

This is the code I am working with:
       var r = [],
        arg = arrayCombOptions,
        max = arg.length - 1;
      function helper(arr, i) {
        for (var j = 0, l = arg[i].length; j < l; j++) {
          var a = arr.slice(0);
          a.push(arg[i][j]);
          if (i == max) r.push(a);
          else helper(a, i + 1);
        }
      }
      helper([], 0);

How do I find all the combinations including individual and dual combinations?

A: You could add for each inner array a dummy like undefined, generate a cartesian product, map only arrays without undefined and slice the array from one, because the first is empty as well.

var data = [[{ optionName: "red" }, { optionName: "blue" }, { optionName: "green" }], [{ optionName: "S" }, { optionName: "L" }, { optionName: "XL" }], [{ optionName: "spotted" }, { optionName: "striped" }, { optionName: "lined" }]],
    result = data
        .map(a => [undefined, ...a])
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
        .map(a => a.filter(Boolean))
        .slice(1);

console.log(result.length);
document.getElementById('out').innerHTML = JSON.stringify(result, null, 4);

A: A clean and simple solution:
You need to iterate through the array of arrays and for each individual array find all of the possibilities.
const addToEach = (element, arr) => [...arr, element];

const getAllPossibilitesForSingleArr = (arr) => {
  let r = [];
  for(let i=0;i<arr.length;i++) {
    const combinationsSoFarWithNewElementAdded = r.map(ar => addToEach(arr[i],ar))
    r.push(...combinationsSoFarWithNewElementAdded, [arr[i]]);
  }
 return r;
};

const getAllPossibilitesForArrays = arrays => arrays.map(getAllPossibilitesForSingleArr);

In order to find every possibility in a single array I have iterated through the array and in each iteration, I am expanding the result array with a new element and all combinations so far with the new element added.
You can also do it with pure functions (always better):
const getAllPossibilitesForSingleArrFunc = (arr) =>
  arr.reduce((acc, curr,i) => {
    const combinationsSoFarWithNewElementAdded = acc.map(ar => addToEach(arr[i],ar))
    return [...acc, [arr[i]], ...combinationsSoFarWithNewElementAdded]
  },[]);

const getAllPossibilitesForArraysFunc = arrays => arrays.map(getAllPossibilitesForSingleArrFunc);


text:
Q: Shadow on UILabel does not appear I want to add a little shadow to my UILabel, but it is not showing up.
companyLabel.textAlignment = UITextAlignmentLeft;
        companyLabel.font = [UIFont fontWithName:@"Arial" size:13];
        companyLabel.adjustsFontSizeToFitWidth = YES;
        companyLabel.minimumFontSize = 10.0;
        companyLabel.backgroundColor = [UIColor clearColor];
        companyLabel.textColor = [UIColor colorWithRed:103.0/255.0 green:103.0/255.0 blue:103.0/255.0 alpha:1.0];
        companyLabel.layer.shadowColor = [[UIColor colorWithRed:241.0/255.0 green:241.0/255.0 blue:241.0/255.0 alpha:1.0] CGColor];
        companyLabel.layer.shadowOffset = CGSizeMake(0.0, -1.0);
        companyLabel.highlightedTextColor = [UIColor whiteColor];

A: You're not setting shadowOpacity, which defaults to 0.0. You need to set that to something else to make the shadow show up. However, there's no reason to even touch CALayer right now because UILabel has its own shadowColor and shadowOffset properties.
companyLabel.shadowColor = [UIColor colorWithRed:241.0/255.0 green:241.0/255.0 blue:241.0/255.0 alpha:1.0];
companyLabel.shadowOffset = CGSizeMake(0.0, -1.0);


text:
Q: Sci Fi/Adventure Anime of the late 70s or 80s I am looking for an old anime movie from 30-40 years ago, which was released on VHS in Germany.
It was definitely Japanese style anime, definitely hand drawn. I think it was a sci-fi setting, because they were using strange weapons (exploding marbles). I am not exactly sure if it was dubbed in German, English or even if it was in Japanese. I am about sure it was not a series but instead a whole movie.
I barely know anything about it anymore, the only thing I remember clearly that there were three young boys, trying to escape from something on bikes/scooters? I think three young boys and one of them drops exploding marbles.
I can't get that out of my head, maybe someone has an idea what I watched at that time.
Sorry for having not much information, I was like 6-7 and this is like 35 years back now.
Maybe the main protagonist was actually a girl, but I am not sure.
Edit: I am kinda sure that the anime style of the people was more like Captain Future and Queen Millenia. For years I actually thought it was Queen Millenia until I watched it and never found any of those scenes I remember. One of the kids were kinda chubby I think and I think they didn't start with weapons and somehow get them later.

A: It might be Akira (1988)
Japanese anime, right period, hand drawn.
Here's a scene where three young men ride motorbikes. Another gang drop exploding "marbles", or smallish round bombs. (see at 2m40s).

A: It's possible that this could be: Galaxy Express 999.
After looking up Queen Millenia, I saw what it looked like and Googled 1970s anime list, which brought me to: this website.  The blond person looks like Queen Millenia, it's scifi, there's some kids, and at least one matched your earlier description.


text:
Q: Cannot make 5 consecutive "joins" in LINQ? I have this rather complex query in SQL server 2008:
declare @LanguageID as int = 1

select k.datePublish, k.dateEditing, k.dateTables

from TableAreasLevel1 as areaL1

inner join TableAreasLevel2 as areaL2
on areaL1.LanguageID = areaL2.LanguageID and
areaL1.CodeAreaLevel1 = areaL2.CodeAreaLevel1

inner join TableAreasLink as link
on areaL2.CodeAreaLevel1 = link.CodeAreaLevel1 and
areaL2.CodeAreaLevel2 = link.CodeAreaLevel2 and

inner join TableProducts as tblProds
on tblProds.CodeAreaLevel1 = areaL1.CodeAreaLevel1 and
tblProds.CodeAreaLevel2 = areaL2.CodeAreaLevel2

inner join TableSI_Products as prod
on prod.SiAreaCode = link.SiAreaCode

inner join TableCalendar as k
on k.KodTableSI_Products = tblProds.KodTableSI_Products

where areaL1.LanguageID = @LanguageID and
prod.Code = 'some string' and
k.LanguageID = @LanguageID and
tblProds.LanguageID = @LanguageID;

I am trying to develop the same query in LINQ, but I get error when I try join the table TableProducts, i.e the third consecutive join.
Here is my LINQ query:
List<Tuple<DateTime, DateTime, DateTime>> dates = (from areaL1 in gpe.TableAreasLevel1
    join areaL2 in gpe.TableAreasLevel2
        on new { areaL1.CodeAreaLevel1, areaL1.LanguageID } equals
            new { areaL2.CodeAreaLevel1, areaL2.LanguageID }

    join link in gpe.TableAreasLink
        on new { areaL2.CodeAreaLevel1, areaL2.CodeAreaLevel2, areaL2.RbrOblastNivo2} equals
            new {link.CodeAreaLevel1, link.CodeAreaLevel2}

    join tblProds in gpe.TableProducts
        on tblProds. // The name tblProds is not in the scope of the left side of 'equals'

    );

Is the problem connected with how the tables are designed or, something else I should check for?
Any ideas, why tblProds is not visible in the scope of the LINQ query?

A: You are using Query as your guide something like:
on k.KodTableSI_Products = tblProds.KodTableSI_Products

but take a look at your linq:
on new { areaL1.CodeAreaLevel1, areaL1.LanguageID } equals

it has two fields. I think its not a good idea.
linq join something like
var dates = (from areaL1 in gpe.TableAreasLevel1
    join areaL2 in gpe.TableAreasLevel2
        on areaL1.PKFields  equals areaL2.PKFields
          where areaL1.CodeAreaLevel1== areaL2.CodeAreaLevel1 && areaL1.LanguageID =  areaL2.LanguageID
Select new YournewClass{YournewClass.Field1=areaL1.fields1, And so on}

)

You can do to join the other tables with aliases.
Sorry need to go for now.
I'm giving you an idea.
Hope it helps.


text:
Q: Jasmine-karma error: Can't resolve all parameters for Storage: (?) The app running fine with "@angular/core": "5.0.3" and "@ionic/storage": "2.1.3", while run unit test, getting error on the karma debug page.
At first time got the below error message,
error :
no provider for Storage
next added :
import { IonicStorageModule, Storage } from '@ionic/storage';
to .spec.ts file and added to provider as well then getting different error message called
Can't resolve all parameters for Storage: (?).
How can I solve this issue from spec.ts file / any internal file changes require ?
login.component.spec.ts :
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { LoginPage } from './login';
import { IonicModule, Platform, NavController} from 'ionic-angular/index';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HttpClientModule } from '@angular/common/http';
import { LoginService } from "../../otherts/login.service";
import { GlobalLoginSession } from "../../otherts/GlobalLoginSession";
import { IonicStorageModule, Storage } from '@ionic/storage';

describe('Login Component', () => {
  let de: DebugElement;
  let comp: LoginPage;
  let fixture: ComponentFixture<LoginPage>;
  let a : boolean;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LoginPage],
      imports: [
        HttpClientModule,
        IonicModule.forRoot(LoginPage)
      ],
      providers: [
        NavController,
        LoginService,
        GlobalLoginSession,
        IonicStorageModule,
        Storage
      ]
    });
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginPage);
    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css('h3'));
  });

  it('should create component', () => expect(comp).toBeDefined());

});

login.component.ts :
import { Component } from '@angular/core';
import {Events, IonicPage, NavController, NavParams} from 'ionic-angular';
import { Storage } from '@ionic/storage';

import { LoginService } from "../../otherts/login.service";
import {FormControl, FormGroup, Validators} from "@angular/forms";
//import {TabsControllerPage} from "../tabs-controller/tabs-controller";
import {MyApp} from "../../app/app.component";
import {GlobalLoginSession} from "../../otherts/GlobalLoginSession";

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
    public rawJsonData: any ;

    disableEmail : false;
    myform: FormGroup;

    ngOnInit() {
        this.myform = new FormGroup({
            firstName: new FormControl('',Validators.required),
            lastName: new FormControl('',Validators.required),
            loginAsMobile: new FormControl(),
            email: new FormControl(),
            mobile: new FormControl('',Validators.required),
            password: new FormControl('',Validators.required)
        });
    }

    public submitIt() {
        console.log("Submitting  assuming the form is valid.......");
        let firstName = this.myform./*get('name').*/get('firstName').value;
        let lastName = this.myform./*get('name').*/get('lastName').value;
        let loginId : any;
        let loginTypeMobile = this.myform.get('loginAsMobile').value;
        let password = this.myform.get('password').value;
        if(loginTypeMobile)
        {
            loginId = this.myform.get('mobile').value;
        }else{
            loginId = this.myform.get('email').value;
        }

        this._loginService.doLogin( { loginId:loginId, password: password}).subscribe(data => {
            console.log("formSubmitted:",data);
            this.rawJsonData  = data;
            if ( this.rawJsonData && this.rawJsonData.status == "$200") {

                this.loginSession.isPatient = this.rawJsonData.httpHeaders.isPatient ;
                this.loginSession.subID =        this.rawJsonData.httpHeaders.accountId ;
                this.loginSession.patientId = this.rawJsonData.httpHeaders.memberId ;

                this.loginSession.h5cAuthToken = this.rawJsonData.httpHeaders.h5cAuthToken ;

                this.loginSession.needChangePassword = <boolean> this.rawJsonData.httpHeaders.chngPswd ;
                this.loginSession.needChangeProfile = <boolean> this.rawJsonData.httpHeaders.profUpdate ;

                this.loginSession.message = this.rawJsonData.httpHeaders.message ;
                this.loginSession.loginId = loginId;
                this.loginSession.isMobileLoginId = loginTypeMobile;
                this.loginSession.firstName = firstName;
                this.loginSession.lastName = lastName;
                this.loginSession.message = this.rawJsonData.httpHeaders.message;

                this.loginSession.sessionActive =  true ;

                if( this.loginSession.isPatient) {
                    console.log("You are a patient you are allowed to login into this app");
                }
                else {
                    console.log("You are not a patient still, you are allowed to login into this app, you will ejected out soon");
                }

                console.log("Login Message",this.rawJsonData.httpHeaders.message);

                this.storage.set("authToken", this.rawJsonData.httpHeaders.h5cAuthToken);
                this.storage.set("memberId", this.rawJsonData.httpHeaders.accountId);
                this.storage.set("patientId", this.rawJsonData.httpHeaders.memberId);
                this.storage.set("loginId", loginId);
                this.storage.set("loginTypeMobile",loginTypeMobile);
                this.storage.set("firstName", firstName);
                this.storage.set("lastName", lastName);

                console.log("loginId "+loginId);

                //this.navCtrl.push(TabsControllerPage);
            }else{
                alert(this.rawJsonData.httpHeaders.message);
            }
        },(err) => {
            console.log(err);
        });
    }
    constructor(public _loginService:LoginService, public navCtrl: NavController, private storage: Storage,private events:Events, private loginSession : GlobalLoginSession) {
    }
    add(num){
        return num + 1;
    }
}

A: You need to import the IonicStorageModule, not add it in providers:
  imports: [
    HttpClientModule,
    IonicModule.forRoot(LoginPage),
    IonicStorageModule.forRoot()
  ],

(as explained in docs)
You also don't need anything else in providers, since the IonicStorageModule would likely export the Storage provider you want to use
  providers: [
    NavController,
    LoginService,
    GlobalLoginSession
  ]


text:
Q: Textfield with centered text with Appcelerator Titanium How to make textfields in Titanium with centered text? Is it possible using Android?

A: Have you tried textAlign:'center' property in the constructor/createTextField. I know this isn't in their API docs but it might just work this bug report seems to say that the property should have been added. (at least in the latest RC 1.7.0) it is how ever not in the API docs but this might have simply been an omission.
Give it a try comment if it works or doesn't if it does then maybe you should ping them to update the docs

A: Have you tried paddingLeft as a property?


text:
Q: DB2 ROLLFORWARD option "TO END OF LOGS" - does it read archive logs? I read about ROLLFORWARD option on link http://www-01.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0001978.html?cp=SSEPGG_9.7.0%2F3-6-2-4-106 but I could not find answer to my issue.
I have database in Archive mode.
I am using DISK option in LOGARCHMETH1
I made full ONLINE backup at Monday at 23:59
I have archive logs for Tuesday, Wednesday and Thursday.
Let's say just for example one for each day: S0000001.LOG and S0000002.LOG and S0000003.LOG.
In Friday I have active log S0000004.LOG.
Let's say just for testing purpose I want to do the restore of Online backup made at Monday and all transactions committed during  Tuesday, Wednesday,Thursday and Friday. So I want to restore everything from Monday to Friday
I thought by reading all manuals that I just need to perform after restore ROLLFORWARD TO END OF LOGS
db2 rollforward db maxdb75 to end of logs and complete;

I thought that this command to end of logs it will include Archive Logs(S0000001.LOG + S0000002.LOG + S0000003.LOG.)+Active Logs(S0000004.LOG)
But one good database expert told me that: "When rolling forward to end of logs without specifying overflow log path only active logs will be read"
So I have 2 questions:

*

*What in my example will be restored in case of "to end of logs" command

*Is this the command if after the restore I want to rollforward everything from Monday To Friday in my exampe: db2 rollforward db maxdb75 to end of logs and complete overflow log path "(/data/archiveLogsPath)";
Thank you in advance!!!!

A: Whoever told you "When rolling forward to end of logs without specifying overflow log path only active logs will be read" was wrong.
When you have LOGARCHMETH1 set to DISK, TSM, USEREXIT or VENDOR, the DB2 log manager EDU (db2logmgr) is responsible for moving log files to and from the archive location.  When performing a ROLLFORWARD operation, DB2 will determine which log files it needs, and db2logmgr will retrieve files for processing if they aren't already in the active log path.
Now, if you have LOGARCHMETH1 set to LOGRETAIN, and you are manually moving log files from the active log path to somewhere else, only then will you have to specify OVERFLOW LOG PATH (or move/copy the transaction log files back to the active log path).
So: to end of logs means just what it sounds like:  DB2 will replay all transactions present in log files between the backup time and when the restore took place.

A: Yes, Ian is correct here. I am sure your issue is resolve now. Also, archive logs can still exist in Active log path if we set LOGARCHMETH1 to LOGRETAIN  correctly . Details at Information Center can give better overview .Hope it helps !


text:
Q: Backing Up mysql db from the command line I am trying to backup my database and keep getting error :

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$ mysqldump -u root -p chandlers > backup_db.sql' at line 1

I am using the following command to launch the backup :
$ mysqldump -h localhost -u root -p chandlers > backup_db.sql

edit>>>>
This is how I connect to the db, this is a shortcut I have setup to open a command line :
C:\server2go\server2go\server\mysql\bin\mysql.exe -h localhost -P 7188 -u root

This works fine and connects, I have tried creating another like this >>
 C:\server2go\server2go\server\mysql\bin\mysqldump.exe $ mysqldump -h localhost -P 7188 -u root -pchandlers > backup_db.sql

but I am getting an access denied error now.

A: you can use mysqldump to backup mysql database.
Below is the script example to backup mysql database in command line:-
$ mysqldump -h localhost -u username -p database_name > backup_db.sql

If your mysql database is very big, you might want to compress your sql file.
Just use the mysql backup command below and pipe the output to gzip,
then you will get the output as gzip file.
$ mysqldump -u username -h localhost -p database_name | gzip -9 > backup_db.sql.gz

If you want to extract the .gz file, use the command below:-
$ gunzip backup_db.sql.gz

A: You seem to be calling mysqldump from within mySQL, which is incorrect - it's a separate executable.
Call it from the command line instead.

A: I think it should be $ mysqldump -h localhost -u root -pchandlers > backup_db.sql. Otherwise it seems fine to me.


text:
Q: Interesting algorithm problem I have an interesting algorithm problem here. The problem is in a way related to simulation of electronic designs.
Say for example, I have a structure containing some gates. say a 3-input AND gate.
There are 8 possible inputs i.e
000
001
...
111

Out of these 8 inputs, if I only feed in two inputs (000) and (111), I get both the possible outputs i.e 0 and 1.
So The minimal set of input vectors that produces both the states '0' and '1' on the output are {000, 111}.
The problem is given a design, some arrangement of gates, give an algorithm to find the minimal set of input vectors that produces both the states (i.e 0 and 1) on the final output.

A: This is solved with the Quine McCluskey algorithm. There are also some JavaScripts and Tools which may solve your problem.

A: Your problem is equivalent to solving the boolean satisfiability problem. It is therefore NP-complete.
To get one of the inputs you can choose an arbitrary input and see if that gives either 0 or 1. To find an input that gives the other output you need a SAT solver.
Wikipedia suggests some algorithms that can be used:

*

*DPLL algorithm

*Chaff algorithm

*GRASP

*WalkSAT

*etc...

If you don't want to implement it, there are tools that are ready-to use SAT solvers:

*

*CVC3 (open-source LGPL)

*Yices (free for non-commercial use)


text:
Q: Transaction (Process ID) was deadlocked: Sql Server Management Studio I'm trying to delete a database (from Sql Server Management Studio) and I receive this error:

Transaction (Process ID 52) was deadlocked on lock resources with
  another process and has been chosen as the deadlock victim. Rerun the
  transaction. (.Net SqlClient Data Provider)

I googled a lot (with a lot of result also here in so) but I cannot find any solution.
I really need to delete (and restore this db), but I'm stucked.
Any suggestion?

A: I guess you have open transactions. For example, for the database StackOverflow I am opening a transaction like this:
USE StackOverflow
BEGIN TRAN

and
USE StackOverflow
exec sp_whoisactive

So, when I try to deleted it:

I get the following error:

An exception occurred while executing a Transact-SQL statement or
  batch. (Microsoft.SqlServer.ConnectionInfo)
Cannot drop database "StackOverflow" because it is currently in use.
  (Microsoft SQL Server, Error: 3702)

If I choose close existing connections from the delete interface the database is successfully deleted.


text:
Q: Why does the `--oformat binary' option of the gnu linker place the `.data' segment at 0x0200000 I've been writing some "free standing" code for i386 real mode and came across some weird errors while PXE netbooting my code:
PXE-E79: NBP is too big to fit in free base memory
PXE-M0F: Exiting Intel Boot Agent.

after much fiddling with my binaries I isolated it as having any data or code after the
.data

segment marker.
After hexdumping I found that ld moved the instructions all the way to 0x0200000 of all places.
I'm currently generating my flat bin with:
ld --oformat binary

Questions:

*

*Why does ld do this?

*Is this specific to the oformat option?

A: 1) The linker probably does this because it felt like it (e.g. possibly for alignment with "2 MiB pages" on 80x86), and because you didn't provide a linker script that says to do anything other than "whatever the linker feels like".
2) I'd assume all output formats do "whatever the linker feels like" (unless the linker is told otherwise).
Note: The actual behaviour may be determined by a default linker script hidden somewhere, and may be "whatever the distribution of the OS felt like" rather than merely "whatever the linker felt like".
In any case, if you want the linker to do something specific, you need to tell the linker specifically what you want by writing a linker script. If you actually have written a "less specific than necessary" linker script then you'd need to make that script more specific.

A: 1-ld use the default linker script. Try -v to see your default
2-Is not specific to the oformat
3-To set another size you must to use
-z max-page-size=0x
I tried with 0x100 and 0x1000 and work fine, but 0x500 doesn't.
Salu2 totales


text:
Q: Is there a way to interrupt Eclipse when it is hanging (eg, on content assist) I'm using the Scala plugin, and it sometimes likes to hang and spin a rainbow wheel (Mac wait icon) for a long time. It's very annoying. Is there something like a "Control C" for the current thread? I'd like a way to tell Eclipse to kill the current UI command.  This would help when use plugins that are not as polished as the one for Java.

A: There is no such feature and I would not hold your breath waiting for one. Unlike system processes that exist independent of each other, threads are entangled. Force killing a thread is very likely to corrupt various data structures and leave Eclipse process in a bad state.
Various API techniques exist to allow for cancellation of an operation, but they all rely on the running operation to actively check for cancellation request and safely shutdown. Not much help for dealing with unpolished plugins, since graceful handling of cancellation in all cases tends to be implemented as part of polishing.


text:
Q: How to get fractions in an integer division? How do you divide two integers and get a double or float answer in C?

A: You need to cast one or the other to a float or double.
int x = 1;
int y = 3;

// Before
x / y; // (0!)

// After
((double)x) / y; // (0.33333...)
x / ((double)y); // (0.33333...)

Of course, make sure that you are store the result of the division in a double or float!  It doesn't do you any good if you store the result in another int.

Regarding @Chad's comment ("[tailsPerField setIntValue:tailsPer]"):
Don't pass a double or float to setIntValue when you have setDoubleValue, etc. available.  That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.
For example, on my system, the file:
#include <stdio.h>
int main()
{
    double x = 3.14;
    printf("%d", x);
    return 0;
}

outputs:
1374389535
because the double was attempted to be read as an int.

A: Use type-casting.
For example,
main()
    {
        float a;
        int b = 2, c = 3;
        a = (float) b / (float) c;     // This is type-casting
        printf("%f", a);
    }


text:
Q: How can i download a file faster? I have made a download program in C#. It is a queue downloader.
You can see how it works here: Click Express Downloader
Is there any faster method to download?
Here is the method i use, it must support resume support.
private void Download(object startPoint)
    {
        try
        {
            try
            {
                //int startPointInt = Convert.ToInt32(startPoint);
                Int64 startPointInt = Convert.ToInt64(startPoint);
                webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.AddRange(startPointInt);
                webRequest.Credentials = CredentialCache.DefaultCredentials;
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                Int64 fileSize = webResponse.ContentLength;
                strResponse = webResponse.GetResponseStream();
                if (startPointInt == 0)
                {
                    strLocal = new FileStream(txtPath.Text + "\\" + filename, FileMode.Create, FileAccess.Write, FileShare.None);
                }
                else
                {
                    strLocal = new FileStream(txtPath.Text + "\\" + filename, FileMode.Append, FileAccess.Write, FileShare.None);
                }
                int bytesSize = 0;
                byte[] downBuffer = new byte[4096];
                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    strLocal.Write(downBuffer, 0, bytesSize);
                    this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize + startPointInt });

                    if (goPause == true)
                    {
                        break;
                    }
                }
            }
            catch { }
        }
        finally
        {

            strResponse.Close();
            strLocal.Close();
        }
    }

A: You have to do two things,

*

*Get faster bandwidth

*Change block size from 4096 to something like 8192 or any number which can be hold in memory easily.


text:
Q: WebBrowser control not showing last 2 lines of local HTML file I have a WebBrowser control that's loaded with a local HTML file, like so:
var rs = Application.GetResourceStream(new Uri("View/Help.html", UriKind.Relative));
StreamReader reader = new StreamReader(rs.Stream);
browser.NavigateToString(reader.ReadToEnd());
reader.Close();

It displays fine, except the last two lines are cropped off.  It's like the viewport of the WebBrowser isn't large enough (I can pull up and see the last two lines, but when I let go it bounces back down).  The HTML file is fairly long, maybe 5 screens worth.
The XAML for the page is super simple, the entire page is the WebBrowser control:
<Grid x:Name="LayoutRoot" Background="Transparent">
    <phone:WebBrowser x:Name="browser" Width="480" Height="800" IsScriptEnabled="True"/>
</Grid>

Any ideas?

A: If you've got the ApplicationBar visible then you'll need to reduce the size of your WebBrowser otherwise you'll be displaying content underneath the app bar.


text:
Q: How to break out of a sandboxed iFrame? 1. What is the issue?
The sandbox attribute added for iFrame elements in HTML5 spec renders any frame breaking/busting/killing method null in modern browsers (tested with current version of Chrome & Safari) if the flag allow-top-navigation is not set, even if the flags allow-forms and allow-scripts are present.
2. What I have tried?

*

*Any JavaScript method out there, such as if(top != self)
top.location.replace(location);

*Triggering a submit event on a form
with the target="_top" attribute

*Triggering a click event on an
anchor element with the target="_top" attribute. In fact, anchor elements with the target="_top" attribute are rendered useless. So, a nice message to advice users to take action won't work either (as shown in this Flickr iFrame example).
3. What I want to achieve?
I want a way to break out of frames on modern browsers, which have implemented the sandbox attribute for iFrames with the flags allow-forms and allow-scripts present?
Seems like they have just given the missing pieces of a puzzle to all black hats with this attribute.
4. What I am not looking for?
I am looking for a solution, which will break out of frames. Not for a solution, which won't display the site inside frames (such as X-Frame-Options response header) or using CSS to hide the body and such.

A: I am afraid that you won't find a solution, as the point of the sandbox is that you can't break out of it.
If there was a hack to break out, it would be classified as a security issue by the vendor and patched quickly.


text:
Q: Howto show next row before animain is done I have tried to solve this for days but now i try my luck here.
I use an lazy load to show my images in a custom adaper.
i want to fade in images as they ar download loaded.
This is working BUT the Thread stops while animation is ON
public void run()
    {
        if(bitmap!=null) {
    myProgressBar.setVisibility(View.INVISIBLE);
    imageView.setVisibility(View.VISIBLE);
    Animation animation = new AlphaAnimation(0.0f,1.0f);
    animation.setDuration(800);
    imageView.startAnimation(animation);
    imageView.setImageBitmap(bitmap);
        }else {
            myProgressBar.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.INVISIBLE);
            imageView.setImageResource();
        }

what I want to do is to show next row even if the privius animaion not are finished.
Any ides?

A: This is so because the thread hasn't anything more to execute after the line
imageView.setImageBitmap(bitmap);

is reached.
Although you set a duration of 800 ms, Java doesn't wait on the startAnimation line until this 800 ms are over. If you want to stop your thread after the animation is completed I would recommend to use an AnimationListener to get notified when the animation ends.


text:
Q: How to make optional word in regex I have this sample data
/user/test/30173650
/sample/30079887?pos=0&code=3232323&cc=32232
/sample/30079887?pos=1
/test/codemelbourne/30173650/dsadsad/dasdasdsa/dasdas

I want to get the number item.
I have this code:
\/(\d*)[?]?

Why does this also match /?

A: The reason is that the remaining part of your regex also matches the empty string:

*

*\d* - zero or more digits

*[?]? - an optional questionmark

To fix this, you can use repetition that requires at least one digit to be found:
\/(\d+)[?]?

A: * Means that it will get zero or more digits. +means one or more, so this will remove all empty matches.
Working regex \/(\d+)[?]?
() is the capture group so this will only return the digit needed.

A: You are using * which means, 0 or more digits. Use +:
\/(\d+)\??


text:
Q: Code folding regions in ruby on VIM? I know not everyone like code folding, but as a convert to Rails and a convert to VIM, I want one of the conveniences back that I had in Visual Studio.Net.  I want to be able to place arbitrary #region #endregion tags and have VIM fold them for me like everything else.
I have syntax code folding turned on and normal def..end folding works fine, I just want to augment that with #regions.
I did some googling and thought that I could do this in a ruby.vim in my syntaxes folder, but it didn't work, and I don't know enough to debug whether it was bad code that I copied over or if it just "doesn't work that way."
let b:match_words = '\s*#\s*region.*$:\s*#\s*endregion'

This is my only line in syntax/ruby.vim.  In fact, the file wasn't there before I started, even though ruby highlighting is working fine. (which also throws big red flags for me - I haven't a clue where the ruby/rails syntax, unless its in the rails.vim plugin, but I can't find it there either.
Can someone lend me a thread so that I can follow it and figure this out?
Thanks
UPDATE:
I found some other code snippets and tried this version instead, which almost gets me there:
syn region vimFoldRegion
  \ start="#region"
  \ end="#endregion"
  \ skip=+"\%(\\"\|[^"]\)\{-}\%("\|$\)\|'[^']\{-}'+
  \ transparent fold
  \ keepend extend
  \ containedin=ALLBUT,@vimNoFold

This lets me fold the region, but all of the code inside the region is shown like its a comment.  I've tried different variations of the parameters on the syn, but I'm not grokking it.

A: Vim can fold regions based on markers if you set foldmethod=marker.  The default markers are {{{ and }}}, though I'm pretty sure you could override these to be #region and #endregion.  The problem is you then lose the ability to fold based on syntax.  There's another Stack Overflow question dealing with combining the two fold methods [1], but the conclusion there is that it's not possible to do both simultaneously.
For what it's worth, I find that vim's syntax-based code-folding is horrendously slow for large Ruby files, so you might find yourself wanted to switch to a marker-only fold method if you run into the same problem.
[1] Foldmethod=marker and syntax at the same time?


text:
Q: Authentication by certificate in ssh -- am I doing it properly? I've read various articles about how to setup authentication without password, only by certificate and I haven't a common solution: some suggest this, other that. How to do this properly?
This config works, yes, but maybe there's something I should I remove? Or something I should add anything else?
# /etc/ssh/sshd_config:

ChallengeResponseAuthentication no
UsePAM no
PermitRootLogin no
PasswordAuthentication no
PermitEmptyPasswords no
RSAAuthentication yes
PubkeyAuthentication yes

My question is about this config in particular and I don't need any more links to read.

A: *

*You don't need RSAAuthentication. It is deprecated in current OpenSSH.

*PermitEmptyPasswords is not needed once you disable the password authentication.

*UsePAM should stay on in most of todays systems since it does not do only authentication, but also setting up your session.


text:
Q: Create a Venn Diagram in R to represent rows with the same value from a dataframe I want to create a Venn Diagram in R that represent the interesection between three columns of a dataframe, i.e. that represent how many observations are "1" for each pairwise comparison and also between the three groups.
Here is a reproducible example.
library(ggVennDiagram)
df <- as.data.frame(cbind(A=c(1,0,0,0,0,1,1,1,0,1),
                    B=c(0,0,1,1,0,0,0,1,1,0),
                    C=c(0,0,1,1,1,1,0,1,0,0)))

The resulting toy dataframe:
df
   A B C
1  1 0 0
2  0 0 0
3  0 1 1
4  0 1 1
5  0 0 1
6  1 0 1
7  1 0 0
8  1 1 1
9  0 1 0
10 1 0 0

So, I want to produce a Venn Diagram of the intesection of A, B and C, i.e. representing how many rows have "1" in common between A and B, B and C, A and C, and A B and C at the same time.
However, if I run ggVennDiagram(df) it does produce this plot:

Which is obviously not the output that I am expecting.
Anyone knows how can I solve?

A: You need a named list of integer vectors, which is equivalent to which(x == 1) for each column in your data frame, so you can do:
ggVennDiagram(lapply(df, function(x) which(x == 1)))


text:
Q: Defining Writes for case class that contains property whose type is a Map . Json / Scala / PlayFramework I have a case class defined this way:
scala> import play.api.libs.json._
  import play.api.libs.json._
scala> import play.api.libs.functional.syntax._
  import play.api.libs.functional.syntax._

scala> type MapIntString = Map[Int, String]
  defined type alias MapIntString

case class Duh(a: MapIntString)
  defined class Duh

When I tried declaring its Writes this way, I got an error:
scala> implicit val duhWrites = Json.writes[Duh]
  <console>:25: error: No implicit Writes for MapIntString available.
  implicit val duhWrites = Json.writes[Duh]

So I resort to this..., still got an error:
scala> implicit val duhWrites: Writes[Duh] = (
     |   (JsPath \ "a").write[MapIntString]
     | )(unlift(Duh.unapply _))
  <console>:26: error: overloaded method value write with alternatives:
  (t: MapIntString)(implicit w: play.api.libs.json.Writes[MapIntString])play.api.libs.json.OWrites[play.api.libs.json.JsValue] <and>
  (implicit w: play.api.libs.json.Writes[MapIntString])play.api.libs.json.OWrites[MapIntString]
  cannot be applied to (Duh => MapIntString)
  (JsPath \ "a").write[MapIntString]

Can somebody help me pointing out where I did wrong?
I feel that my understanding of this reads/writes combinators a bit shaky. I posted related question here (when I was trying to understand what was going on): What is this "and" in ScalaJsonCombinator (when defining a Writes)?
If you know the best way to implement the Writes and Reads for "Duh" please share.
Thanks in advance!

A: There are no predefined Writes for Map[Int, String], only Map[String, A]. This is because all JSON keys must be a String, to Int keys don't really make any sense. You can fix this by defining one that converts the Int keys to Strings.
type MapIntString = Map[Int, String]

implicit val mapIntWrites = new Writes[MapIntString] {
    def writes(m: MapIntString): JsValue =
        Json.toJson(m.map { case (k, v) => (k.toString, v)} )
}

scala> implicit val duhWrites = Json.writes[Duh]
duhWrites: play.api.libs.json.OWrites[Duh] = play.api.libs.json.OWrites$$anon$2@50973f47


text:
Q: How do I prove $p(x) = x^2$? Suppose $p(z)=z^2+az+b$ for some $a,b$ complex numbers, and $|p(z)|=1$ whenever $|z| = 1$.
Prove that $a=b=0$.

A: (For a general result see Characterizing nonconstant entire functions with modulus 1 on the unit circle which proves that the only entire functions that satisfy $|f(z)|=1$ on the unit circle $|z|=1$ are polynomials of the form $f(z)=a z^n$ with $|a|=1$. The following is an elementary proof, not using complex analysis, for $2^{nd}$ degree polynomials such as the one in the posted question.)
$$|z|=1 \iff |z|^2 = z \bar z = 1 \iff \bar z = \frac{1}{z}$$
$$|p(z)|=1 \iff |p(z)|^2=1=p(z) \overline{p(z)}=p(z) p(\bar z)=p(z) p(\frac{1}{z})$$
Substituting $p(\frac{1}{z}) = \frac{1}{z^2}(1 + a z + b z^2)$ gives:
$$ (z^2 + az + b)(1 + a z + b z^2) = z^2$$
$$q(z) = b z^4 + a(b+1)z^3 + (a^2+b^2)z^2+a(b+1)z + b = 0$$
But the latter shows that the polynomial $q(x)$ has all points on the unit circle $|z|$ as roots, thus it has infinitely many roots, which can only happen if $q \equiv 0$. Equating coefficients to $0$ gives $a=b=0$.


text:
Q: Need help identifying an integer sorting algorithm What sorting algorithm is this? I thought of this method last night and quickly drew up some code, and to my surprise worked perfectly. I've been looking through the Wikipedia article on sorting algorithms and have searched Stack Overflow but have been unable to find this or similar algorithm.
This is the algorithm's written process:
[3, 1, 0, 4]
 ^        ^  Check outermost items, swap if necessary
----------------
[3, 1, 0, 4]
 ^     ^     Check first pair of second farthest apart items, swap if necessary
[0, 1, 3, 4]
----------------
[0, 1, 3, 4]
    ^     ^  Check second pair of second farthest apart items, swap if necessary
----------------
[0, 1, 3, 4]
 ^  ^        Check first pair of third farthest apart items, swap if necessary
----------------
[0, 1, 3, 4]
    ^  ^     Check second pair of third farthest apart items, swap if necessary
----------------
[0, 1, 3, 4]
       ^  ^  Check third pair of third farthest apart items, swap if necessary
----------------
[0, 1, 3, 4]
             Cannot compare closer items (adjacent), done.

This is the algorithm in JavaScript:
var unsorted = [4, 9, 10, 2, 9, 4, 0];
var sorted = ianSort(unsorted);

function ianSort(array) {
    for(var j = array.length; j > 1; j--) {
        for(var i = 0; i < array.length - j + 1; i++) {
            if(array[i] > array[i + j - 1]) {
                var temp = array[i];
                array[i] = array[i + j - 1];
                array[i + j - 1] = temp;
            }
        }
    }
    return array;
}

(I've called the function IanSort here in the unlikely event that I'm the first person to think this up. ^_^)

A: I believe that what you've devised is related to comb sort, which is a generalization of bubble sort that initially starts with a large step size and then decays the step size over time.  Traditionally, comb sort works by starting with a large size and then decaying the interval size by a constant factor on each iteration.  Your algorithm essentially does this by choosing a constant such that the step size shrinks by one on each iteration.

A: Looks like a Comb sort

A: I'm not quite sure, but it looks like the bubble sort algorithim to me.

A: This appears to be a form of the Comb Sort algorithm.  I also thought I was the first to discover it several years ago and made up several variations to test against the quick sort and other sorting algorithms.  You can read about my research here.
It's a fast algorithm that can compete with the quick sort, even beating it under some conditions.


text:
Q: ActionbarSherlock want to insert an image inbetween icon and Tabs I have a tablet layout using ABS.
The Home (app) icon is displayed and my 4 tabs are shown to the right of it.
I'd like to insert an image (for advertising) inbetween the icon and tabs.
Does anybody know if it can be done?
Thanks in advance.

A: You can't insert an image between the icon and the tabs, but you could:
A. Use a logo drawable which has the icon and ad in it -- then add this by setting the android:logo attribute on your application or activity to your logo drawable.
or
B. Use a custom view and set this on the ActionBar with setCustomView(View view).


text:
Q: what is the point of twilio's StatusCallback parameter? The API states that status_callback is: "A URL that Twilio will request when the call ends to notify your app."
Okay, so....does this url execute TwiML or no?
I'm really confused.
require 'twilio-ruby'

account_sid = '##'
auth_token = '##'

@client = Twilio::REST::Client.new account_sid, auth_token

@client.account.calls.create({
    :from => '+18005550199',
    :to => '+10000000000',
    :url => 'http://thisurl.com/blahblah/outbound.xml',   #plays a message to :to
    :status_callback => "http://i don't know what to do here or if this url is supposed to execute TwiML"
})

A: A request to make a phone call may take a "long" time (in terms of web requests that means "several seconds"). Therefore the API cannot answer with a single return code, but it will update your status after some "some time" using a post-back URL. Try providing a URL to your own app and see what comes back.
Trouble is in order to do this you will most probably need a deployed app as you need a publicly available URL to do so (and localhost will not do :-). So you will have to setup a test domain, but most probably you will be able to use a subdomain, something like beta.mydomain.comin order to figure out what you will get.
Most of the examples they show on their website seem to be in PHP, but the callbacks they provide after making a call seem to expect to be called after "some time" if a connection could be established.
The API-Link you provided states rather clearly

After a call ends, Twilio will make an asynchronous HTTP request to
  the StatusCallback URL if you provided one in your POST. This will
  happen regardless of the call status.

so that is what you should expect, an asynchronous HTTP request to the callback-link you provide. This is made asynchronously as Twillio can not maintain an http-connection for the (indefinite) duration of your call. So you should provide it with an URL such as
http://beta.mydomain.com/call-me-back-here

and wire it to an appropriate route (most probably a POST-request).


text:
Q: Got stuck how to insert previous date and time how to insert previous day date,and time. (i am using Date datatype)
Time is - 00:00:00

A: Subtract 1 from date value; doing so, you'd subtract 1 day.
Setting format (so that you'd know what is what):
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select sysdate right_now,
  2         sysdate - 1 yesterday,
  3         trunc(sysdate - 1) yesterday_midnight
  4  from dual;

RIGHT_NOW           YESTERDAY           YESTERDAY_MIDNIGHT
------------------- ------------------- -------------------
14.03.2022 11:16:14 13.03.2022 11:16:14 13.03.2022 00:00:00

SQL>


text:
Q: regex search and replace with modified result I have a string with tagged elements inside. I want to remove the tags and add some characters to the content inside the tags.
s = 'Hello there <something>, this is more text <tagged content>'
result = 'Hello there somethingADDED, this is more text tagged contentADDED

So far, I've tried
import re
result = re.search('\<(.*)\>', s)
result = result.group(1)

and s =  s.split('>') and regex each substring one by one, but it doesn't seem like the correct or efficient way of doing this.

A: Use back-reference \1.
x="Hello there <something>, this is more text <tagged content>"
print re.sub(r"<([^>]*)>",r"\1added",x)

Output :Hello there somethingadded, this is more text tagged contentadded


text:
Q: Would you delete these questions? Isn't closing enough? This question is mainly motivated by the following case, which I have just noticed on Stack Overflow:

*

*Learning Python in one weekend (Snapshot)

*Learning JavaScript in one weekend
The Python question was posted on April 21, but got closed and ultimately deleted on May 1. Unfortunately there were some pretty good answers in there, especially the top-voted one by ghostdog74, which I am sure took plenty of time and effort to write and revise.
The JavaScript question was posted 12 hours after the Python one, and received roughly the same amount of answers, of similar quality, especially the accepted answer by CMS. However, in this case nobody bothered to cast a single close vote, but more importantly, the JavaScript question is still there for public reference, unlike the Python version which got deleted.
I understand that both question are subjective, and probably should have been a community wiki, but I find it difficult to consider them argumentative or off topic.
So my question is, should we vote to close the JavaScript question so that we delete it, or should we vote to reopen the Python version?

A: There's a subtle but important difference between the two questions, that being that the JavaScript question specifically asks for online resources, whereas the python question seems to merely ask "how do I learn python?"
It may seem like splitting hairs, but it's all in the wording.  If I ask a question, "how do I build an e-commerce site", it would rightly get closed as nonsense.  But if the question is "what are some good resources on building e-commerce web sites", that's not so bad (as long as it's CW).
The former seems like it's asking us to do the work, to write up a long tutorial or a bunch of bullet-point "best practices" for them to follow.  The latter respects other people's time and assumes that answers will consist of mostly outbound links, not private tutoring sessions.
I think that the python question would be okay, if it were reworded and converted to CW.  The JavaScript question should also be CW.  With the appropriate phrasing, neither are truly subjective.
I'll vote to undelete the first one if and only if I see it converted to wiki mode and if somebody more familiar than I with the subject matter can edit it to sound less subjective.

A: I can't imagine that those questions are the first ones to ask how to best learn python/javascript.
So if these questions are duplicates they should be closed. If there are any especially useful answers these should be merged into the original questions and the rest should be deleted.

A: UPDATE: This thread was posted just a few hours before deletion votes became rate limited. The concerns highlighted in this answer will hopefully be mitigated by this feature. Nonetheless, I appreciate that about 200 of the most popular deleted threads are being audited in The Great Question Deletion Audit of 2010, which is what I intended to incite with this answer. Thank you Jeff, for listening and responding promptly.

I say that the Python question should be undeleted (at least).
I have to admit that I do not frequent the 10k moderation tools very much, and I appreciate the guys that keep the trilogy sites clean by monitoring this often. However, just from today's "Recently Deleted" questions, I cannot help but wonder whether questions such as the following had to be deleted:

*

*Is the 'var' keyword bad? Or am I just old school?

*Why do some languages not use semicolons and braces?

*Why does the .NET framework not include USB tools?

*What best describes clean code?

*How measure complexity of program

*Do vs. Run vs. Execute vs. Perform verbs

*Premature optimization is the root of all evil, but can it ever be too late?

*Is it compulsory to learn about Data Structures if you want to be a Java/C++ programmer?

*Given 3 pts, how do I calculate the normal vector?

*What is the difference between scripting language and a programming language?

*What is JUnit in Java?
On this, there seems to be an "official policy" on the SO blog that defines the properties of questions that should be deleted. Quoting:

Why would you delete a question? Isn't closing it enough?

*

*Some questions are of such poor quality that they cannot be salvaged. They're literally nonsense. Not every byte of data that is created in the world is infinite and sacred.

*Some questions are so incredibly off topic that they add no value to a programming community.

*The mental cost of processing these closed questions is not zero, particularly for users who are actively engaged and scanning questions to find things they can help answer.

*If users see a lot of closed questions, they'll note that we don't enforce the guidelines, so why should they? Without any final resolution, asking questions that get closed becomes something we are implicitly encouraging — a broken windows problem. If this goes on for long enough, we're no longer a community of programmers who ask and answer programming questions, we're a community of random people discussing.. whatever. That's toxic.

*If enough of these closed questions are allowed to hang around, they become clutter that reduces the overall signal to noise ratio — which further reduces confidence in the system.

(I added the bold and bullet numbering myself)

It is probably points 3, 4 and 5 that are a bit of a grey area, where the community may disagree what constitutes clutter, mental cost, or a broken windows problem. On the other hand, I guess classifying questions as "literally nonsense" and "incredibly off topic" should be quite straightforward.
I think that one of the problems is that deleted questions do not get enough visibility for others to counter-react with undelete votes. The reasons for this were recently described by mmyers a few days ago.
In fact, I would propose that while the deletion process remains as is, we could submit a post on Meta whenever we encounter a deleted question that got deleted and with which we disagree. The post should contain the arguments in favor of its resurrection, and the community would get some visibility and enough information to make an informed decision on whether to cast an undelete vote or leave it as it is. Maybe this post by Jeff Atwood and this one by Greg Hewgill could be taken as examples.
In the log run, I think this could also serve to refine the policies of what should be deleted in the first place.

A: This question seems to be particularly in the water at the moment. Most of the recent discussion has been about duplicates, not 'subjective' or 'off topic.' For duplicates, recent discussion has centered around 'flag the question so that a diamond can merge it.' Several of us with janitorial tendencies have been switching from 'click delete' to 'flag for moderator attention' for dups with interesting answers.
There still seem to be some quirks even in this process in terms of arranging things so that the maximum value is preserved. A recent suggestion is that the sites need a new condition for a question that would preserve the question and title but send the reader to some other question to read or write answers.
On the non-duplicate front, there is a side-effect of deletion that we can't entirely sweep under the rug: the rep game. I believe that it's relevant to some of the items you list above, as follows:

*

*Someone opens a subjective or humorous or troll question without ticking off Community Wiki.

*Like flies to carrion, a swarm of upvotes arrives.

*The question is closed, often after multiple iterations of close/reopen.

*Deletion wipes out all the dubious rep. Leaving it closed does not.

I know that I have a visceral reaction when I see 'how do you pronounce C++' with 20 upvotes and no community wiki, and I suspect that I'm not alone. (No, I haven't seen that, but I've seen plenty of other 'how do you pronounce' noise.)

A: I have just cast the final (for now) vote to reopen the original python question. By no means should it have been either closed or deleted.
Keep in mind, however, that the moderation process is a "democratic" one. There are currently two very diametrically opposed opinions on the subject of moderation. Most agree that stupid questions or obviously duplicated or spammy questions should be removed. But it's that subjective/argumentative thing that is a huge bone of contention. It's quite possible the question will be re-closed or even re-deleted.
Alas that I can only cast one vote on the subject.

A: I recommend "Never delete any question with an accepted answer."


text:
Q: Describing every ZF2 route - is it really required? I'm trying to switch to ZF2 from ZF1. From what I've read about the new Zend\MVC\Router and the way it is configured, it looks like every single location should be described in ['router']['routes'] config key.
Is that really so? In ZF1 you could build a complex app with multiple locations and not have a single route described. I find it hard to believe, hopefully I am missing something.
Thanks!

A: The routing works in a similar way to ZF1. The config in the skeleton app includes a few example routes, one of which is a /:controller/:action route (line 42). So this is your out-of-the-box ZF1 style MVC route.
In ZF1, the framework adds a /:controller/:action and /:module/:controller/:action route for you (which you had to remove if you had some custom requirements). In ZF2 you have to define the routes yourself, but if you want the same setup as ZF1, the skeleton app setup works in the same way, just without the module prefix.


text:
Q: Will water kept in a beaker get compressed in a lift accelerating upwards?
I came across this question while studying fluid mechanics and the answer to the question is that P, Q and R all match to 1 i.e. range does not depend upon gravity, but rather height of water and beaker. But even if that is true, wouldn't the acceleration cause a deformation and reduce the volume, thus reducing the height of the water?

A: Let's take scenario 1 - the lift is accelerating vertically upwards with acceleration $a$.
The pressure at the hole in the jar will increase by a factor of
$\displaystyle \frac {g+a} g$
If the liquid obeys Torricelli's Law then the horizontal velocity of the water jet will increase by a factor
$\displaystyle \sqrt \frac {g+a} g$
which at first leads us to think that $d$ will increase by the same factor.
However, the floor of the lift is accelerating upwards too, which decreases the time that each droplet of water is in flight by a factor
$\displaystyle \sqrt \frac g {g+a}$
This effect cancels out the effect of the increased horizontal velocity of the water jet, and the final outcome is that $d$ is unchanged by the acceleration of the lift.
The water in the jar will be compressed very slightly by the acceleration, but the compressibility of water is very, very small (approximately the same order of magnitude as solid rock) so the change in the height of the water will be negligible.


text:
Q: What is the correct way to have an editable "Name"-text area in Flutter App? I'm quite a newbie with Flutter and coding in general:
My problem is:
I'd like to have a name of device in a Row, which should be able to be changed/rewritten after a long press.
The Long Press - functionality is preferrable. I Thought about just having a Container with TextField, but I don't know how to implement long press to it.
Another way I was thinking was a TextButton, but how to be able to rewrite the text/name in it..?
So, does anybody have experience and advice in this?

A: wrap your textField with InkWell, like this
 InkWell(
              onLongPress: (){
                //do something
              },
              child: TextField(

              ),
            ),


text:
Q: How to create a json in for loop in laravel I have a array of 3 images
$images
          for ($i=0;$i<count($image); $i++) {
                   array_push($imgArray, $image[i]);
                    $valString = implode(',', $imgArray);
                    $setting = $valString;
                       print_r(settings);
          }

o/p:   img1.jpg,img2.jpg,img3.jpg
But I wnat the o/p as
{'ad1':img1.jpg,'ad2':img2.jpg,'ad3':img3.jpg}

i.e like a json.
Can anyoe please suggest help.Thanks.

A: if your array is ['img1.jpg','img2.jpg','img3.jpg'] then you should use below code
<?php
    $images = ['img1.jpg','img2.jpg','img3.jpg'];
    foreach($images as $key=>$image){
      $images['ad'.($key+1)] = $images[$key];
      unset($images[$key]);
    }
    print_r(json_encode($images));
?>

live demo : https://eval.in/823702

A: $arr = [];
for ($i=0;$i<count($image); $i++) {
    $arr['ad'.$i+1] = $image[$i];
}
$settings = json_encode($arr);
print $settings;


text:
Q: Garbage collection eats status item I turned on garbage collection (objective-c 2.0) and the image for the status item disappeared when I restarted my application.  I am manually memory managing the image and status item.
This application works normal when garbage collection is off (i.e. the status item doesn't disappear.)  Is there a way to make the garbage collection not collect specific variables or should I turn it off completely? When turning on garbage collection, my app's memory drops from 100mb to 2mb.

A: How are you "manually managing the memory of the image and status item"?  If you are using release and retain, they are actually ignored under GC.
Under GC, objects stick around if (a) you have a strong reference to them in GC scanned memory or you (b) CFRetain them.

A: Just keep a reference to it as an instance variable of some object e.g. the controller of the view it appears in.


text:
Q: Trying to recover/import/transfer database from MySQL data dir I used phpMyAdmin->export to create a backup of my database but I have now discovered it did not export the whole database, some tables was missed/refused.
However at the time of doing the export I also saved the whole data directory located at mysql/data/ which has many .ibd and .frm filetypes, which seem to reflect the tables I used to have.
I have tried to copy the entire data directory and paste it into my new setup, but I am not sure if the versions of MySQL / phpMyAdmin are the same, how can I find the MySQL version from my old data directory? Possibly in one of those .frm / .ibd files?
When I do paste the entire data folder, some of the tables in the database are working like normal but some display the following error.
#1033 - Incorrect information in file: '.\db\a_table.frm'

Also it seems every table which shows this same error message is marked in use under Collation in the Structure view in phpMyAdmin
What can I do to fix this? What does it mean?
I am wondering if I re-create my old OS setup, it could work?
Is there a better way?

A: I managed to find a workaround for this but I am not very happy about it.
I installed my previuos setup which was EasyPHP and copied my old MySQL *data* dir into the EasyPHP *MySQL* data directory.
This time around the database was able to read the .ibd / .frm files correctly.(even though these files did not change at all)
I then used phpMyAdmin to export the database(this time around all tables/data was stored in the sql file)
I then disabled EasyPHP enviroment and started up my new enviroment and used phpMyAdmin->import with the new sql file which loaded the data correctly.
Overall I think its pretty poor that MySQL cant simply output some type of notice stating that the .ini enviroment variables are not set corresponding to the .ibd / .frm files rather than just output incorrect information and leave the user in the dark with all sorts of angles to think about. After googling around it seems many people seem to believe that their data is corrupt when that's really not the case.

A:
How can I find the MySQL version from my old data directory?

$mysql> select version();

Before taking the backup, you should know few things:
1. Default storage engine: select * from information_schema.engines where support='Default';
If it is InnoDB. You should run
show global variables like 'innodb_file_per_table'; and check the value. If it is Off - there is a single file for data and index.
So, You can't copy by database by just copying the directory. Also, copying database by copying the directory is not recommended way.
There are two ways to export the backup.
1st way: The way through which you are taking the backup - using phpmyadmin or other GUI tools. Its easy if your Database size is less.
2nd way: Use commands to export and import the data. These commands (mysqldump for export and source for import) are inbuilt in MySQL. This post would be very useful for using commands either on terminal (Linux) or command prompt (windows). You would have a lot of flexibilities also when use these commands.
Before importing, please check the storage engines on the destination server. Use the first query I have written in this answer.


text:
Q: PowerPoint/MS Access VBA assistance I am trying to automate a report writing process by linking an MS Access database to PowerPoint. I do not know how to make the code output the query into a textbox. The code is running fine until the line with "******". Does anyone know how to make the label1.value equal to the query output? Thanks!
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset1 As ADODB.Recordset

'Database path info
 Dim FD As FileDialog
 Dim vrtSelectedItem As Variant
 Dim fileName As String

 Set FD = Application.FileDialog(msoFileDialogFilePicker)

With FD
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
MsgBox "The path is: " & vrtSelectedItem

 'Open the connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & vrtSelectedItem & ";"
Connection.Open ConnectionString:=Connect

'Set RecordSet
Set Recordset1 = New ADODB.Recordset

With Recordset1
    Source = "SELECT [xxx] FROM [yyy] WHERE [zzz] = '12345'"
.Open Source:=Source, ActiveConnection:=Connection
********
***Label1.Value = Recordset1***
********
End With

Next vrtSelectedItem

End If
End With
End Sub

A: Do
    Label1.Value = Label1.Value & vbCrLf & Recordset1.Fields("[YOUR FIELD]").Value
    Recordset1.MoveNext
Loop Until Recordset1.EOF

This code will display all records ([YOUR FIELD] Field) in your query.

But you need to add Recordset1.RecordCount to avoid the error.

If Recordset1.RecordCount > 0 Then
    Do
        Label1.Value = Label1.Value & vbCrLf & Recordset1.Fields("[YOUR FIELD]").Value
        Recordset1.MoveNext
    Loop Until Recordset1.EOF
End If


text:
Q: RDP to Windows XP guest on kvm constantly reconnecting after logon ISSUE
I have, after some days of "hard" work, managed to correctly configure kvm on a Centos 5.5 host.  I have 2 VM running successfully.  Since I only have one public IP address (for the kvm host) I am trying to setup port forwarding (using IP tables).  And everything seems to work fine.  When I rdp to 'hostname.com:3389' I successfully get the login screen for my Windows XP VM.
The problem starts after logging in...  As soon as I provided my credentials in the Windows XP VM the rdp session disconnect/reconnects...  It all happens so fast that I cannot really do anything (in a matter of seconds I am disconnected and reconnected again).
TROUBLESHOOTING
So what have I already tried/checked?
1. I tested the port forwarding the other VM (a Centos system) and I can successfully connect using ssh (and no disconnects).
2. I checked that after I created the iptables rules I could still access the host and the Internet from my Windows XP VM.
LOGS/OUTPUT
PREROUTING rule:
DNAT       tcp  --  0.0.0.0/0            12.12.12.12       tcp dpt:21 to:192.168.122.1:3389

FORWARD rule:
ACCEPT     all  --  anywhere             192.168.122.0/24    state NEW,RELATED,ESTABLISHED

To me this all should work...  Unfortunately it does not!  Hope somebody can help me!

A: are you able to connect to the XP VM from behind the NAT? I mean another VM


text:
Q: Android fragment addToBackStack not working with Navigation drawer I had Created a Home activity which includes a Navigation Drawer onclick with fragment. I had included  fragmentTransaction.addToBackStack(null).commit(); with the fragment transaction code. But it doesn't go back to previous page,instead it is closing the app.
In My MainActivity
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.mainlayout);

  if (id == R.id.nav_project) {
        ProjectFragment fragment = new ProjectFragment();
        mainLayout.removeAllViews();
        fragmentTransaction.replace(R.id.mainlayout, fragment);
        fragmentTransaction.addToBackStack(null).commit();

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
 @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

My Default Fragment
public class ProjectFragment extends Fragment {

       @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View v =  inflater.inflate(R.layout.fragment_project, container, false);

            return v;
        }

}

Can anyone help me to figure out this problem.

A: Thanks for your response, it helps. Basically you need to add a fragment to the stack.
Instead of using replace(), use the add method of fragmentTransaction. This will give you the desired effect.
Easy sample: fragmentTransaction.add(R.id.mainlayout, fragment);


text:
Q: Microsoft SQL: How to select two queries reult in one I want to select HighRisk, MediumRisk and so on low risk etc in one row result, The issue is MicrosoftSQL server format i am not aware of
Select HighRisk , MediumRisk from
(
Select  count(Distinct(PatientKey)) as HighRisk from dbo.vw_FactReferral a
where   (a.PrescriptionDueDateKey <= Cast(FORMAT(getdate(), 'yyyyMMdd') as int)
         AND a.OrderConfirmationDueDateKey <= Cast(FORMAT(getdate(), 'yyyyMMdd') as int)
 AND a.NextDeliveryDueDateKey <= Cast(FORMAT(getdate(), 'yyyyMMdd') as int)) as HR
,
 Select  count(Distinct(PatientKey)) as MediumRisk from dbo.vw_FactReferral a
where   (a.PrescriptionDueDateKey <= Cast(FORMAT(getdate(), 'yyyyMMdd') as int)
         AND a.OrderConfirmationDueDateKey <= Cast(FORMAT(getdate(), 'yyyyMMdd') as int)
 AND a.NextDeliveryDueDateKey <= Cast(FORMAT(getdate(), 'yyyyMMdd') as int)) as HM
 )a


text:
Q: I can't seem to run playn-showcase-android in eclipse I'm currently trying to set up playn on eclipse to make a game on android I followed the installation steps here: http://0-code.google.com.precise.petronas.com.my/p/playn/wiki/GettingStarted
I installed the Android development stuff and the Maven natives plugin and I even did all the android specific steps including adding a Maven installation that is compatible with the Android Maven plugin (in my case it was Maven 3.0.4).
I imported the sample files and tried to run the playn showcase for android and this is what I got:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building PlayN Showcase Android 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
    Downloading: http://snapshots.repository.codehaus.org/org/apache/maven/plugins/maven-install-plugin/maven-metadata.xml
Downloading: http://snapshots.repository.codehaus.org/org/apache/maven/plugins/maven-resources-plugin/maven-metadata.xml
Downloading: http://snapshots.repository.codehaus.org/org/apache/maven/plugins/maven-surefire-plugin/maven-metadata.xml
Downloading: http://snapshots.repository.codehaus.org/org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml
Downloading: http://snapshots.repository.codehaus.org/org/apache/maven/plugins/maven-deploy-plugin/maven-metadata.xml
Downloading: http://forplay.googlecode.com/svn/mavenrepo/com/googlecode/playn/playn-showcase-core/1.0-SNAPSHOT/maven-metadata.xml
Downloading: https://oss.sonatype.org/content/repositories/snapshots/com/googlecode/playn/playn-showcase-core/1.0-SNAPSHOT/maven-metadata.xml
Downloading: http://forplay.googlecode.com/svn/mavenrepo/com/googlecode/playn/playn-showcase-core/1.0-SNAPSHOT/playn-showcase-core-1.0-SNAPSHOT.pom
Downloading: https://oss.sonatype.org/content/repositories/snapshots/com/googlecode/playn/playn-showcase-core/1.0-SNAPSHOT/playn-showcase-core-1.0-SNAPSHOT.pom
[WARNING] The POM for com.googlecode.playn:playn-showcase-core:jar:1.0-SNAPSHOT is missing, no dependency information available
Downloading: http://forplay.googlecode.com/svn/mavenrepo/com/googlecode/playn/playn-showcase-core/1.0-SNAPSHOT/playn-showcase-core-1.0-SNAPSHOT.jar
Downloading: https://oss.sonatype.org/content/repositories/snapshots/com/googlecode/playn/playn-showcase-core/1.0-SNAPSHOT/playn-showcase-core-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.687s
[INFO] Finished at: Tue Jun 12 00:05:36 PDT 2012
[INFO] Final Memory: 10M/109M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project playn-showcase-android: Could not resolve dependencies for project com.googlecode.playn:playn-showcase-android:apk:1.0-SNAPSHOT: Could not find artifact com.googlecode.playn:playn-showcase-core:jar:1.0-SNAPSHOT in forplay-legacy (http://forplay.googlecode.com/svn/mavenrepo) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

So apparently I'm missing a POM for com.googlecode.playn:playn-showcase-core:jar:1.0-SNAPSHOT. How do I resolve this issue?

A: Try running the Maven command from the top directory of your project instead of some sub-directory.
Read this somewhere. Maven seems to be stupid. For me it made it work.

A: Ok. After writing the last comment on your question I figured out the solution:

*

*Right click on playn-showcase: Run As -> Maven Build...

*On the Edit Configuration window set:

*

*Goals: Integration Test

*Profiles: android

I was having a problem to build html but the error I got was the same, so in my case the solution was setting html under Profiles.


text:
Q: Is the matrix of Lagrange multipliers associated to a symmetric matrix itself symmetric? Given the optimisation problem
\begin{equation}
\min_{V} f(V) \quad \text{s.t.} \quad C(V) = 0
\end{equation}
where $V \in \mathbb{R}^{p \times k}$ and $C(V) \in \mathbb{R}^{k \times k}$. The Lagrangian is
\begin{equation}
L(V,\Lambda) = f(V) - \langle C(V) , \Lambda \rangle
\end{equation}
where $\Lambda \in \mathbb{R}^{k \times k}$ is the associated matrix of Lagrange multipliers.
If $C(V)$ is symmetric, does this imply that $\Lambda$ is also symmetric ?

A: The constraint $C(V)=0$ is really just a set of $n^{2}$ constraints
$C_{i,j}(V)=0$, $i=1, 2, \ldots, k$, $j=1, 2, \ldots, k$,
with lots of redundancy, since $C_{i,j}(V)=C_{j,i}(V)$.
The trace inner product of $\Lambda$ and $C(V)$ in the Lagrangian can be written as
$\langle C(V),\Lambda \rangle=\mbox{tr}(C(V)^{T}\Lambda)=\sum_{i=1}^{k} \sum_{j=1}^{k} \Lambda_{i,j}C_{i,j}(V)$
Since $C_{i,j}=C_{j,i}$, this simplifies to
$\langle C(V), \Lambda \rangle=\sum_{i=1}^{k} \Lambda_{i,i}C_{i,i}(V)+\sum_{i=1}^{k} \sum_{j=i+1}^{k} (\Lambda_{i,j}+\Lambda_{j,i}) C_{i,j}(V)$
The actual Lagrange multiplier for the $i,j$th constraint is now $\Lambda_{i,j}+\Lambda_{j,i}$ whenever $i \neq j$ and $\Lambda_{i,j}$ when $i=j$.
It should be clear that you can require $\Lambda$ to be symmetric if you want to, but that you could also let $\Lambda$ be nonsymmetric.  In the first case, $\Lambda_{i,j}=\Lambda_{j,i}$.  In the second case, you've introduced some non-uniqueness in that any pair of $\Lambda_{i,j}$ and $\Lambda_{j,i}$ with the same sum are equivalent.


text:
Q: Why does my python script break after compiling? I'm checking out how much of a performance increase I get after compiling a python script. After research looking into this issue I don't think I will actually see an increase in performance with the script I have written because I found out that once the script is loaded, the execution time doesn't increase. I still would like to know why this is failing to run after compiling as this is my first time trying this. Here is my script
#!/bin/python3
from datetime import datetime
start = datetime.now()

import psutil

BYTES_PER_GB = 1024*1024*1024

# Memory
m = psutil.virtual_memory()
#total = m.total/BYTES_PER_GB
#available = m.available/BYTES_PER_GB
#used = m.used/BYTES_PER_GB
m_free= m.free/BYTES_PER_GB
m_percent = m.percent

# Swap
s = psutil.swap_memory()
s_free = s.free/BYTES_PER_GB
s_percent = s.percent

print(' %.1fG (%.1f%%)  %.1fG (%.1f%%)' % (m_free, m_percent, s_free, s_percent))
print(' %.1fG (%.1f%%)  %.1fG (%.1f%%)' % (m_free, m_percent, s_free, s_percent))

print(datetime.now() - start)

I'm trying to compile with this line
python3 -m py_compile memory

In my print statements I have some special characters from font awesome. Not sure if that would cause a problem but if it doesn't show up correctly in my post then that's what that is.
The output when I try to run the compiled file is
./memorycpython-35.pyc: line 1: $'\026\r\r': command not found
./memorycpython-35.pyc: line 2: �k�W��@s�ddlmZej�ZddlZdZej�Zejeej: command not found
./memorycpython-35.pyc: line 3: syntax error near unexpected token `)'
./memorycpython-35.pyc: line 3: `ej
                                �Z
                                  e
e                                      je
 j  Ze�eej�e�dS)�)datetimeNiii@)rZnow�startZpsutilZ
                                                                   BYTES_PER_GBZvirtual_memory�mZfreeZm_freeZpercentZ   m_percentZ
              swap_memory�sZs_freeZ s_percent�print�rr�memory<module>s

       '
   ^[[?62;c^[[?62;c

EDIT
To narrow down the problem I wrote the following script
#!/bin/python3
print("Hello World!")

This is the output
./testcpython-35.pyc: line 1: $'\026\r\r': command not found
./testcpython-35.pyc: line 2: syntax error near unexpected token `)'
./testcpython-35.pyc: line 2: `�r�W%�@sed�dS)z
                                               Hello World!N)�print�rr�./test<module>s'

Compiled using
python3 -m py_compile ./test

This creates a file in __pycache__/ called testcpython-35.pyc which I then do chmod +x testcpython-35.pyc and ./testcpython-35.pyc

A: It appears my issue is the ./testcpython-35.pyc part. When I run python3 testcpython-35.pyc, independent on whether I did chmod +x ./testcpython-35.pyc, the output is scrabbled. As long as I run the compiled program by first specifying what program to run it with, python3, it outputs Hello World! as expected.


text:
Q: Azure Datafactory Pipeline execution status It is kind of annoying we cannot change the logical order(AND/OR) of the Activity dependencies. however, I have got another issue. having said that I have activities for on failure to log the error messages in DB, since the logging activity succeeds, the entire pipeline  succeeds too! is there any workaround to say if any activities failed the entire pipeline and the parent pipeline, if it is called from another pipeline, should be failed either?
In my screenshot, i have selected the on completion dependencies to log the successful or error.

A: I see that you defined "On Success" of the copy activity to run "usp_postexecution" . Please define a "On failure"  of the copy activity and add any activity ( may be a set variable for testing  ) and execute the pipeline . The pipeline will fail .
Just to give you more context what i tried .
I have a variable name "test" of the type boolean and I am failing it deliberately ( by assigning to a non-boolean value of true1 )
Pipeline will fail when I define both success and failure scenarios .

The pipeline will succeed  when you have only "Failure" defined


text:
Q: minDate and maxDate Options not working in BeyondAdmin theme, mvc I am trying to add minDate and maxDates in datepicker of BeyondAdmin Theme not simple jquery datepicker, but it's not working. Following is myjquery code to set dates :
<script type="text/javascript">
     $('#id-date-picker').datepicker({
         format: 'dd/mm/yyyy',
         minDate: new Date(),
         maxDate: new Date(),
      });
</script>

and I have used razor syntax like this
@Html.Bootstrap().TextBoxFor(t => t.EntryDate).Id("id-date-picker")

Date Format is working fine but not min and max Dates. Has somebody used this theme, can somebody please help me out? Thank you