text:
Q: Vue.js transition-group deleting and adding again I have a list of forms in a Vue single page template.  The template loads content as arrays asynchronously which are then iterated over to create the forms.  the list is the child of a <transition-group>.  Each form has an up/down button enabling them to be moved up and down the list; when up/down is clicked the form above/below swaps with the clicked form using a transition animation.
The animation for the list is absolutely fine when the page is loaded with asynchronous content during the template's created() hook.
However, when the list is empty during created() or where all the forms in the list are deleted and a new form is subsequently added, the order animation ceases to operate.  Nothing else breaks, all the reactivity etc. is completely fine.  Given the below, is there a workaround to this bug?
I'll try and provide the briefest stub that I can below should it be useful:
[HTML]
<template>
...
<transition-group v-if="sections.length"
                          name="flip-list"
                          tag="div">

       <button @click.prevent="decrementOrder(section.order, i)">

       </button>
       <button @click.prevent="incrementOrder(section.order, i)">

       </button>
       ... FORM FIELDS ETC ...

</transition-group>
...
</template>

[JS]
computed: {
  sortedOrder () {
      let sorted = this.sections
      return sorted.sort((a, b) => { return a.order - b.order })
    }
},
methods: {
   ...
   addSection () {
      let newSection = {
        id: -1,
        order: this.sections.length,
        ...
      }
      let i = this.sections.push(newSection) - 1
      ...
    },
    deleteSection (id) {
      let wasSpliced = 0
      this.sections.forEach(function (section, i) {
        if (section.id === id) {
          this.sections.splice(i, 1)
          if (this.sections.length && this.sections.length > i) {
            --this.sections[i].order
          }
          wasSpliced = 1
        } else if (wasSpliced) {
          --this.sections[i].order
        }
      }.bind(this))
    },
    decrementOrder (order, i) {
      if (order > 0) {
        this.sections.forEach((it, j) => {
          if (it.order + 1 === order) {
            ++this.sections[j].order
            --this.sections[i].order
          }
        })
      }
    },
    incrementOrder (order, i) {
      if (order <= this.sections.length - 1) {
        this.sections.forEach((it, j) => {
          if (it.order - 1 === order) {
            --this.sections[j].order
            ++this.sections[i].order
          }
        })
      }
    }
    ...
}

[CSS]
...css
.flip-list-move {
transition: transform 1s;
}


text:
Q: Does Javascript temporary object need reference variable and/or closures? I need short messages disappearing after preset time. Please see the fiddle here: http://jsfiddle.net/X88F9/1/.
It works well, what I am not sure about is the reference for each created object:
function addObject() {
    new SomeObj(Math.random() * 1000 + 300);
}

it is not stored in any variable, can I just leave it as it is ? Or do I need to push them in some array ?
I also found this recommendation to put all in closures: https://stackoverflow.com/a/10246262/2969375, but not sure if necessary in my case and if yes, then how.

A: My answer to the question is: Javascript does not need a reference to the object to work, as proofed by your fiddle. So the question is more about if you need a reference to the object, to do other stuff with it later on. If you, for instance, would like to give the user the ability to click the temporarily display message and stop it from disappearing, than you can put all that code in a closure and do not need a reference, too. But if you would like to display the very same object again after it was removed from the DOM, than you need to store it in an array, other object, or variable, depending on your needs and ways to find it in a list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to identify if an x86-based Android device can run armeabi-v7a? Link https://developer.android.com/ndk/guides/abis.html says that many (but not all) x86-based Android devices can run armeabi-v7a and armeabi NDK binaries. Is there an API to identify if an x86-based device supports armeabi-v7a binaries? Or, is there an adb way to check for this support? Regards.

A: in case of my x86 android device there is this (accessible from Java side):
Build.SUPPORTED_ABIS = {java.lang.String[3]@4180}
 0 = "x86"
 1 = "armeabi-v7a"
 2 = "armeabi"

for adb access to check supported abis, you can try geting props
adb shell getprop ro.product.cpu.abilist

ro.product.cpu.abilist=x86,armeabi-v7a,armeabi
ro.product.cpu.abilist32=x86,armeabi-v7a,armeabi
ro.dalvik.vm.isa.arm=x86

more info about checking abis: https://software.intel.com/en-us/blogs/2014/12/16/how-to-identify-the-image-is-32-bit-or-64-bit-user-space

A: I believe there's a /system/lib/arm or something like that if Houdini is available.


text:
Q: PostgreSQL copy command generate primary key id I have a CSV file with two columns: city and zipcode. I want to be able to copy this file into a PostgreSQL table using the copy command and at the same time auto generate the id value.
The table has the following columns: id, city, and zipcode.
My CSV file has only: city and zipcode.

A: The COPY command should do that all by itself if your table uses a serial column for the id:

If there are any columns in the table that are not in the column list, COPY FROM will insert the default values for those columns.

So you should be able to say:
copy table_name(city, zipcode) from ...

and the id will be generated as usual. If you don't have a serial column for id (or a manually attached sequence), then you could hook up a sequence by hand, do your COPY, and then detach the sequence.


text:
Q: error in getFollowing(); the application hangs The application hangs, in these two parts. And it does not let you start the application.
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    mListView = (ListView) view.findViewById(R.id.listView);
    mFollowing = new ArrayList<>();
    mPhotos = new ArrayList<>();

    getFollowing(); /* <= error */

    return view;
}

private void getFollowing(){
    Log.d(TAG, "getFollowing: searching for following");

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    Query query = reference
            .child(getString(R.string.dbname_following))
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid()); /* <= error */

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                Log.d(TAG, "onDataChange: found user: "+
        singleSnapshot.child(getString(R.string.field_user_id)).getValue());

                mFollowing.add(singleSnapshot.child(getString(R.string.field_user_id)).getValue().toString());
            }
            mFollowing.add(FirebaseAuth.getInstance().getCurrentUser().getUid());
            //get the photos
            getPhotos();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}


text:
Q: golang time.Sleep bug? I make test code below(gotest.go)
package main

import (
    "fmt"
    "time"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    go testa()

    wg.Wait()
}

func testa() {
    for {
        fmt.Println("test goroutine")
        time.Sleep(2 * time.Second)
    }
}

console
go run gotest.go

and, change my computer's date
(ex : 2015-07-30 -> 2015-07-29)
and then,
println not printed!!
is it bug??
(It is working to set next day)
I use MacOs latest ver.
Thank you.

A: time.Sleep(20_000_000_000) n is nanoseconds

A: Internally sleep is done with absolute time: if you call Sleep(n) at time T the program is scheduled not to wake up after n time, but at time T + n.
This is generally preferable because:

*

*time usually does not flow backwards

*due to OS scheduling delays a program which repeatedly sleeps may lag behind schedule indefinitely; using absolute time make it compensate for delays by sleeping for shorter intervals.
In your case, you just have to wait for a day for the program to start printing again. :D
Or set a time just a little in the past (say 15 sec), and see the program resuming after 15+2 sec.
PS. To clarify what happens with an example:
At 2016-08-25 16:27:12 the program calls time.Sleep(2 * time.Second)
The Go runtime schedules the goroutine to be woken up on 2016-08-25 at 16:27:14 and puts the goroutine to sleep
meanwhile ...
the user sets the system time to 2016-08-24 16:27:13
now the timeout is scheduled to expire one day and one second later.
This should not happen on systems, on which Go uses POSIX CLOCK_MONOTONIC or equivalent thereof.


text:
Q: Index and Match Function for Separated Comma I have been trying to make a formula which INDEX the value of Sheet1.Rage("B2") and Matches with Sheet2.Rage("A2") then paste the result in Sheet2.Rage("B2")
The Match ID's i have is with separated comma  in Sheet2.Rage("A2") like this BFXI77,CTIB60,KWPX76
and Sheet1.Rage("A2") has ID like this BFXI77.
So i want to SUM the result thrice in Sheet2.Rage("B2").
I have attached a Sheet link which may help better your help will be appreciated.
https://docs.google.com/spreadsheets/d/1I9kiYaTnaIS-EZ3QpN-6Z063Y2CGsDZNeZvYO5Z0bRw/edit?usp=sharing
=INDEX(Sheet1!B2:B27,MATCH(A2,Sheet1!A2:A27,0),1)

A: In Excel you can use FILTERXML function in array formula:
=SUM(INDEX(Sheet1!B:B,N(IF(1,MATCH(FILTERXML("" & SUBSTITUTE(A2,",","") & "","//b"),Sheet1!A:A,0)))))

Array formula after editing is confirmed by pressing ctrl + shift + enter

A: You need to split the 3 separate MatchIds at comma, and then do the VLOOKUP separately on each one.
It's a bit tricky because if there are not enough commas, you get #VALUE!, so each formulas for the second and third lookups have to check using ISERROR.
Like this: On sheet 2
B2 formula: comma 1 pos:  =FIND(",",A2)
C2 formula: comma 2 pos : =FIND(",",A2,B2+1)
D2 formula: lookup 1:     =LEFT(A2,IF(ISERROR(B2),LEN(A2),B2-1))
E2 formula: lookup 2:     =MID(A2,B2+1,IF(ISERROR(C2),LEN(A2),C2-1)-B2)
F2 formula: lookup 3:     =RIGHT(A2,LEN(A2)-C2)
G2 formula: value 1:      =VLOOKUP(D2,ItemTable,2,0)
H2 formula: value 2:      =IF(ISERROR(B2),,VLOOKUP(E2,ItemTable,2,0))
I2 formula: value 3:      =IF(ISERROR(C2),,VLOOKUP(F2,ItemTable,2,0))
J2 formula: Total:        =G2+H2+I2


text:
Q: If value in column A is true or equal take the value from Column B ```Class       Grade
   Physics       8
   Math          7
   English       7.5
   Biology       5
   Physics       4

if(Class == Physics) {Sum(Grade)

I am looking that when the Class is similar to what I am searching it takes the Grade next to it. I assume something like this. and it will combine so in this case 12 for physics. And then That I can create a new dataframe where I can combine all the numbers corresponding to the Class.

A: A data.table solution for this.
df = data.frame(Class = c("Physics", "Math", "English", "Biology", "Physics"),
                Grade = c(8, 7, 7.5, 5, 4))

library(data.table)
setDT(df)
df[, sum(Grade), by =  Class]


text:
Q: Get end of week using PHP How can I return the end of the week using PHP?  I wanted to return an array of dates in the following format:-
Array
(
    [0] => Friday 17 April 2015
    [1] => Friday 24 April 2015
    [2] => Friday 1 May 2015
    [3] => Friday 8 May 2015
)

A: This should work for you:
(Here I simply create a DatePeriod starting from the next Friday from today. With a DateInterval of 7 days and until the next month)
<?php

    $today = (new DateTime())->modify("next Friday");
    $interval = new DateInterval("P7D");
    $end = (new DateTime())->modify("next month");
    $period = new DatePeriod($today, $interval, $end);

    foreach($period as $date)
        echo $date->format("l j F Y") . "<br />";

?>

output:
Friday 17 April 2015
Friday 24 April 2015
Friday 1 May 2015
Friday 8 May 2015

And for next time if you need todo something with dates see this: http://php.net/manual/en/book.datetime.php

A: Similar to Rizier's answer, but using PHP generators:
function fridays() {
    $begin = new DateTime('First friday of this month');
    $end = new DateTime('First friday of next month');

    $interval = new DateInterval( 'P1W' );
    $daterange = new DatePeriod( $begin, $interval ,$end );

    foreach($daterange as $date){
        yield $date;
    }
}

foreach(fridays() as $date){
    echo $date->format("l j F Y"), PHP_EOL;
}


text:
Q: Want to set innodb configuration variables setting properly ? want to know what variable size will best for mysql 5.5 I used Mysql 5.5.57 and used innodb
Currency I face performance related issues due to which our system gets crashed.
and got many errors like lockwait time out and deadlock problems on many tables.
I trying to solve that.
but i think if i change my innodb configuration default setting then also system performance gets increased but i dont know what type of variable needs to change so please help me
below is our default innodb configuration setting:
The below is the settings in my.cnf:
innodb_file_format=barracuda
innodb_file_format_max=barracuda
innodb_file_per_table=1
query-cache-size    = 64M
thread_cache_size   = 8
default-time-zone = '+05:30'
query_cache_limit   = 10M
character_set_server=utf8mb4
collation_server=utf8mb4_general_ci
innodb_thread_concurrency=8
key_buffer_size=183500800
group_concat_max_len=50000
innodb_log_file_size=178257920
#innodb_lock_wait_timeout=150

innodb_buffer_pool_size=134 MB
innodb_thread_concurrency=8
innodb_thread_sleep_delay=10000
innodb_concurrency_tickets=500
innodb lock_wait_time_out=150

We have 132GB Ram on the server with 2 processors and each has 6 cores.
16GB should be more than enough for MySql.
please help to set proper variables size for each parameter i provided here

A: I suggest you read this atrticle https://www.percona.com/blog/2013/09/20/innodb-performance-optimization-basics-updated/
You will find example for each variable there, i think this is what you need.

A: I've got a significant performance boost by setting
innodb_flush_log_at_trx_commit=0
innodb_buffer_pool_size=2G
innodb_log_file_size=256M
innodb_log_buffer_size=8M
innodb_buffer_pool_instances=1

Specifically, innodb_flush_log_at_trx_commit=0 speeds up loading a dump file from minutes to seconds! This setting is not recommended for "mission-critical" environments but is pretty fine for a development machine.


text:
Q: Access JSRender view data with converted values I have some converter functions - for example, one to format a column of dates from the raw data to what appears in the rendered table.
What I'm wondering is how to access the view data as it is shown in the output (as in post render and put through the converters). I can access the root data through the view object, but the date values are shown in the original format (as one would expect).
Here's the actual problem I'm trying to solve:
My table header has drop down menus with filter options based on distinct values in the column below. Those filter options must be for the entire data set (not just hat is currently filtered/shown). AND those filter options must be the converted values.
Above, I give an example with a date conversion. Another example would be a status 0 Disabled and 1 Enabled. The rendered tables shows Disabled or Enabled, based on the converter converting to those from 0s and 1s in the root data. If I create the filter based on the raw data, by default I have 0s and 1s instead of the converted values of Disabled and Enabled (that would shown in the rendered table below).


text:
Q: I get this error: 'jdb' is not recognized as an internal or external command, operable program or batch file." I tried remote debugging using Java debugger(jdb). Even though I have installed the jdk and set the JAVA_HOME variable properly but I get an error as above mentioned.
'jdb' is not recognized as an internal or external command, operable program or batch file."
Can anyone please tell what I did wrong?
Necessary details:
java -version
java version "1.8.0_211"
Java(TM) SE Runtime Environment (build 1.8.0_211-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.211-b12, mixed mode)
Please be noted: Anyway all of my java projects in NetBeans and Eclipse everything is working fine with java jdk except remote debugging.
And also if I type, it prompts this error againThis is the output image I got
jdb -version
'jdb' is not recognized as an internal or external command, operable program or batch file."

A: The Java JDK is installed properly, that is why you dont have any issues with Eclipse and Netbeans. JDB isnt working because you have to add the Path to JDK in System Environment Variables. To do this;

*

*just search for "System Environment Variable" in the Taskbar search feature and hit {Enter}.

*Select "Advanced" tab if not already selected.

*Click "Environment Variables"

*Select "Path" in User variables or System variables (I have selected it just for my profile)

*Click "Edit" and "Browse" to path of "C:\Program Files\JDK_version\bin"
Now open up a new command prompt and enter

jdb -version

you should be able to see JDB version details.
I know this is late, but anyone else with the same problem will hopefully find this helpful.


text:
Q: Function " was not declared in this scope" I'm new to C++ and I am attempting to write a program that simulates a football game. I'm getting a compiler error that says the functions get_rank, get_player, and get_name are not declared in this scope. Any help is greatly appreciated!
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Player {
    int playerNum;
    string playerPos;
    float playerRank;
    public:
        void set_values(int, string, float);
        float get_rank(){ return playerRank; };
};

class Team {
    Player team[];
    string teamName;
    public:
        void set_values(Player[],string);
        Player get_player(int a) { return team[a]; };
        string get_name() { return teamName; };
};

void play(Team t1, Team t2){
    float t1rank = 0.0;
    float t2rank = 0.0;
    for(int i=0; i<11; i++){
        t1rank += get_rank(get_player(t1, i));
    }
    for(int j=0; j<11; j++){
        t2rank += get_rank(get_player(t2, j));
    }
    if(t1rank>t2rank){
        cout << get_name(t1) + " wins!";
    }
    else if(t2rank>t1rank){
        cout << get_name(t2) + " wins!";
    }
    else{
        cout << "It was a tie!";
    }
}

A: It looks like you want to do something like:
    t1rank += t1.get_player(i).get_rank();

In C++, method calls are of the form object.method(args). In your case, you have two method calls, one where object is t1 and the method is get_player, and the second where the object is the return value of the previous call, and the method is get_rank.


text:
Q: how to clear tokenfield with js I want to make a reset button for a jquery tokenfield, but dont know how to reset it.
HTML
<input type="text" class="input" name="testtokenfield" id="testtokenfield" placeholder="testtokenfield" value="">
<button onclick ="clear()"></button>

JS
$('#testtokenfield').tokenfield({
        showAutocompleteOnFocus: true
});
function clear(){
     document.getElementById('testtokenfield').value = "";
}

A: Can't you just do:
$('#testtokenfield').tokenfield('destroy');

Reference: Tokenfield for Bootstrap.

A: Use setToken method to pass empty array to your input
$('#testtokenfield').tokenfield('setTokens', []);

see below working snippet :

$(function() {
  $('#testtokenfield').tokenfield({
    autocomplete: {
      source: ['red', 'blue', 'green', 'yellow', 'violet', 'brown', 'purple', 'black', 'white'],
      delay: 100
    },
    showAutocompleteOnFocus: true
  });

 $("#btn").on("click", function(e) {

  $('#testtokenfield').tokenfield('setTokens', []);
 });
});
body {
  padding: 5px;
}
<link href="http://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="http://sliptree.github.io/bootstrap-tokenfield/docs-assets/js/typeahead.bundle.min.js"></script>
<script src="http://sliptree.github.io/bootstrap-tokenfield/dist/bootstrap-tokenfield.js"></script>
<script src="http://sliptree.github.io/bootstrap-tokenfield/dist/bootstrap-tokenfield.js"></script>
<script
  src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
  integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
  crossorigin="anonymous"></script>
<link href="http://sliptree.github.io/bootstrap-tokenfield/dist/css/bootstrap-tokenfield.css" rel="stylesheet"/>
<link href="http://sliptree.github.io/bootstrap-tokenfield/dist/css/tokenfield-typeahead.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<input type="text" class="input" name="testtokenfield" id="testtokenfield" placeholder="" value="">
<br>
<button class="btn btn-success" id="btn">clear</button>

A: <input type="text" class="input" name="testtokenfield" id="testtokenfield" placeholder="testtokenfield"/>
<button id='clearbtn'>Clear</button>

const testtokenfield= document.getElementById("testtokenfield");
const clearbtn= document.getElementById("clearbtn");

clearbtn.addEventListener('click', ()=>{
                // clearing the input field
                testtokenfield.value = " ";
            })

we need to attach a click event to the clear button element and set a testtokenfield.value property to an empty string " ". so that when a user clicks on the button, the input field value is cleared.


text:
Q: What rights do I need to run DBCC commands? Do I need to be sysadmin to run DBCC commands on SQL Server? Or is db_owner rights enough?

A: Not all of them are the same, but at least one explicitly requires sysadmin.
See the Permissions section of DBCC INPUTBUFFER on msdn- this requires sysadmin. DBCC CHECKDB only requires db_owner.
Are there any in particular that you're looking to use?


text:
Q: Dropbox - no lan sync on a virtual machine Is there any way of making dropbox's lan sync working on a virtual machine ?
Another "dropboxed" machine in the LAN is a standalone PC running *buntu 12.04 amd64, not a VM.

detailed info:
host OS: Windows 7 64 bit
guest (VM): *buntu 12.10 amd64
target LAN is: inet addr:192.168.0.x Mask:255.255.255.0
while out of the box virtualbox's settings yield: inet addr:10.0.2.15 Mask:255.255.255.0 (NAT mode)
I've already tried to tamper with those settings and the most promising ones that I've managed to get are:
networking mode: "Bridged adapter", same LAN prefix, same MAC address as the host (with different MAC it wasn't possible to circumvent local network access denial), but neither Dropbox nor the Internet is working
Installing Dropbox on the host and mounting the folder to guest is last resort

A: I haven't used Dropbox on Linux, but have used it inside virtual machines. This should work as long as you set the VM network adapter to "Bridged" mode. Your virtual machine and and physical machine should then be on the same subnet, with similar IP addresses, i.e. both 192.168.0.x, but both with different MAC addresses. Then they should be able to find each other and do LAN syncing.
If you've changed the VM MAC address after installing the OS, it may be the case that you're experiencing the problem explained in this thread:
https://forums.virtualbox.org/viewtopic.php?f=7&t=43090
With the adapter set to bridged mode, and a unique MAC address for the VM, try running ifconfig in the VM. See if the ethernet interface exists, and if the VM has connectivity to the internet. If not, leave the unique MAC address as is and try the solution from that thread. It sounds like that's your problem, since you say the VM now has no internet access.
The aim is to get your VM onto the same subnet as the physical machine. Bridged mode is the adapter setting you need, since if using NAT mode, the virtual machine gets placed in a different subnet than the physical machine and the Dropbox software may not be able to recognize they're on the same physical network.


text:
Q: I'm not able to allocate the sums of integers in a list using a for loop I'm trying to give a general score to different sentences, some words have different values and I need a general score for each of the sentences:
sentences = ['This is so awesome , fr!', 'Ngl Im bad', 'awesome ! still bad tho' ]
values = {'awesome' : 4, 'bad' : -1 }

This is the for loop I used to get the sentences split:
split = []
for i in range(len(sentences)):
    split.append(sentences[i].lower().split(' '))

so far so good, but now I cannot get the general score of each of the sentences in a list, I've tried using for loops but never got the desired output, this was my first attempt:
scores = [0,0,0]

for list_ in split:
    for word in list_:
        if word in values:
            for i in range(len(punctuations)):
                scores[i] += values[word]
        else:
            continue

And this was my second attempt:
count = []
scores = []

for list_ in split:
    for word in list_:
        if word in values:
            count.append(values[word])
        else:
            continue
    scores.append(sum(count))

I've tried some other ways but I cannot find a solution, could you point me in the right direction?

A: Python is actually a really clean language for writing solutions to these types of problems:
sentences = ['This is so awesome , fr!', 'Ngl Im bad', 'awesome ! still bad tho' ]
values = {'awesome': 4, 'bad': -1}

ratings = [sum(values[word] if word in values else 0 for word in sentence.split()) for sentence in sentences]
print(ratings)

Result:
[4, -1, 3]

A bit of explanation:

*

*the whole expression assigned to ratings is a list comprehension, which constructs a list from an internal generator; a simple example is x = [range(3)]

*the generator loops over ever sentence in sentences and processes it

*the processing consists of computing the sum of the values from a second generator

*the second generator loops over the words in the sentence, by splitting it over spaces using .split() and looks up the value in values or assigns it value 0 if it's not in values
Perhaps a more readable version of the same code:
ratings = [
    sum(
        values[word] if word in values else 0
        for word in sentence.split()
    )
    for sentence in sentences
]


text:
Q: Incompatible types. Found: 'android.view.View', required: 'com.example.luckandchance.TextView' I am trying to display text in textview but this error shows:

Incompatible types. Found: 'android.view.View', required:
'com.example.luckandchance.TextView'

Here is the code:
package com.example.luckandchance;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.ui.AppBarConfiguration;
import com.example.luckandchance.databinding.ActivityCoinTossBinding;

public class CoinToss extends AppCompatActivity {

private TextView textView4;
private Button button3;

    private AppBarConfiguration appBarConfiguration;
    private ActivityCoinTossBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coin_toss);

        textView4 = findViewById(R.id.textView4);
        button3 = findViewById(R.id.button3);
    }
}

A: You probably created a class with the automatic solution when the IDE suggested it.
Add these imports:
import android.widget.Button;
import android.widget.TextView;

And delete the classes that you created.


text:
Q: Blackberry BrowserFieldHistory Does Not Get Updated by history.go(-1) javascript Have an application that is using a BrowserField.  The web site that is rendered within it all works fine except for an issue where pages have a back button that executes the following javascript: history.go(-1);
The page itself in the browser does go back one but the BrowserFieldHistory object is not updated and there are no requests to either handleNavigation or handleResource (I guess because the page is already cached).
Because of this the application cannot determine when the user has gone all the way back to the first page loaded and subsequently the Blackberry hardware back key cannot be used in the same way it operates in the device browser application (pressing back either goes back a web page or if pressed while in the first page closes the screen).
Any ideas why history.go(-1) is not reflected in the history stack and/or why the application doesn't receive handleNavigation/handleResource events?
I am developing on Win7 (32bit) in Eclipse Helios, BB 1.5 JDK on the 9800 (Torch) simulator (OS 6.0.0 of course).
Thanks
James


text:
Q: Can't run rails server within a DB-driven rails project; can't view localhost I'm able to create a "rails new demoproject" and run "rails s" successfully within the folder, however when I try and create a rails project with a DB "rails new demoproject -d mysql" and run "rails s" within the folder I get the following error:
user$ rails server
=> Booting WEBrick
=> Rails 4.0.0.beta1 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2013-04-20 16:06:26] INFO  WEBrick 1.3.1
[2013-04-20 16:06:26] INFO  ruby 1.9.3 (2013-02-22) [x86_64-darwin12.3.0]
[2013-04-20 16:06:26] INFO  WEBrick::HTTPServer#start: pid=1945 port=3000

Started GET "/" for 127.0.0.1 at 2013-04-20 16:06:39 -0400

Mysql2::Error (Access denied for user 'root'@'localhost' (using password: NO)):
  mysql2 (0.3.11) lib/mysql2/client.rb:44:in `connect'
  mysql2 (0.3.11) lib/mysql2/client.rb:44:in `initialize'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/mysql2_adapter.rb:18:in `new'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/mysql2_adapter.rb:18:in `mysql2_connection'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:446:in `new_connection'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:456:in `checkout_new_connection'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:427:in `acquire_connection'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:364:in `block in checkout'
  /Users/user/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:363:in `checkout'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:273:in `block in connection'
  /Users/user/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:272:in `connection'
  activerecord (4.0.0.beta1) lib/active_record/connection_adapters/abstract/connection_pool.rb:552:in `retrieve_connection'
  activerecord (4.0.0.beta1) lib/active_record/connection_handling.rb:79:in `retrieve_connection'
  activerecord (4.0.0.beta1) lib/active_record/connection_handling.rb:53:in `connection'
  activerecord (4.0.0.beta1) lib/active_record/migration.rb:739:in `current_version'
  activerecord (4.0.0.beta1) lib/active_record/migration.rb:747:in `needs_migration?'
  activerecord (4.0.0.beta1) lib/active_record/migration.rb:357:in `check_pending!'
  activerecord (4.0.0.beta1) lib/active_record/migration.rb:346:in `block in call'
  activesupport (4.0.0.beta1) lib/active_support/logger_silence.rb:16:in `silence'
  activerecord (4.0.0.beta1) lib/active_record/migration.rb:345:in `call'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.0.0.beta1) lib/active_support/callbacks.rb:373:in `_run__3314375952420028571__call__callbacks'
  activesupport (4.0.0.beta1) lib/active_support/callbacks.rb:78:in `run_callbacks'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/reloader.rb:64:in `call'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.0.0.beta1) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.0.beta1) lib/rails/rack/logger.rb:21:in `block in call'
  activesupport (4.0.0.beta1) lib/active_support/tagged_logging.rb:67:in `block in tagged'
  activesupport (4.0.0.beta1) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.0.beta1) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.0.beta1) lib/rails/rack/logger.rb:21:in `call'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.0.beta1) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.0.beta1) lib/action_dispatch/middleware/static.rb:64:in `call'
  railties (4.0.0.beta1) lib/rails/engine.rb:510:in `call'
  railties (4.0.0.beta1) lib/rails/application.rb:96:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  /Users/user/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
  /Users/user/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
  /Users/user/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

  Rendered /Users/user/.rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0.beta1/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
  Rendered /Users/user/.rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0.beta1/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.5ms)
  Rendered /Users/user/.rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0.beta1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.3ms)
  Rendered /Users/user/.rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0.beta1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (51.9ms)

And when I go to localhost:3000 I get a "Action Controller: Exception caught" error in the heading of the web browser and a mysql2 error on the web page which can be viewed here: http://postimg.org/image/9wemvhwkj/
update:
Here is what was in the database.yml file...
# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MYSQL driver
#   gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
#   gem 'mysql2'
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: mysql2
  encoding: utf8
  database: cms_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: mysql2
  encoding: utf8
  database: cms_test
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

production:
  adapter: mysql2
  encoding: utf8
  database: cms_production
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

A: username and password in your database.yml file do not have access to DB
you need to

*

*go to user mysql2 shell

*

*create new user

*new db

*grand the user permissions on the db

*go to database.yml file and update the development configurations to match

*

*user-name

*password

*db-adapter

*db name

A: Mysql2::Error (Access denied for user 'root'@'localhost' (using password: NO)): -  check database username\password

A: What I did to solve my question with your guys help:
In Terminal typed: mysql -u root -p (without -p if you did not set a root password when you installed mysql)
then typed CREATE DATABASE cms_development; (replace cms with your rails project name)
Then opened config/database.yml located in the rails project folder
And under "development:" put in my password under "password:"


text:
Q: Suggested/recommended use for {% block extraBody %} Did not find an example or recommended use of {% block extraBody %}
Your thought please.

A: The purpose of the extraBody nunjucks block in outerLayoutBase is to allow you to add code that you wish to place immediately before the closing </body> tag without being forced to override outerLayoutBase completely. You might, for instance, want to place third-party script tags here to avoid blocking rendering of the page while they load and run, if the script in question is not a good candidate for the async attribute.
Our goal with outerLayoutBase is to ensure that we insert Apostrophe's markup as part of a standardized base template that is flexible enough that people don't feel forced to override it and then have difficulty with markup we need to insert for Apostrophe later because they do not have the necessary template code in their stale copy of outerLayoutBase. Project level code should, if needed, start with an override of outerLayout that extends outerLayoutBase and just overrides a few blocks rather than reinventing the wheel. You'll note that the "stock" version of outerLayout is intentionally set up this way — it just extends outerLayoutBase and does nothing else. Your version can extend outerLayoutBase and override some blocks.
We encourage our own in-house developers to follow this rule, and to add new blocks to outerLayoutBase if they would otherwise be forced to override it, as a way of ensuring that other developers find the needed flexibility is there for them as well.


text:
Q: QMake / Moc behave differently when MOD_DIR is set I'm now working on a project that causes me headache.
I use some piece of code provided by a third party in which at one point, a MOC file is included at the end of a cpp file. Let's call those files respectively moc_problematic.cpp and problematic.cpp
If I leave MOC_DIR empty - by doing nothing or adding 'MOC_DIR = ' to my pro file, the generated project uses the MOC to generate moc_problematic.cpp (and all others), places in in my project's folder, and kind of automatically sees that it is included somewhere and shouldn't be compiled afterwards.
If I specify a custom MOD_DIR, the MOC generates all MOC files correctly and puts them into my MOC_DIR. Then the compiler compiles all moc files, including moc_problematic, and the build fails because some identifiers are unknown (as they are defined in problematic.cpp).
This behavior is identical whether I generate a makefile and use nmake or generate a vcproj and use Visual Studio.
Do anybody have an idea of what I'm doing wrong?
PS I'm using Qt 5.3.1 with MSVC2013


text:
Q: Spring MVC RESTful web services with Jackson: How to restrict to subset of URLs Following the steps outlined here http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program , I've been able to setup my RESTful WS exactly how I want it.
Now, I want to make this app context a hybrid of RESTful WS (under a specific URL prefix /myapp/rest/) and standard MVC mappings for the rest of the site.
But from the servlet-context XML file, I can't really make out how to restrict MappingJackson2HttpMessageConverterto only apply to a certain URL prefix.
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>

<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>

Is there anything else that I should be checking on here?
Thanks
Wong

A: You can have both SpringMVC style controllers and SpringMVC REST style controllers in the same application. In fact you can write one SpringMVC handler method and a REST Endpoint in same controller too.
@Controller
public class MyController
{
    @RequestMapping("/home")
    public String homePage(Model model)
    {
        model.addAttribute("data",someObject);
        return "home"; //this will render the view home.jsp
    }

    @RequestMapping(value="/users", method=RequestMethod.POST)
    @ResponseBody
    public User saveUser(@RequestBody User user)
    {
        //persist user
        return user; //this will return JSON/XML based representation of User object
    }

}

Observe the use of @RequestBody and @ResponseBody annotations for REST style handler methods.


text:
Q: install git on RHEL3 having a problem installing git on redhat enterprise 3.  When I try and install the rpm it gives a circular dependency problem.
[root@tflaus001 tmp]# rpm -i git-1.5.2.1-1.el3.rf.i386.rpm
warning: git-1.5.2.1-1.el3.rf.i386.rpm: V3 DSA signature: NOKEY, key ID 6b8d79e6
error: Failed dependencies:
    perl(Git) is needed by git-1.5.2.1-1.el3.rf

[root@tflaus001 tmp]# rpm -i perl-Git-1.5.2.1-1.el3.rf.i386.rpm
warning: perl-Git-1.5.2.1-1.el3.rf.i386.rpm: V3 DSA signature: NOKEY, key ID 6b8d79e6
error: Failed dependencies:
    git = 1.5.2.1-1.el3.rf is needed by perl-Git-1.5.2.1-1.el3.rf
    perl(Error) is needed by perl-Git-1.5.2.1-1.el3.rf

can anyone give me an idea of how to fix this or what I need to add to yum.conf to fix this?

A: Install both at the same time, i.e.
rpm -i git-1.5.2.1-1.el3.rf.i386.rpm perl-Git-1.5.2.1-1.el3.rf.i386.rpm

An alternative is to use yum localinstall some-package-...rpm where yum will resolve and download any missing dependencies (but in this case you do not need that since you obviously have the two packages you need already).

A: # rpm -ivh git-1.5.2.1-1.el3.rf.i386.rpm perl-Git-1.5.2.1-1.el3.rf.i386.rpm

or you can install DAG repo  yum install git*
yum install rhel 3 how to


text:
Q: Debugging Goodreads Bookshelf Request Currently building a Swift iOS app using the api and I'm coming up against something funky. I'm trying to cycle through an array of shelves and pull down data for each shelf using a for loop with Goodreads' reviews.list API method.
Here's what it looks like:

func getBooksFromShelf(_ oauthswift: OAuth1Swift, userID: String, shelf: Shelf, name: String) {
        let _ = oauthswift.client.get(
            "https://www.goodreads.com/review/list?v=2",
            parameters: ["key": developerKey, "id": userID, "shelf": name, "sort": "date_added"],
            success: { response in
                let xml = SWXMLHash.parse(response.data)
                for review in xml["GoodreadsResponse"]["reviews"]["review"].all {
                    let book = review["book"]
                    let bookID = book["id"].element!.text
                    let bookTitle = book["title"].element!.text
                    let bookCoverURL = URL(string: book["image_url"].element!.text)

                    var bookAuthors = "by "
                    for author in book["authors"].all {
                        bookAuthors += author["author"]["name"].element!.text
                    }

                    let newBook = Book.init(id: bookID, title: bookTitle, authors: bookAuthors, cover: bookCoverURL)
                    shelf.books.append(newBook)
                }
        },

The problem is each run through the loop returns the data for https://www.goodreads.com/review/list/USER_ID_HERE.xml?key=DEVELOPER_KEY_HERE&v=2  as if no parameters were added to the request at all. But when I replace the name variable with the string of a shelf I know exists —like "currently-reading"—I get the proper result https://www.goodreads.com/review/list/USER_ID_HERE.xml?key=DEVELOPER_KEY_HERE&v=2&shelf=currently-reading.
I've tried dropping the parameters array and creating the URL string myself but that's not working either. I saw this thread but it's not quite the same since I'm not getting an error message, just the wrong url. Any ideas?


text:
Q: Are C# events feasible for domain events in DDD? I read that people use event dispatching libraries for domain events in their domain-driven design.
The C# language have built-in support for events using the event keyword together with the EventHandler<> class. Is it feasible to use this instead of a event dispatcher library (such as MediatR)?
I know that domain events are often dispatched when persisted, not when the method on the aggregate is called. But by adding the events to a List<Action> you can defer the raising of events.
Event declaration:
public event EventHandler<InvoiceCreatedEventArgs> InvoiceCreated;

Deferred event raising:
private ICollection<Action> _events = new List<Action>();

public void AddDomainEvent(Action action)
{
    _events.Add(action);
}

protected virtual void OnInvoiceCreated(InvoiceCreatedEventArgs e)
{
    AddDomainEvent(() => { InvoiceCreated?.Invoke(this, e); });
}

If the events are exposed as public members of the root aggregate then the application would have to resubscribe for every new instance of the root aggregate whenever a root aggregate was fetched from the repository.
Wouldn't that be a bit of a undesirable trait to have to resubscribe for every instance? Would the application have to unsubscribe too?
Unless the events were declared as static, but I have heard bad things about static events and memory leaks. Would this be a concern?
If C# events were used, would they belong in the root aggregate or would they belong in the repository?
If the events were declared in the repository (which could be a Entity Framework Core DbContext) then when registered with the ASP.NET Core dependency handler using the .AddDbContext method it would be registered with the "Scoped" lifetime (once per client request), so unless the events were to be declared as static then the application would have to resubscribe on every new instance of the repository which would occur at every new incoming HTTP request.
Is using C# events for domain events in a application employing domain-driven design feasible or is it just an non-viable ill-fated idea?

A: Without distinguishing between C# Events and Domain Events it's difficult to follow your narrative.  However, if I understand your proposal correctly, you're envisioning a C# component that listens to the Entity Event stream, then publishes those incoming domain events via C# events to listeners in the app.  If that's what you're proposing then you would have to work hard to make it work, and it wouldn't work well.
If we look at Mediatr, it subscribes to an event source and creates new command processors to process incoming domain events.  The key is that it creates new command processors so it is able to call a method on them.  Also, there is a one-to-one correspondence between a domain event and a command processor, and nothing is required at system startup other than Mediatr itself.
With C# Events the command processor is created by something, then registers itself to receive C# events of a particular type.  The command processor initiates the link, not the event source subscriber.  In order to process all kinds of events, at startup you would have to create at least one of each type of command processor and let it register itself as the receiver of the C# messages which carries the Domain Event as a payload.
Then what happens when you start to scale? Mediatr scales well because it creates a command processor for each Domain Event.  Your proposal would not scale because to process 2 of the same event type you would need to manually create 2 command processors, and each of those command processors would receive BOTH of the incoming Domain Events because they are both subscribed to the same C# Event.
It is possible to code around all this mess, but that's what Jimmy Bogard has already done.  Instead of rewriting all that just fire up NuGet, pull down Mediatr, and then go play with your kids with all the time you saved.

A: It depends on the type of application.
If the application is a web application then it have a DbContext scoped to the life time of the HTTP request, and all the aggregates have a short life time too that lasts for the duration of the HTTP request. Hence registering the C# event handlers is cumbersome, also since you would have to do it after you fetch get the DbContext or the aggregate it would have to be inside the controller, repeatedly, everywhere. So for web applications using C# for events is a poor choice, and it a much better idea to delegate it to a singleton class as is done with MediatR.
If the application maintains a persistent DbContext that survives for the lifetime of the application and a root aggregate that survives for the lifetime of the application then you can could use C# events and just register the event handlers once. Such an application could be a command-line application, a background service, or a desktop application with a UI.


text:
Q: EditText: Toggle InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS I've created a custom EditText by extending android.widget.EditText.
I would like to have the auto correct spans only visible, when the EditText has focus. So I call setInputType(INPUT_NO_FOCUS); in the constructor and:
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    if (focused) {
        setInputType(INPUT_FOCUS);
    } else {
        setInputType(INPUT_NO_FOCUS);
    }
}

with:
private final int INPUT_NO_FOCUS = TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE
        | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
private final int INPUT_FOCUS = TYPE_CLASS_TEXT | TYPE_TEXT_FLAG_MULTI_LINE
        | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLET;

==> There is indeed no auto correction and auto complete, but it does not appear after clicking on the EditText. Input type is changed successfully.
How can I trigger the auto correction/ add auto completion?
//Edit:
User Case I want to archive:

*

*MyEditText extends EditText view is displayed and not focused. There is no spell checking on the text (--> No red spans/lines under the text)

*User clicks into the edit field to. --> Spell checking gets triggered --> Red lines appear (User can click on wrong spelled words and let the OS correct them)

*User clicks on another View element --> Red lines/spans disappear.

A: I'm afraid there's no good way to do this.  The problem is that the Android framework doesn't really have a mechanism to tell the keyboard when the input type has changed.  A keyboard generally checks the type when the field opens.  After that, if the type changes it won't know unless it polls for it, and I don't think any existing keyboard does that.

A: Override this method in MyEditText class
@Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        setInputType(INPUT_FOCUS);
    }
Using this method you can change the inputType of EditText to INPUT_FOCUS that show red line under text when user edit text of MyEditText


text:
Q: Cross platform internationalization I'm in the process of writing a cross platform c# application that will run on win/linux using .net/mono.
I want to internationalize the application. Should I use Mono.Unix or System.Globalization?

A: System.Globalization should be supported by Mono if it is part of the standard (which I think it is); Mono.Unix won't be supported by .Net, so I personally would rely on System.Globalization and maybe look at runtime referencing of Mono.Unix at a later date if it proves that you really really really need it...


text:
Q: onClick not working but mouseOver working

   {
      editNestedComment(chldCmt, e);
    }}
  >
    Edit Comment

;

onClick is not working but mouseOver working fine.

A: An anchor tag refreshes the page when clicked.
To prevent this add e.preventDefault() to the onClick function
example:
 {
         e.preventDefault()
         editNestedComment(chldCmt, e)
         }}
>
 Edit comment

Not too sure why you are using an anchor tag as you are not using a href to link anywhere. It makes much more sense to replace the anchor tag with a button tag and then this wouldn't be a problem.
E.g.
  <button
    onClick={e => {
      editNestedComment(chldCmt, e)
    }}
  >
    Edit Comment
  </button>

A: Try sharing the code for the function that you passed as well.
Here's the documentation:
https://reactjs.org/docs/handling-events.html
You should probably use a button:

  <button
    onClick={(e) =>
      editNestedComment(chldCmt, e)
    }
  >
    Edit Comment
  </button>

;


text:
Q: Java how to stream a list inside a list for an object? So I have lists stored inside of another list.
And inside of that lists there a different objects.
I want to get a specific object based on an attribute.
Human robert = building.getRoomList()
    .stream()
    .filter(room -> room.getEmployeeList()
         .stream()
         .filter(human -> human.getName().equals("Robert")))
    .findFirst().get();

Why doesn't it work?

A: Try this:
Human robert = building.getRoomList().stream()
    .map(Room::getRoomList)
    .flatMap(Collection::stream)
    .filter(human -> human.getName().equals("Robert"))
    .findFirst()
    .orElseThrow(() -> new RuntimeException("Robert not found!"));

A: You can do it using Stream.flatMap:
Optional<Human> robert = building.getRoomList().stream()
    .flatMap(room -> room.getEmployeeList().stream())
    .filter(human -> human.getName().equals("Robert"))
    .findFirst();

robert.ifPresent(r -> /* do something with Robert */);

Stream.flatMap maps each room to a stream of humans and the returned stream consists of all the humans of all the rooms, flattened (i.e. not as sublists or substreams).

A:
Why doesn't it work?

Stream::filter requires a Predicate<T> and returns the very same Stream<T>. As long as you nest filter in filter, this would never work because the outer one requires Predicate<T> while the inner one returns Stream<T> which is clearly not compatible.
You might want to use flatMap:
Human robert = building.getRoomList()
    .stream()                                     // Stream<Room>
    .flatMap(room -> room                         // Stream<Human> flatmapped from:
        .getEmployeeList()                        // .. for each Room get List<Human>
        .stream()                                 // .. for each Room have Stream<Human>
        .filter(human -> human.getName()          // .. for each Room keep the one named
                              .equals("Robert"))) // .. Robert
    .findFirst()                                  // find the first Robert, the Human
    .orElse(null);                                // or result in null

Remember the predicate human -> human.getName().equals("Robert")) is not null-safe neither when human is null nor when its name is null. For the null-safety, flat-map like this:
    .flatMap(room -> room.getEmployeeList()
                         .stream()
                         .filter(Objects::nonNull)
                         .filter(human -> "Robert".equals(human.getName())))

A: You are doing .findFirst() on RoomList only but you need to do .findFirst() on inner list means EmployeeList of every Room also and transform Room into Human using .map(), like
building.getRoomList()
.stream()
.map(room -> room.getEmployeeList()
                 .stream()
                 .filter(human -> human.getName().equals("Robert"))
                 .findFirst().get())
.findFirst().get();

Which can be simplified using flatMap to flatten then EmployeeList then get findFirst
building.getRoomList()
        .flatMap(e -> room.getEmployeeList().stream())
        .filter(human -> human.getName().equals("Robert"))
        .findFirst().get();

Note: It's better to use .orElse() rather calling .get()


text:
Q: está correto o teste de validade do RegExp? estou tentando validar uma senha através do RegExp, em javascript, mas ele só retorna false quando na verdade deveria retornar true, por ter dado match no valor, alguém saberia se tem algo de errado com meu codigo?
    $scope.verifyPasswordIsValid = function (a , b) {
    var digits_4 = new RegExp("^(\d\d)\d{0,4}\1$");
    var seq_number = new RegExp("^1*2*3*4*3*2*1$");
    var seq_alphab = new RegExp("^a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$");

    console.log("reg alp: "+seq_alphab.test(a));
    console.log("reg 4: "+digits_4.test(a));
    console.log("reg number: "+seq_number.test(a));
}

A: Percebi que o problema estava na interpretação do navegador, onde ele removia as barras "\"
para resolver isso é simples, é só adicionar outra barra na frente, ou seja, o codigo fica assim:
   $scope.verifyPasswordIsValid = function (a , b) {
var digits_4 = new RegExp("^(\\d\\d)\\d{0,4}\\1$");
var seq_number = new RegExp("^1*2*3*4*3*2*1*$");
var seq_alphab = new RegExp("^a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$");

console.log("reg alp: "+seq_alphab.test(a));
console.log("reg 4: "+digits_4.test(a));
console.log("reg number: "+seq_number.test(a));

}
para os sequenciais estava faltando o "*" na frente do sinal de dólar


text:
Q: passing 'const *' as 'this' error during if comparison I get the error:

../ConcreteRequest.h:23:49: error: passing 'const
  std::map, std::basic_string >' as 'this'
  argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type&
  std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp,
  _Compare, _Alloc>::key_type&&) [with _Key = std::basic_string; _Tp = std::basic_string; _Compare = std::less >; _Alloc =
  std::allocator,
  std::basic_string > >; std::map<_Key, _Tp, _Compare,
  _Alloc>::mapped_type = std::basic_string; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::basic_string]' discards qualifiers [-fpermissive]

#ifndef CONCRETEREQUEST_H
#define CONCRETEREQUEST_H
#include "RequestFactory.h"
#include "Request.h"
#include "MasterFile.h"
#include <map>
#include <string>
#include <iostream>

class ConcreteRequest : public RequestFactory
{
  Request *createRequest(const std::map<std::string,std::string> &input) const
  {
    std::cout << "==Starting createRequest==" << std::endl;
    Request *pRequest;

    if (input["dataset"] == "masterfile")
      {
        pRequest = new MasterFile(input);
      }

    std::cout << "==Finishing createRequest==" << std::endl;
    return pRequest;
  }
};
#endif

This is for the if comparison. Why?


text:
Q: Change right icon image UITextField I am trying to change between rightView UIImages that are added as a subView to my UITextfield. When a user taps the icon it should show or hide the inserted password and change the UIImage depending on the state.
How am I able to edit the code below to achieve this?
Code:
// Show eye icon to show the password
    func textFieldDidChange() {
        if passwordField.text != "" {
            let leftImageView = UIImageView()
            leftImageView.image = UIImage(named: "view_password")
            leftImageView.contentMode = .scaleAspectFit

            let leftView = UIView()
            leftView.addSubview(leftImageView)

            leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
            leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 12)

            passwordField.rightViewMode = .whileEditing
            passwordField.rightView = leftView

            let tapgesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.togglePasswordSecurity))
            leftImageView.isUserInteractionEnabled = true
            leftImageView.addGestureRecognizer(tapgesture)

        }else{
            passwordField.rightViewMode = .never
        }
    }

    func togglePasswordSecurity(imageView: UIImageView) {

        if passwordField.isSecureTextEntry == false {

            // change left UIImage to hide_password
            passwordField.isSecureTextEntry = true
        }else{

            // change left UIImage to view_password
            passwordField.isSecureTextEntry = false
        }
    }

Thanks a lot!

A: Have you tried adding a tag to each of your images?
For example:
let leftImageView = UIImageView()
leftImageView.image = UIImage(named: "view_password")
leftImageView.contentMode = .scaleAspectFit
leftImageView.tag = 1

Then, to change that image you can write:
let myImage = UIView(withTag: 1) as! UIImageView
myImage.image = ...

EDIT:
To toggle between 2 images, just change this:
    func togglePasswordSecurity(imageView: UIImageView) {
    if passwordField.isSecureTextEntry == false {

        let myImage = UIView(withTag: 1) as! UIImageView
        myImage.image = YOUR_IMAGE_1
        // change left UIImage to hide_password
        passwordField.isSecureTextEntry = true
    }else{

        let myImage = UIView(withTag: 1) as! UIImageView
        myImage.image = YOUR_IMAGE_2
        // change left UIImage to view_password
        passwordField.isSecureTextEntry = false
    }
}

A: Solution:
// Show eye icon to show the password will be triggered once there is a change in data in the UITextField
    func textFieldDidChange() {
        if passwordField.text != "" {
            let leftImageView = UIImageView()
            leftImageView.image = passwordImage
            leftImageView.contentMode = .scaleAspectFit
            leftImageView.tag = 1

            let leftView = UIView()
            leftView.addSubview(leftImageView)

            leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
            leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 12)

            passwordField.rightViewMode = .whileEditing
            passwordField.rightView = leftView

            let tapgesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.togglePasswordSecurity))
            leftImageView.isUserInteractionEnabled = true
            leftImageView.addGestureRecognizer(tapgesture)

        }else{
            passwordField.rightViewMode = .never
        }
    }

    func togglePasswordSecurity() {

        if passwordField.isSecureTextEntry == false {

            passwordImage = UIImage(named: "view_password")
            textFieldDidChange()

            // change left UIImage to hide_password
            passwordField.isSecureTextEntry = true
        }else{

            passwordImage = UIImage(named: "heart")
            self.textFieldDidChange()
            // change left UIImage to view_password
            passwordField.isSecureTextEntry = false
        }
    }


text:
Q: Access Nested Map With Using Escape Character in Esper I have a LinkedHashMap like so:
{_index=1, _type=zz, _source={custom_field=custom, field_0=Group, field_10=was, field_3}}

Using an EPL statement, how can I access the custom_field in a EPL statement. Here are some things I've tried
String expression = "select `_source.custom_field` from MyMapEvent";
String expression = "select \\_source.custom\\_field` from MyMapEvent";

The escape characters documentation can be found here: http://esper.codehaus.org/esper-4.6.0/doc/reference/en-US/html_single/index.html#eventrep-properties-escaping

A: I have tried this and it works: create schema MyInnerEvent(_c int); create schema MyEvent(_a int, _b MyInnerEvent); select _b._c from MyEvent;


text:
Q: Enrollment's like table has days split into rows, format these as columns instead I have a table that holds student enrollments in a class that has the following rows:
Enrollment_id | Student_id | ... | Day | start_time | end_time| Location

For a student enrolled in say Math 101, which for example could be at 2pm to 4pm on Monday Tuesday, and 4pm to 5pm on Thursday, would have the following data in the table.
1 | x | 'Monday' | 14:00:00 | 16:00:00 | 'Class Room x'
1 | x | 'Tuesday' | 14:00:00 | 16:00:00 | 'Class Room x'
1 | x | 'Thursday' | 16:00:00 | 17:00:00 | 'Class Room x'

I need to create an export for this, that formats this students enrollments as the following:
Student_id | ... | M | T | W | T | F | Time | Location
x | ... | Y | Y | N | N | N | '14:00:00 - 16:00:00 | 'Class Room X'
x | ... | N | N | N | Y | N | '16:00:00 - 17:00:00 | 'Class Room X'

So it's essential grouping by the student_id, some course information, then by the time. Once grouped, it creates this Monday / Tuesday, ect. columns and puts either a Y / N if they have that class on that day. This is also by specific times, so the same class may have different times (IE labs, and classroom lectures) on different days, and these would be different rows.
Looking for help on how to write this as a subquery. Happy to provide additional info on the table, or other tables around it. I'm stumped on this one though, and I'm not even sure it's possible. Currently, this is done in a Python api using Sqlalchemy so either as a sqlalchemy or raw sql would be great!

A: You could use the CASE expressions like below.
SELECT student_id,
   ISNULL(MAX(CASE WHEN DAY = 'Monday'
              THEN 'Y'
              END),'N') AS 'M',
   ISNULL(MAX(CASE WHEN DAY = 'Tuesday'
        THEN 'Y'
        END),'N') AS 'T',
   ISNULL(MAX(CASE WHEN DAY = 'Wednesday'
        THEN 'Y'
        END),'N') AS 'W',
   ISNULL(MAX(CASE WHEN DAY = 'Thursday'
        THEN 'Y'
        END),'N') AS 'T',
   ISNULL(MAX(CASE WHEN DAY = 'Friday'
        THEN 'Y'
        END),'N') AS 'F',
   CONCAT(Start_time,'-',end_time) as Time,
   Location
   FROM student
   GROUP BY student_id,CONCAT(Start_time,'-',end_time),Location

Result set based on your sample data
student_id  M   T   W   T   F   Time                Location
 x          Y   Y   N   N   N   14:00:00-16:00:00   Class Room x
 x          N   N   N   Y   N   16:00:00-17:00:00   Class Room x

A: I think you want conditional aggregation:
select student_id, time, location,
       max(case when day = 'Monday' then 'Y' else 'N' end) as mon,
       max(case when day = 'Tuesday' then 'Y' else 'N' end) as tue,
       . . .
from t
group by student_id, time, location;

Because you are using Postgres, I would advise you to use booleans rather than characters for each day.  That results in the simpler:
select student_id, time, location,
       bool_or(day = 'Monday') as mon,
       bool_or(day = 'Tuesday') as tue,
       . . .
from t
group by student_id, time, location;


text:
Q: Change the type of the key in a dictionary I got this JSON:
{
  "test":{
    "0":{
      "test":"test"
    }
  }
}

The key in a JSON can only be a string, so when I retrieve this json, I got the following declaration:
let myJson = [String: [String: Any]]()

Now I want to filter out all the keys than can be casted to an integer, so the dictionary I want to use is:
let myJson2 = [Int: [String: Any]]()

How can I compactMap/filter myJson to myJson2 to filter out all the Int keys and copy the value? I got this:
var myJson2 = [Int: [String: Any]]()

for (key, value) in myJson {
    guard let keyInt = Int(key) else { return }
    myJson2[keyInt] = value
}

But I am looking for a solution with compactMap which can do it in 1 line

A: You can use compactMap on the sequence of key/value pairs of the original
dictionary to extract those with an integer key, and Dictionary(uniqueKeysWithValues:) to create a new dictionary:
let myDict: [String: [String: Any]] = [
    "test": [ "0": [ "test" : "test" ]],
    "123": [ "1" :[ "foo": "bar" ] ]
]

let myDict2 = Dictionary(uniqueKeysWithValues: myDict.compactMap { (key, value) in
    Int(key).map { ($0, value) }
})

print(myDict2) // [123: ["1": ["foo": "bar"]]]
print(type(of: myDict2)) // Dictionary<Int, Dictionary<String, Any>>

Here it is assumed that all strings represent different integers. If that
is not guaranteed then use
let myDict2 = Dictionary(myDict.compactMap { (key, value) in
    Int(key).map { ($0, value) }
}, uniquingKeysWith: { $1 })

instead. The additional parameter determines which value
is used in the case of duplicate keys,  with { $1 } the last one
"wins".


text:
Q: Equivalent condition for flatness of an A-module (Atiyah-MacDonald ex. 2.26) I would like to solve the following exercise (2.26) from Atiyah & MacDonald's "Introduction to Commutative Algebra":
If $M$ is an $A$-module (where $A$ is a commutative ring), then:
$$M \text{ is flat} \iff \text{Tor}_1(M,A/\mathfrak{a}) = 0 \text{ for all finitely generated ideals } \mathfrak{a}\subset A$$
I managed to prove that:
$$M \text{ flat } \iff  \text{Tor}_1(M,A/\mathfrak{a}) = 0 \text{ for all ideals } \mathfrak{a}\subset A$$
Any solutions or suggestions on how to proceed would be much appreciated.

A: So you want to show that $\operatorname{Tor}_1(M,A/\mathfrak{a}) = 0$ for all finitely generated ideals $\mathfrak{a} \subset A$ implies that $\operatorname{Tor}_1(M,A/\mathfrak{a})$ for all ideals $\mathfrak{a} \subset A$. Let's suppose we have such an ideal $\mathfrak{a}$. The trick is to 'approximate' $\mathfrak{a}$ by finitely generated ideals by writing it as an inductive limit $\mathfrak{a} = \varinjlim \mathfrak{a}_n$ of finitely generated ideals (this can always be done). Then, assuming I haven't convinced myself of anything false, we can write $\operatorname{Tor}_1(M,A/\mathfrak{a}) = \operatorname{Tor}_1(M,A/\varinjlim \mathfrak{a}_n) = \operatorname{Tor}_1(M,\varinjlim A/\mathfrak{a}_n) = \varinjlim \operatorname{Tor}_1(M,A/\mathfrak{a}_n)$, thus reducing the question to the finitely generated case.
Now you can use the assumption that each $\operatorname{Tor}_1(M,A/\mathfrak{a}_n)$ vanishes.
(disclaimer: I haven't thought hard about commutative algebra for a while, so apologies if I've overlooked anything important)


text:
Q: reddit get_comments action, can someone clarify what is going on here? I'm trying to understand reddit's source, and I am looking at the get_comments action method of front.py
This is the action that displays a story:
http://code.reddit.com/browser/r2/r2/controllers/front.py#L139
Specifically, what is the top part of the method doing where there is a @Validate marker?
And on the bottom near the return, it is sending objects to the view page.
Which viewpage is being called here?
211 res = LinkInfoPage(link = article, comment = comment,
212                            content = displayPane,
213                            subtitle = _("comments"),
214                            nav_menus = [CommentSortMenu(default = sort),
215                                         NumCommentsMenu(article.num_comments,
216                                                         default=num_comments)],
217                            infotext = infotext).render()
218         return res

A:
Specifically, what is the top part of the method doing where there is a @Validate marker?

@validate is validation decorator, used to validate and process parameters from request.
You can see its sources at http code.reddit.com/browser/r2/r2/controllers/validator/validator.py#L129

And on the bottom near the return, it is sending objects to the view page.
  Which viewpage is being called here?

It does not use 'view page', it uses widgets there. LinkInfoPage which contains PaneStack (http code.reddit.com/browser/r2/r2/lib/pages/pages.py#L1317)
So res = LinkInfoPage(...).render() is already generated html, in Pylons response form. It recursively calls .render() on underlying widgets.
P.S. you need to add :// to links, since it does not let to post more than one link.


text:
Q: Why does a "less than" expression become a "less than or equal to" expression after taking a limit? In a proof of the completeness of $l^\infty$ on this page, the author finds a candidate limit point $x$ for a cauchy seqeuence $x^n$. He then chooses an $\varepsilon$ and then considers $\varepsilon/2$ and says we can find $N > 0$ such that $$|x_k^n - x_k^m | < \frac{\varepsilon}{2},$$
for all $k$ and for all $n, m > N$.
Then he takes the limit as $m \to \infty$ and obtains
 $$|x_k^n - x_k| \le \frac{\varepsilon}{2},$$
for all k and for $n > N$.
Question
I don't see how this has become a less than or equal to expression as opposed to the original less than expression? Here are my detailed workings:
For $n, m > N$ we have
$
\begin{align}
|x_k^n - x_k^m| & < \frac{\varepsilon}{2} \\
\lim_{m \to \infty} |x_k^n - x_k^m| & < \lim_{m \to \infty} \frac{\varepsilon}{2} \\
|x_k^n - \lim_{m \to \infty} x_k^m| & < \frac{\varepsilon}{2} \\
|x_k^n - x_k| & < \frac{\varepsilon}{2} \\
\end{align}
$
Am I missing something or is the author incorrect? Where in my workings have I make a mistake if I am indeed incorrect?

A: The author is correct. Sadly, strict inequalities are not conserved when taking the limit. They become weak inequalities in general.
Consider a simple example: the sequence $(a_n)_{n\geq 1}$ defined by $a_n = \frac{1}{n}$. Clearly, we have $a_n > 0$ for all $n\geq 1$. Yet, taking the limit,
$$
\lim_{n\to\infty} a_n = 0
$$
so the strict inequality "dies."
You can see it happen in related occurrences, maybe simpler to understand — for instance with the supremum of a set. The supremum of $S=[0,1)$ is $1$, even though every element $s\in S$ is strictly smaller than $1$. This is exactly the same phenomenon: if your sequence has elements  getting arbitrarily "close to making the strict inequality tight," then the limit cannot satisfy the strict inequality as well. Otherwise, there would still be elements of the sequence staying bounded away from the limit ("close to" the RHS of the inequality).


text:
Q: A decreasing sequence of Lebesgue measureable sets I am trying to find an example of a decreasing sequence $\{E_n\}$ of Lebesgue measurable sets such that $m(\bigcap ^\infty_{n=1} E_n)\neq \lim _{n\to\infty} m(E_n)$.
I feel like whether the measure of the set is finite or infinite matters.
I have no idea....
I would really appreciate it if you could help me.
Thank you

A: Let $E_n = [n,+\infty).$ Then $\bigcap_{n=1}^\infty E_n = \varnothing,$ which has measure $0,$ and $\lim\limits_{n\to\infty} m\left(\bigcap\limits_{n=1}^\infty E_n\right) = +\infty.$
Now suppose instead $E_n$ are some other sets and one of $E_n$ has finite measure. No generality is lost by assuming it's $E_1.$ Now let
$$
A_n = E_n \smallsetminus \bigcap_{m=n+1}^\infty.
$$
Then
\begin{align}
& +\infty>m(E_n) \\[8pt]
= {} & m\left(A_n \cup A_{n+1} \cup A_{n+2} \cup \cdots\cup \bigcap_{m=1}^\infty E_m\right) \\[8pt]
= {} & m(A_n) + m(A_2) + m(A_3) + \cdots + m\left( \bigcap_{m=1}^\infty E_m \right) \\[8pt]
\to {} & \bigcap_{m=1}^\infty E_m \text{ as } n\to\infty \text{ since the series converges.}
\end{align}

A: It is well known that measures are continuous from below/above with respect to (increasing unions)/ (decreasing intersections) of measurable sets. Formally, you can show that if $E_{n+1}\subseteq E_n$ and at least one $E_k$ has finite measure, then you'll get equality. So the only alternative is either some of your $E_n$ are not measurable, or if all of them have infinite measure.
E.g. if $m$ is Lebesgue measure, then take $E_n=(n,\infty)$, so that $E_\infty=\{\emptyset\}$.


text:
Q: Android custom XferMode / PorterDuff.Mode There are some predefined blending modes described here: https://developer.android.com/reference/android/graphics/PorterDuff.Mode.html
Is there a possibility to use some other custom modes? (for drawing various stuff on Canvas)
For example, I really need two more:

*

*Replace the alpha (it would be written as [Sa, Dc] if I understand right)

*Blend using destination alpha [Sa, Da * Sc + (1 - Da) * Dc] (here I don't really care about the result's alpha)

And it would be OK if it would require OpenGL ES 2+.
There's a [remotely] similar question here: Implementing different PorterDuff modes in android — but the answer seems to require using two bitmaps, and I want to stay free of temporary bitmaps, because they are… not free.


text:
Q: Vue.js Show value as price but keep it as int I have a vue component called "formatted-number", it receives an int value (1234) and changes it currently to a string ("12.34"), so that it is showed as an price (with "," or "." depending on the country) in a textfield.
I would like to keep the value as an int and just show it as a price, so that our users can edit the "string-price" but it also updates the int value in the background.
Do someone have a clue how I can manage this?
Here is the current code:
Vue.component('formattedNumber', {
    props: ['value', 'abs'],
    template: '<input type="text" :value="value" autocomplete="off" @blur="updateNumber($event.target.value)" ref="input">',
    mounted: function () {
        this.updateNumber(this.value / 100);
    },
    methods: {
        separators: function () {
            var comparer = new Intl.NumberFormat(navigator.language).format(10000 / 3);

            return {
                thousandSeparator: comparer[1],
                decimalSeparator: comparer[5]
            };
        },
        unformat: function (number) {
            var separators = this.separators();

            var result = number
                .toLocaleString(navigator.language)
                .replace(separators.thousandSeparator, '')
                .replace(/[^\d.,-]/g, '')
                .replace(separators.decimalSeparator, '.');

            return this.abs ? Math.abs(Number(result)) : this.Number(result);
        },
        updateNumber: function (value) {
            this.$emit('input', new Intl.NumberFormat(
                navigator.language,
                {minimumFractionDigits: 2, maximumFractionDigits: 2}).format(this.unformat(value)
            ));
        }
    }
});

A: Create a filter: docs.
Filters only change html output and leave the value intact.


text:
Q: HttpWebRequest.Timeout behaviour different in .Net / .Net CF? During some tests on multipart upload (using Ethernet) i have found something interesting:
I set a short (17sec) HttpWebRequest.Timeout and simulate a long upload using Thread.Sleep in the loop, where the byte-blocks are written to the server.
On a PC i get the timeout (RequestCanceled) but on .Net CF (Windows CE 5/6 Module) i dont get the timeout.
Does anyone has made the same observation ?

A: This is because the implementation of HttpWebRequest.Timeout in .Net CF does nothing:
// from C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v3.5\WindowsCE\System.dll
public override int Timeout
{
    get { }
    set { }
}


text:
Q: Show that $h \equiv 1 \pmod p$, where $h$ is the number of subgroups of order $p$ and $p$ divides the group order.
Let $G$ be a finite group and $p$ a prime number that divides the
  order of $G$. Let $h$ be the number of subgroups of $G$ of order $p$.
  Prove that there are $h(p-1)$ elements of order $p$ in $G$.
  Furthermore, prove $h \equiv 1 \pmod p$.

How should I solve the second part? This is what I did to prove the first:
Let $H$ be a subgroup of $G$ of order $p$. Because the order of an element in $H$ must divide the order of the group, its order must be $1$ or $p$. Since only the identity element has order $1$, the remaining $p-1$ elements have order $p$.
Assume that an element $x$ of order $p$ is contained in two subgroups $H_1$ and $H_2$. Then $x$ is a generator of both $H_1$ and $H_2$, so $\langle x \rangle = H_1 = H_2$, so an element of order $p$ is in only one such group.
So there are at least $h(p-1)$ elements of order $p$ in $G$. Assume there is an element $z$ of order $p$ which is not contained in any of the $h$ subgroups of order $p$. But we know that $\langle x \rangle$ is a subgroup of $G$ of order $p$. So all elements of order $p$ must be in one of those $h$ subgroups. Therefor, there are exactly $h(p-1)$ elements of order $p$ in $G$.
Now, how do I prove that $h \equiv 1 \pmod p$? This question is in a chapter about group actions, so that should maybe help. I'm assuming that I have to use the previously proven fact. And something that has to do with group actions. However, I'm not quite used to that concept and when it is useful to apply (more importantly, how to apply it). Could someone also explain to me its importance (especially in the case of this question)?
Thanks in advance.


text:
Q: Image caching issue by using files in ASP.NET I am facing a problem with Image caching by using files in ASP.NET. My detailed solution is:

*

*For 1st request: I check the image file not exists and write the image file into hard disk. After that returns the url of the file to the browser

*For later requests: the function just returns the url of the file to the browser
My problem is: sometimes with 1st requests, the browser can not get the image data from the url and cause the 404 - File Not Found error. I think it might because of the file is written but not ready for retrieving from browsers, but in the code I am using both "using statement" and "Dispose method" for bitmap & graphic objects to ensure everything are ready for accessing from browsers.
In more details, I am using the similar solution as in NopCommerce:
lock (s_lock) { ...........
 using (var stream = new MemoryStream(LoadPictureBinary(picture))) {
  using(var b = new Bitmap(stream)){
   using(var newBitMap = new Bitmap(newSize.Width, newSize.Height)){
    .......................
    newBitMap.Save(
        Path.Combine(this.LocalThumbImagePath, localFilename),  ici, ep);
   }
  }
 }
} // end lock

return url;

More information: you can check the full code at http://nopcommerce.codeplex.com/SourceControl/changeset/view/9125b9a7fafe#src%2fLibraries%2fNop.Services%2fMedia%2fPictureService.cs (please search the GetPictureUrl() function)

A: This is a case that I have see when multi-request happens together for the same image.
For this case the lock is not enough, you need to use mutex to lock this procedure for all threads and all request together.
So what I suggest is to change the lock, with mutex and use the image name, or a code of the image as name for the mutex to not lock anything and any image that is going to made but only the one that is defined by the name on the mutex. So change the lock with mutex, and then see if this problem still exist.
one tip: The mutex name have some limitations on the size and the characters. If you use the image file name as the name for the mutex be sure that is accepted by mutex.

A: Move check for file existence to be under the same s_lock as file creation. Should solve the problem with partially completed file (if it is the problem).
If fixed - use @Aristos suggestion to replace lock (Monitor) with named Mutext to scope locking down to individual files (if you site is expected to have heavy load).


text:
Q: CakePHP redirecting from one controller to another controller In cakephp folder, I have one controller SystemsController in one file(Admin) and another controller called UserController out of the admin file. how to redirect from SystemController to UserController?

A: If you are using CakePHP 3 you can set redirect after POST submit like this:
return $this->redirect(
            ['controller' => 'Orders', 'action' => 'thanks']
        );

If you are using Admin (or another) prefix just add before controller 'prefix' => 'Admin'
If you want to redirect user after click on some button, use HtmlHelper
$this->Html->link('Magic Button', ['controller' => 'YourController', 'action' => 'YourAction'];

And eventually set prefix.
More:
Controllers - Redirecting to Other Pages
Html Helper - Create Links
Request & Response Objects - Request Parameters


text:
Q: python pygogo throws error, no module named builtins I am using python and pygogo over raspberry pi 3 b, for error loggin.
After executing python program I am getting an error
pygogo no module named builtins

A: Installing future module worked for me.
sudo pip install future


text:
Q: Turning datagrid values to a datatable I have a datagrid that I want to turn into a datatable on a button click. I had thought the way you convert a grid to a table was below but when I run it I get that the table is null. Have no idea what I am doing wrong.
Dim dt = DirectCast(dtgrid.DataSource, DataTable)

A: I found my answer. It was that I was not posting the checkbox values back into the dataset.


text:
Q: How do I randomize an array full of strings? C++ I searched and found some for randomizing numbers, but I don't think it applies for strings....For example I have a list like this in an array:
string restaurants[] = {"Texas Roadhouse,","On The Border,","Olive Garden,","Panda       Express,","Cracker Barrel,","IHOP,","Panda Express,","Pei Wei"};

How would I randomize this or just swap them all around and jumble them up?

A: Don't reinvent the wheel if you don't have to.
std::random_shuffle(std::begin(restaurants), std::end(restaurants));

In C++03, without implementing your own begin and end:
std::random_shuffle(restaurants, restaurants + sizeof restaurants / sizeof restaurants[0]);

Be aware that unless you use something such as std::vector, passing it into a function to do this not by reference will need to use the latter with an additional size argument.

A: you could do like
 #include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

int main ()
{
  static string numbers[] =  {"Texas Roadhouse,","On The Border,","Olive Garden,","Panda       Express,","Cracker Barrel,","IHOP,","Panda Express,","Pei Wei"};
  srand(time(0));
  int rand_index = rand() % 10;
  cout << numbers[rand_index] << endl;

  string input;
  getline(cin,input);
  cout << (((input=="even")==(rand_index+1)%2==0) ? "Right." : "Wrong.") << endl;
}

A: Just an alternative for fun (sort by random) :
std::sort(restaurants, restaurants + sizeof(restaurants) / sizeof(std::string), [](int x, int y) -> bool { return rand() % 100 >= 50; });


text:
Q: Download ContentDocument in Community redirect to maintenance site I'm trying to download a ContentDocument from community, here is the url:
String downloadUrl = Url.getSalesforceBaseUrl().toExternalForm() + '/sfc/servlet.shepherd/document/download/' + ContentDocumentId + '?operationContext=S1'

But every time I press the download's button, I'm redirected to the maintenance page...

A: It's because, Salesforce files aren't hosted on your salesforce domain, instead if you download your file and check the source it will show something like,
https://<your-instance>-dev-ed--c.documentforce.com/sfc/servlet.shepherd/version/download/documentId?operationContext=S1

So either you need to trim down the URL like,
String documentId = Cd.ContentDocumentId;
String baseURL = URL.getSalesforceBaseURL().toExternalForm(). split ('-ed.')[0];
basURL+='c.documentforce.com/sfc/servlet.shepherd/version/download/'+documentId+'?operationContext=S1';

which you can try but i wouldn't recommend. Since their is a dedicated SObject to handle file URL's, the ContentDistribution.
Though, it isn't created automatically like ContentDocument when ContentVersion is created, instead either you create it manually or when the user clicks 'Public URL' under salesforce files.
So additionally you need to create ContentDistribution for your files if they're being shared publically.

A: After some research and attempts I found the solution. Here is the code I used:
String UrlDownload = '/' + yourCommunityName + '/sfc/servlet.shepherd/document/download/' + contentDocumentId;


text:
Q: How do I define NSLayoutConstraint for a right alignment within a stack view? I am try to align an icon, some text, and a result within two stack views.
The first stack view is vertical and contains X horizontal stack views. Each of the horizontal stack views contains a UIImageView and two UILabels.
While the UIImageView and the first UILabel should be aligned to the left, the last UILabel should align on the right side of the stack view.
The whole UI is generated in code, in this case C# but I don't think it is hard to convert Swift code to C#. After reading a bit about iOS UI, I think I can solve this with NSLayoutConstraint, but I don't know how to use it — my current attempts always end in an exception.
This is how I am setting my constraint currently:
dataStack.Constraints.Append(NSLayoutConstraint.Create(percentageLabel, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, dataStack, NSLayoutAttribute.Leading, 1, 0));

Edit:
This is how it currently look like: https://puu.sh/Ddlrx/ab36d7c864.png but the percentage should be right aligned so each line ends at the same place.
And this is my current code which generates the UI: https://pastebin.com/pvMTGx0U
The constraints in the current code are a 1:1 copy of a working implementation in XCode Designer... I don't get it why it won't work this way in my widget. :/

A: Add a vertical Stackview with
stackView.alignment = .fill
stackView.distribution = .fillEqually
stackView.spacing = 2

Add top, leading, trailing, bottom constraints. Don't add height constraint. It will be calculated from subviews.
Next add n Horizontal stackviews as arranged subviews with
stackView.alignment = .center
stackView.distribution = .fillProportionally
stavkView.spacing = 2

Now add an Image view and two labels in each horizontal stackview.
Don't add leading, trailing, top, bottom constraints to these image view and labels.
Add width and height constraint for each image view
Assign equal width to lbl1 and lbl2
lbl1.widthAnchor.constraint(equalTo: lbl2.widthAnchor).isActive = true

Change lbl2's textAlignemnt to .right
lbl2.textAlignment = .right

Now you'll get this

OR
Instead of adding equal with to lbl1 and lbl2
set content hugging priority for lbl2
lbl2.setContentHuggingPriority(.defaultHigh, for: .horizontal)

Now lbl2's width will shrink to fit its text. lbl1 will take remaining width


text:
Q: probability of repeating values in a hashmap Suppose you have a hashmap where you store values. The hashmap is of size m and supports chaining. The hash function is simple uniform hashing assumption. I understand that the average length of a chain is the load factor. But if you were storing values from a set into the hashmap, what is the probability that when you are storing value x, there is another value x already in the hashmap?
I know, that if x already exists, it would map to the same linked list in the hashmap. But how do you go further?

A: If a size of hash table is $m$, a size of your set is $n$, and you are picking the numbers from this set by uniform distribution, this is a probability that one random element $z$, which is in $N$, is in $M$, where $M \subseteq M$. This is sure $m \over n$.
If you want to know a conditional probability, where you know already $x$ is in a certain chain, you need to determine the probability that the size of a full class of $x$ is equal to some $|class|$, when you know already, $|class| \ge |chain|$. $P(|class| = n ~\backslash~ |class| \ge |chain|) = {P(|class| = n) \over P(|class| \ge |chain|)}$, if $|class| \ge |chain|$, and $0$ if $|class| < |chain|$. Note that |class| and |chain| are here constants. The full probability that $x$ is in chain already is $$\sum_{C = |chain|}^{n}{P(x~in~chain~\backslash~|class|=C)P(|class|=C ~\backslash~ |class| \ge |chain|)} = \\ =\sum_{C = |chain|}^{n}({|chain|\over C}\cdot{P(|class| = C) \over P(|class| \ge |chain|)}) ~=~
\sum_{C = |chain|}^{n}({|chain|\over C}\cdot{{C_{n}^{C}p^{C}(1-p)^{n-C}} \over P(|class| \ge |chain|)}) ~=\\
=~ ({|chain| \over P(|class| \ge |chain|)}) \cdot {\sum_{C = |chain|}^{n} {{C_{n}^{C}p^{C}(1-p)^{n-C}} \over {C}}}$$
Here $|class|$ is already a binomial random variable, $|chain|$ is a constant you know, and $1 \over p$ is a number of classes. This function can be sure approximated.


text:
Q: JSON Data validation in python I'm new to the world of Python. My question is what is the best way (if any way is already done without doing it by hand) to perform validations of object attributes in Python.
The task is that when I receive data coming to me in a JSON from the client (for example an HTTP request to create an article), I want to check that this data is good (It is not a string when it should be an int (age), etc).
I have an object, and the object has the field age, i don't want to do this always. I want somethig that do it for me.
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

I've looked for several things but I can't find a good module or library to perform this important validation task. If anyone knows one with good documentation or shows an example, it would be appreciated.

A: Python has built-in JSON module to work with JSON data, read more here. As well you can try the jsonschema validator module.

A: Make your own validator func. This is just an example how it works.
data = {'age': 18, 'hair': 'brown'}      # Create dict variable
def validator(value):                    # Create a function that receives argument
    if isinstance(value, int):           # Check the type of passed argument
        print('It is a number.')         # Prints if it is a number
    else:
        raise ValueError('It is a %s'%type(value))  # If not number Error is raised

validator(data['age'])  #  Test 1
validator(data['hair'])  # Test 2