text:
Q: A few soft questions about elementary counting methods I am reading a combinatorics textbook for my own amusement and I have a few questions. I apologize for the wall of text below.
Suppose we want to use the framework of $12$-fold way to solve the two problems below:

*

*What's the number of $5$-committees made up of $2$ men and $3$ women given that there are $7$ women and $5$ men?

*What's the number of Two Pair hands in poker?
Solutions:

*

*We have two functions $f: \{\text{men}\} \to \{\text{man$_1$, man$_2$}\}$ and $g: \{\text{women}\} \to \{\text{woman$_1$, woman$_2$, woman$_3$}\}$. Assuming the elements in the domain of $f$ are identical and the elements in the domain of $g$ are identical, by $12$-fold way we have the numbers $\binom{5}{2}$ and $\binom 73$. Then by product principle the answer is $\binom{5}{2}\binom 73.$

*I'll try to do this problem by analogy with the problem above so that men correspond to ranks and women - to suits or vice versa. Let $R$ stand for the set of $13$ ranks and $S$ be the set of $4$ suits. We have five functions: $f: R \to \{\text{rank$_{1a}$, rank$_{2a}$}\}, \ g: R - \{\text{two different ranks}\} \to \{\text{rank$_{1b}$}\},  \ h: S \to \{\text{suit$_{1a}$, man$_{2a}$}\}, j: S \to \{\text{suit$_{1b}$, man$_{2b}$}\}, k: S \to \{\text{suit$_{1c}$}\}$
Assuming the ranks and suits are identical, by $12$-fold way we get the numbers $\binom{13}{2}$, two $ \binom 42$s, $\binom{11}{1}$ and $\binom 41.$ Then our answer must be $\binom{13}{2} \binom 42^2\binom{11}{1}\binom 41$  by product rule.
What's confusing:

*

*According to $12$-fold way, the set $R$ must contain identical elements and the set $S$ must contain identical elements, but the ranks QUEEN and ACE are not the same. Similarly, DIAMONDS and HEARTS are not the same suit. So what's going on here?

*The second problem is done by analogy with the first one, but the problem (?) is that a rank and a suit are stuck on the same card which is not the case for men and women. Given how a slight change in a counting  problem can change the final answer by a factor of a gigantic number, I think some care must be taken :)

*All I did in solving the problems is to force data into the $12$-fold framework or vice versa. It's just post-hoc reasoning as I knew the answer to the problems to begin with. I don't think the very first person who counted poker hands (or anyone) thought like that. Heck, I don't think that's how any problem is solved.

*Solutions to many such counting problems seem very ad-hock especially given that human languages like English can be very ambiguous. This makes me suspect there must be better (say, numerical, algorithmic or whatever) methods for solving and checking counting problems.

My Questions:

*

*Are there any numerical or algorithmic methods for solving counting problems correctly every time? I can actually solve the problems in the textbooks I am reading, but I can't quite articulate and pin down the methods I am using in a very precise way like it's possible when proving theorems in, say, analysis. I hear whispers of generating functions, but I haven't read the chapter on that yet. Since I am studying this stuff on my own and for my own ends, I was wondering if I could simply dump these ad-hoc(?) methods of counting and concentrate on more powerful general techniques if they exist? Are generating functions that tool? If so, I could just get started reading the book "generatingfunctionology" right about now.

*If a combinatorist was asked to count the number of, say, full house hands using the $12$-fold way, how would they go about it? Is this even a correct question to ask? Also, can generating functions be used to count poker hands?
Thanks.

A: I cannot answer your broad questions, but I can tell you how to correctly apply the 12-fold way here.
For the first problem, you are not choosing a function $f:\{men\}\to \{man_1,man_2\}$. Choosing such a function would be equivalent to assigning each of of five men one of two labels, which is not equivalent to choosing a committee. Furthermore, you have specified that the domain elements are identical; this is not what we want, because the people should be distinct. Finally, for the $12$-fold way, you must specify whether the range elements are identical, and whether the function should be injective, surjective, or no restriction. You have not specified these conditions.
Here is the solution for the men. There are two spots in the committee, call them $s_1$ and $s_2$. Each spot in the committee must be filled by a man. Therefore, choosing a committee requires choosing a function $f$ which assigns a man to each spot, so a function $f:\{s_1,s_2\}\to\{m_1,m_2,m_3,m_4,m_5\}$. Now, we must decide three things about this function:

*

*Are the domain elements distinct? Is spot 1 different from spot 2? No. We are just choosing a committee, not a ranking of its members.

*Are the range elements distinct? Yes, people are distinct. It matters when you switch out one man for a different one.

*Must the function be either surjective or injective? The function must be injective. This is because we must choose two different men to go to the two spots.
Now, we have specified which version of the twelvefold way we want, and we can look up that the answer is indeed $\binom{5}2$.

For the poker problem, the functions would be

*

*$f:\{\text{pair}_1,\text{pair}_2\}\to \{\text{Ranks}\}$ [choose the two ranks which appear as pairs. The pairs are identical, since order does not matter within the hand, but the ranks are distinct.]

*$g:\{\text{card}_1,\text{card}_2\}\to \{\text{Suits}\}$ [for the lower chosen rank, choose the two suits of the cards. The cards are identical (order does not matter), the suits are distinct.]

*$h$ is the same as $g$, but for the other suit.

*$k:\{\text{card}_1\}\to \{\text{the set of $44$ cards not appearing in the two chosen ranks}\}$, with the cards distinct. Here, we are choosing the last card which appears. This step does not need to be broken down into two steps of choosing a rank and suit.


text:
Q: How would you implement something like a 2-way map? I want some sort of container that gives me a 2-way map between integers and strings.
I give it an int, and it gives me the string associated with it.
I give it the string, and it gives me the int associated with it .
How would you implement such a thing?

A: You need 2 maps for that and as you add/remove to those maps, make sure they are in sync. I don't know how to do it with only one container.

A: I would create a class with two maps:
class BiMap {

    void insert( string const & s, int i ) {
        stringToInt[ s ] = i;
        intToString[ i ] = s;
    }

    int find( string const & s ) const {
        // use stringToInt[ s ];
    }

    string find( int const & i ) const {
        // use intToString[ i ];
    }

    map< string, int >   stringToInt;
    map< int, string >   intToString;
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extracting item from a list stored as string in pandas dataframe I have the following pandas dataframe
data = [{'a': 1, 'b': '[2,3,4,5,6' }, {'a': 10, 'b': '[54,3,40,5'}]
test = pd.DataFrame(data)
display(test)

    a     b
0   1   [2,3,4,5,6
1   10  [54,3,40,5

I want to list the number in column b, but as the list has the [ only at the beginning, doesnt allow me to create the list, I'm trying to remove the "[" so I can extract the numbers, but I keep getting errors, what I'm doing wrong?
This is how the numbers are stored
test.iloc[1,1]
'[54,3,40,5'

And this is what I've tried to remove the "[".
test.iloc[0,1].replace("[",'', regex=True).to_list()

test.iloc[0,1].str.replace("[\]\[]", "")

What i want to achieve is to have b as a proper list so i can apply other functions.
    a     b
0   1   [2,3,4,5,6]
1   10  [54,3,40,5]

A: To make your 'b' column a list you can first delete the open squared bracket at the beginning, and then use the split method on each element of your 'b' column
test['b'] = test['b'].str.replace('[', '').map(lambda x: x.split(','))

test
#     a            b
# 0   1  [2, 3, 4, 5, 6]
# 1  10  [54, 3, 40, 5]

A: try it:
def func(col):
  return eval(col+']')

test['b'] = test['b'].apply(func)

A: import pandas as pd
data = [{'a': 1, 'b': '[2,3,4,5,6' }, {'a': 10, 'b': '[54,3,40,5'}]
test = pd.DataFrame(data)
print(test['b'][0][1:])
for i in range(len(test['b'])):
    test['b'][i] = test['b'][i][1:]


text:
Q: Relationships in a Tree (Haskell) Binary trees with values in the leaves and nodes are defined by:
   data Tree a = Leaf a
                | Node a (Tree a) (Tree a)
     deriving (Eq, Show)

For example,
         10
        /  \
       /    \
      8      2
     / \    / \
    3   5  2   0

exTree :: Tree Int
exTree = N 10 (N 8 (H 3) (H 5))
               (N 2 (H 2) (H 0))

Well, I need a function called RelationshipBinaryTree, which generates a list of tuples, whose first component is an x and its second the father. In this tree,
relationshipBinaryTree :: Tree a -> [(a,a)]
relationshipBinaryTree exTree =  [(10,8),(8,3),(8,5),(10,2),(2,2),(2,0)]

Also, I need to define it in the Data.Tree hackage (https://hackage.haskell.org/package/containers-0.5.11.0/docs/Data-Tree.html)
I hope you can help me because I don't understand trees and graphs very well.
I have tried this
relationshipBinaryTree :: Tree a -> [(a,a)]
 relationshipBinaryTree (L _) = []
 relationshipBinaryTree (N _ (Tree i) (Tree d)) = relationshipBinaryTree (N _) ++ relationshipBinaryTree (Tree i) ++ relationshipBinaryTree (Tree d)

A: You want to use Data.Tree, but Data.Tree isn't even about binary trees, but about multi way trees (a.k.a. rose trees). However, if you had a function value :: Tree a -> a, then of course you could map it to the children of a rose tree and combine the result with the value.
Now, there exists a function that does that in Data.Tree, it's called rootLabel. And there is another function to geht the children of a node, it's called subForest.
That comes from the definition of Tree in Data.Tree:
Node
   rootLabel :: a           -- label value
   subForest :: Forest a    -- zero or more child trees

So we could define for rose trees:
fatherChild :: Tree a -> [(a, a)]
fatherChild t = map mkPair children ++ concatMap fatherChild children
   where mkPair child = (rootLabel t, child)
         children     = subForest t

Example:
fatherChild (Node 3 [Node 8 [], Node 4 []])
> [(3,8),(3,4)]

Your example:
fatherChild (Node 10 [Node 8 [Node 3 [], Node 5 []], Node 2 [Node 2 [], Node 0 []]])
> [(10,8),(10,2),(8,3),(8,5),(2,2),(2,0)]

Now, this doesn't answer your question about binary trees, but I would like to leave that to you as an exercise, because it will be very similar (except if you get stuck). (And please don't use rose trees as binary trees, because there is no type safety to ensure that there are always two children.)

A: A simple way to do it is by getting the value with an auxiliary function and then do the recursion:
data Tree a = Leaf a
              | Node a (Tree a) (Tree a) deriving (Eq, Show)

exTree :: Tree Int
exTree = Node 10 t1 t2
t1 = Node 8 (Leaf 3) (Leaf 5)
t2 = Node 2 (Leaf 2) (Leaf 0)

relationshipBinaryTree :: Tree a -> [(a,a)]
relationshipBinaryTree (Leaf _) = []
relationshipBinaryTree (Node v i d) = [(v, getVal i), (v, getVal d)] ++ relationshipBinaryTree i ++ relationshipBinaryTree d

getVal (Node v _ _) = v
getVal (Leaf v) = v

   relationshipBinaryTree exTree
=> [(10,8),(10,2),(8,3),(8,5),(2,2),(2,0)]


text:
Q: Comparar cadenas en C ejercicio tengo el siguiente ejercicio:
Implementar una función que se le pase como entrada dos cadenas de caracteres. La función deberá devolver un 1 si las cadenas son iguales, sino devolverá un 0 (no puede hacer uso de funciones especificas de C).
Esto es lo que intenté:
#include<stdio.h>

 char cadenas (char cad1[100],char cad2[100] ) {

int i;

 for (i=0;i<100;i++){

    printf ("\nintroduzca el caracter %s de la cadena");
        scanf  ("%s", cad1[i]);

}

 for (i=0;i<100;i++) {

   printf ("\nintroduzca el caracter %s de la cadena");
    scanf ("%s",cad2[i]);

}

 if (cad1==cad2) {

   printf ("las cadenas %s son iguales");

      return 1;

Lo que pasa es que al compilarlo me salen varios warnings, no sé qué errores podría tener el código:
ejexamen.c: In function 'cadenas':
ejexamen.c:22:11: warning: format '%s' expects a matching 'char *' argument [-Wformat=]
   printf ("\nintroduzca el caracter %s de la cadena");
           ^
ejexamen.c:23:12: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]
    scanf  ("%s", cad1[i]);
            ^
ejexamen.c:30:12: warning: format '%s' expects a matching 'char *' argument [-Wformat=]
    printf ("\nintroduzca el caracter %s de la cadena");
            ^
ejexamen.c:31:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]
   scanf ("%s",cad2[i]);
          ^
ejexamen.c:38:12: warning: format '%s' expects a matching 'char *' argument [-Wformat=]
    printf ("las cadenas %s son iguales");
            ^
ejexamen.c:42:8: error: expected '}' before 'else'
        else {
        ^

Gracias

A: Centrandome tan solo en el código, sin mirar los mensajes:
printf ("\nintroduzca el caracter %s de la cadena");

Indicas que quieres mostrar una cadena (`%s'), pero no la pasas como argumento de la función. Deberia ser
printf( "\nintroduzca el caracter %d de la cadena", i );

para mostrar el índice (que creo que es lo que quieres).
scanf  ("%s", cad1[i]);

Ahí, pides una cadena, pero le pasas como argumento un caracter. Debría de ser:
scanf( "%c", &cad1[i] );

y te saldrá un comportamiento curioso al ejecutarlo, pero lo dejo para que lo descubras tú ;-)
Todo lo anterior te vuelve a pasar otra vez, en el siguiente trozo de código.
Por último, haces
if (cad1==cad2)

Eso te va a dar false siempre. Lo que estas haciendo es comparar punteros a cadenas, que no es lo que tu pretendes.
Para comparar el contenido de las cadenas, lo mas fácil que se me ocurre es
while( ( *cad1 && *cad2 ) && ( *cad1 == *cad2 ) ) {
  ++cad1;
  ++cad2;
}

if( *cad1 == *cad2 ) {
  // Son iguales.
  ...
} else {
  // Son distintas.
  ...
}

Y por último, yo cambiaria la definición de la función por algo así:
int cadenas( char *cad1, char *cad2 ) {

principalemente, por claridad. No afecta realmente.
Ah, se me olvidaba. Te faltan 2 } al final de tu código. Supongo que no lo has copiado/pegado bien.


text:
Q: Scraping literal class description in Python 3 using lxml xpath I have a small question regarding my webscraper.
I am trying to scrape the rating per review of a website on trustpilot.
Let's take for instance https://www.trustpilot.com/review/www.amazon.com
Even though i managed to scrape the review content and title, i can't seem to get a hold of the amount of stars given (1 to 5).
If i look at the html code, it doesn't show 'text' so i can assign the specific class to it (like i did with content and title).
However, the amount of stars given is mentioned in the class description itself - a 5-star ratings has the element : div class=''star-rating count-5 size-medium clearfix''. a 2-star rating the following: iv class=''star-rating count-2 size-medium clearfix''
This class is located within: div class="review-info clearfix"
Does anybody know how I can scrape the literal class, or only the count-x element per review?

A: The class can be easily extracted using BeautifulSoup
from bs4 import BeautifulSoup
import requests
c = requests.get('https://www.trustpilot.com/review/www.amazon.com').content
soup = BeautifulSoup(c, 'html.parser')
reviews = soup.find_all('div', {'class': 'review-stack'})
for review in reviews[:5]:
    print(review.find('div', {'class': 'star-rating'})['class'])

This prints out the following lists:
['star-rating', 'count-5', 'size-medium', 'clearfix']
['star-rating', 'count-5', 'size-medium', 'clearfix']
['star-rating', 'count-1', 'size-medium', 'clearfix']
['star-rating', 'count-4', 'size-medium', 'clearfix']
['star-rating', 'count-4', 'size-medium', 'clearfix']

Now you just need to select the right element of the list and you have your rating.
Using lxml:
from lxml import html
import requests
page = requests.get('https://www.trustpilot.com/review/www.amazon.com')
tree = html.fromstring(page.content)

reviews = tree.xpath("//div[@class='review-info clearfix']/div[1]")
for rev in reviews:
    print(rev.get('class'))


text:
Q: Latex: use Pirat font for the King's fig instead of Skaknew King's fig I'm using chessfss together with xskak package to make game's annotation, my favourite chess font is skaknew, but the figfont for the King look a bit complicated.
Is there anyway to use Pirat font for the King fig?
Thanks
p/s: I added a picture which I took from quality chess's book. The King's fig look simple very close to pirat font, so I came up with the idea.
[![\documentclass\[parskip\]{scrartcl}
\usepackage\[LSF,T1\]{fontenc}
\usepackage{bookman}
\pagestyle{empty}

\usepackage{xskak}
\usepackage{fmtcount}
\usepackage{latexsym}
\usepackage\[utf8\]{inputenc}

\pdfmapfile{=chess-enpassant.map}
\setchessboard{
    boardfontfamily=skaknew,
}
\setfigfontfamily{skaknew}

\newcommand\piratking{\makealetter\fontfamily{pirat}\selectfont\cfss@symking}
\renewcommand\symking\{{piratking}}

\begin{document}
\newchessgame
\mainline{1.  e4  e5 2.Ke2}
\chessboard
\end{document}]

A: You can redefine the king with
\makeatletter
\renewcommand*\cfss@king@@LSB{{\fontencoding{LSF}\fontfamily{pirat}\selectfont K}}
\makeatother

But the result is rather awful. Compared to the other pieces the king is to narrow, the line width differ, the style is different, the placement too.


text:
Q: separate .txt file to csv file trying to convert txt file to csv but doesnt work
orginal text:
 استقالة #رئيس_القضاء #السودان  OBJ
أهنئ الدكتور أحمد جمال الدين، مناسبة صدور أولى روايته   POS
يستقوى بامريكا مرةاخرى و يرسل عصام العريان الي واشنطن شئ NEG
#انتخبوا_العرص #انتخبوا_البرص #مرسى_رئيسى  #_ #__ö  NEUTRAL

expected result :
text                                                             value
استقالة #رئيس_القضاء #السودان                                   OBJ
أهنئ الدكتور أحمد جمال الدين، مناسبة صدور أولى روايته         POS
يستقوى بامريكا مرةاخرى و يرسل عصام العريان الي واشنطن شئ      NEG
#انتخبوا_العرص #انتخبوا_البرص #مرسى_رئيسى  #_ #__ö             NEUTRAL

i have tried this but its doesn't work for space and comma constrain
awk 'BEGIN{print "text,value"}{print $1","$2"}' ifile.txt

also i have tired this with python but it doesn't contain all of them
import pandas as pd
df = pd.read_fwf('log.txt')
df.to_csv('log.csv')

A: Your request is unclear, how do you want to format the last field.
I created a script that align the last line on column 60.
script.awk
BEGIN {printf("text%61s\n","value")}  # formatted printing heading line
{
    lastField = $NF;               # store current last field into var
    $NF = "";                      # remove last field from line
    alignLen =  60 - length() + length(lastField); # compute last field alignment
    alignFormat = "%s%"alignLen"s\n";   # create printf format for computed alignment
    printf(alignFormat, $0, lastField); # format print current line and last field
}

run script.awk
awk -f script.awk ifile.txt

output
text                                                        value
استقالة #رئيس_القضاء #السودان                               OBJ
أهنئ الدكتور أحمد جمال الدين، مناسبة صدور أولى روايته       POS
يستقوى بامريكا مرةاخرى و يرسل عصام العريان الي واشنطن شئ    NEG
#انتخبوا_العرص #انتخبوا_البرص #مرسى_رئيسى #_ #__ö           NEUTRAL


text:
Q: Edit Text/HTML Module in Dotnetnuke adds text/P tags Is there any way to prevent the Text/HTML Module in DNN from adding tags (like an initial  when you edit in source view and switch back to display?)

A: Sigh. Apparently a known issue with early versions of the FCKEditor. Some js tweaks available.


text:
Q: Send a mobile number from default android dialer to my application I have a application for calling an API for phone call,
When a user dials a number from default dialer of android phone, the number should be copied into the second app(free call twilio),shown in picture.

Here is what I tried, but no luck.
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.CALL_BUTTON" />

<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CALL_PRIVILEGED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="tel" />
</intent-filter>
</activity>

Can anyone help please? :-)

A: please use below code
Register a BroadcastReceiver like this in Manifest file:
    <!-- DIAL Receiver -->
    <receiver
        android:exported="true"
        android:name="receivers.DialBroadcastReceiver" >
        <intent-filter >
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
    </receiver>

You need Permission for NEW_OUTGOING_CALL :
<!-- OUTGOING CALL PERMISSION-->
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

public class DialBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Log.v("DileBroadCastReceiver","In onReceive()");

    if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
         String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

         Log.v("DialBroadcast Receiver","Number is: "+number);

    }

  }
}

A: I think you forgot to add intent-filter in your mainActivty like below
       <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>

also add your existing intent-filter as well. Gud luck

A: It can be possible after searching a lot in google. Finally I got an answer I am sharing it for others.
It can be possible by adding following intent filter in manifest file.
  <intent-filter>
        <action android:name="android.intent.action.CALL_BUTTON" />
        <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>

A: create a broadcast reciever with android.intent.action.NEW_OUTGOING_CALL and then call
 dialledNumber=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
This will give you outgoing number
try this.it might help
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);


text:
Q: Где ошибка в функции? Не работает, если задать в параметре массив. Почему выводит NaN?

function formatDate(date) {
 var toString = {}.toString;
 if (toString.call(date) === '[object Date]') {
  var dd = date.getDate();
    if (dd < 10) dd = '0' + dd;

    var mm = date.getMonth() + 1;
    if (mm < 10) mm = '0' + mm;

    var yy = date.getFullYear() % 100;
    if (yy < 10) yy = '0' + yy;

    return dd + '.' + mm + '.' + yy;
 }
 else if (typeof date === 'string') {
  date = date.split('-').join();
  return formatDate(new Date(date));
 }
 else if (Array.isArray(date)) {
  date = date.join();
  return formatDate(new Date(date));
 }
 else {
  date = new Date(date*1000);
  date = date.getFullYear() + ', ' + date.getMonth() + ', ' + date.getDate();
  return formatDate(new Date(date));
 }
}

console.log( formatDate('2011-10-02') ); // 02.10.11
console.log( formatDate(1234567890) ); // 14.02.09
console.log( formatDate([2014, 0, 1]) ); // 01.01.14
console.log( formatDate(new Date(2014, 0, 1)) ); // 01.01.14

A: Upd: прошу прощения, просто формат надо было поправить
console.log( formatDate([2014, 01, 01]) ); // 01.01.14

A: ну у тебя строка получается 2014,0,1, а это не валидный аргумент, наверно надо писать так:
if (Array.isArray(date)) {
    return formatDate(new Date(...date));
}

либо писать валидную строку для входа, как в случае с 2011-10-02


text:
Q: django Models getting user info trying to create a model that has an artist and song and lets you know what user name typed it in.
so far I have in my models.py
from django.contrib.auth.models import User

class Song(models.Model):

uesrname = models.ForeignKey(User,on_delete=models.CASCADE)
artist = models.CharField(max_length=30)
song=models.CharField(max_length=30)

I added a form that works with user input data but the form lets me select one of all exciting Users and input artist, song
forms.py
class NewSong(forms.ModelForm):
    class Meta:
        model=Song
        exclude = ['username']

how can I change it so I will have only my own loged in user in the form?

A: You can exclude username field as exclude = ['username'] on your forms.py file and set username to request.user on form's save method. For more information: selecting fields


text:
Q: Can VB extract interfaces from a class like C#? We have a large chunk of legacy code in VB that I want to unit test, so step one if building interfaces.  In C#, visual studio has the cool little Refactor -> Extract Interface function.  VB Doesn't, though?
Is there a good way to do this in VB?

A:
Extract Interface function. VB Doesn't, though?

Yes. Unfortunately, Microsoft Visual Studio does not support refactor functionality for VB.NET.
You can install third party tools such as ReSharper, though.
For more information, also have a look at this question on SO: Refactoring options in Visual Studio 2010 differ between C# and VB


text:
Q: Bootstrap 3: Thumbnail caption text wrapping to second line makes container height stretch The same question exists for Bootstrap 2 but was unanswered. Hopefully for Bootstrap 3 there will be someone up to the task :-).
Please note that there is also another problem. With lower screen resolutions the text is not only breaking the container shape, it also breaks out of the container.
Thanks in advance!
I have the following code:

PowerPoint

A: Workaround:
I resolved this in the following manner:
                                                                                1. Between each col-md-1 gave margin (bottom, left, right) of 20px.
2. Placed the caption outside of the container, below it and gave each caption another 10px bottom margin.
Now it all looks ok, however it would be nice to get other ideas for those cases where you don't have 20px around each thumbnail and you cannot put the caption below.


text:
Q: document term matrix using list of terms I am trying to build a document term matrix using preidentifed terms.  The corpus is identified in the variable cname and the file with the preidentified terms are read into the terms variable which is then converted into a list. When I run the code below I get an empty DTM. The code I am using below.  Any ideas on what I did wrong? Thank you!!!
tom
library(tm)
library(Rmpfr)
library(stm)

#Loading Documents
cname <- file.path("", "corpus", "goodsmoklss")
library(tm)
corp <- VCorpus(DirSource(cname))

#Transformations
docs<-tm_map(corp,tolower) #AllLowerCase
docs<-tm_map(corp,removeNumbers) #RemoveNumbers

#Remove Stopwords like is, was, the etc
docs<-tm_map(corp, removeWords, stopwords("english"))

#make Sure it is a PLainTextDocument
documents<-tm_map(docs,PlainTextDocument)

#read in list of preidentified terms
terms=read.delim("C:/corpus/TermList.csv", header=F, stringsAsFactor=F)
tokenizing.phrases <- c(terms)

library("RWeka")

phraseTokenizer <- function(x) {
  require(stringr)

  x <- as.character(x) # extract the plain text from TextDocument object
  x <- str_trim(x)
  if (is.na(x)) return("")

  phrase.hits <- str_detect(x, coll(tokenizing.phrases))

  if (any(phrase.hits)) {
    # only split once on the first hit, so we don't have to worry about    #multiple occurences of the same phrase
    split.phrase <- tokenizing.phrases[which(phrase.hits)[1]]
    #warning(paste("split phrase:", split.phrase))
    temp <- unlist(str_split(x, coll(split.phrase), 2))
    out <- c(phraseTokenizer(temp[1]), split.phrase, phraseTokenizer(temp[2]))
  } else {
    #out <- MC_tokenizer(x)
    out <- " "
  }

  # get rid of any extraneous empty strings, which can happen if a phrase occurs just before a punctuation
  out[out != ""]
}

dtm <- DocumentTermMatrix(documents, control = list(tokenize = phraseTokenizer))

A: I'm not that familiar with TM, but in the quanteda package you can simply subset or filter.  Here the same principle should apply. I think you should be able to build the DTM and then simply filter based on the vector of terms that your interested in. First make your DTM as above.
v <- ("your","terms","here")
to_filter <- colnames(dtm)

#then you can simply filter based on the vector
dtm2 <- dtm[,to_filter %in% v]

You might want to consider stemming both your dictionary and your corpus first. If the corpus has a lot of terms and documents memory could be an issue.


text:
Q: PostgreSQL crash recovery We are planning to use PostgreSQL in our application but are concerned about crash-safety and recovery.
I can't find any database crash recovery method or process in PostgreSQL. I know there must be something in PostgreSQL.
Advice? So if anyone can help me out to find  this then that would be great.

A: It sounds you are looking for Point In Time Recovery: http://www.postgresql.org/docs/current/static/continuous-archiving.html
The chapter about high availability might also be interesting for you: http://www.postgresql.org/docs/current/static/high-availability.html

A: Crash Safety
PostgreSQL is crash-safe within certain limits. It guarantees to always preserve committed data if the database system crashes or the host it's on reboots/loses power/crashes unexpectedly. That's what the D in ACID means - atomicity, consistency, isolation, durability.
The critical feature in PostgreSQL's crash safety is the write-ahead log (WAL). The documentation explains it much better than I ever could.
This crash safety is not a substitute for good backups.

*

*PostgreSQL cannot protect you against file system corruption or hard drive failure. The storage system it uses needs to be reliable.

*Hard drives and SSDs will fail, so RAID is necessary but not sufficient for protection. You need backups and/or replication to protect against multi-drive failures, file system corruption, etc.

*There are certain settings documented in PostgreSQL that weaken the crash-safety guarantees it makes. For example, if you set fsync=off you give PostgreSQL permission to destroy your data if it crashes in exchange for going a bit faster.

*PostgreSQL guarantees that it will not save uncommitted data, it will be lost if the system crashes before a transaction COMMITs. Statements not surrounded by BEGIN and COMMIT for this purpose commit when the statement returns.
There's more, but the short version is that Pg is crash-safe and durable, but you still need to look after the other layers in your infrastructure, which is why you need:
Backups
Don't just do a weekly pg_dump where you overwrite the same dump file over and over, that'll end in tears. Use more than one backup strategy, and keep historical backups not just a most recent backup.
For example, I keep both dumps and a continuous archiving/PITR replica. I keep daily pg_dumps for a week, then weekly dumps for a month and monthly dumps for a year to give me some timeline protection. For the PITR setup I refresh from a base backup every week; it's mostly there to give me the ability to recover to the nearest 5-minutes from any failure or catastrophic mistake. Nightly dumps won't help me recover the last 23 hours of data when I accidentally drop a table; PITR will.
There's lots more here:

*

*Pg manual - backup and restore

*Pg manual - streaming replication

*Pg manual - high availability

*Pg wiki - Backup category

*Pg wiki - high availability
Don't be one of the people who turns up on the Pg list saying "my hard drive crashed, how can I recover my database?". Be like this guy, who asked the question for fun because he had backups but was curious if his DB could be recovered. (Answer: probably not).
Repair or recovery of corrupt databases
If you're reading this because you found it in a search and you suspect you have a corrupt Pg database, read this before attempting any repair.
If by crash recovery you mean a repair tool to fix a damaged database, no, there isn't anything much. pg_resetxlog may save you from corrupt/lost transaction logs, but will probably corrupt your database in the process, so you usually need to dump and reload afterwards. There isn't any kind of fsck tool, nor is there anything like myisamchk because unlike MyISAM, Pg's tables are designed not to get corrupted as a routine part of normal operation. It'd actually be quite nice to have some sort of pg_dbcheck, but it would probably not be able to tell you much more than "Yup, there's some corruption here, go find a backup".
The database just doesn't get damaged in the first place unless:

*

*The underlying hardware fails

*The OS or file system has a bug

*PostgreSQL has a bug

*PostgreSQL is explicitly configured not to be durable

*The user did something silly like went around deleting things from the database directory

In all of these cases automated repair would be impractical anyway.
Keep good backups of any database, not just Pg. Don't rely on being able to repair corruption, because you probably won't be able to.


text:
Q: Prevent items from being collapsed in bootstrap 4 navbar toggle I have a bootstrap 4 navigation bar.In this navigation bar i have a font awesome icon-shopping cart that i don't want to toggle(to go in that 3 lines menu) when the page pass a max-width value(the default responsive navbar from bootstrap).I would like to remain near the menu bar.How can i do this?
PS:I will put three ! where the font awesome icon is to help you seeing it.
HTML:

English Park Cuisine
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

</button>

            Acasa(current)

                Meniu

                Pizza
                Paste
                Supe
                Ciorbe
                Desert

            Contact

0746117702

0742112452

0735212352

    !!!

            Login

            Register

A: You need to group the non-collapsible items in a single div, and then use the spacing and order utilities to align it as needed.
https://www.codeply.com/go/SJia0JtI1T

    English Park Cuisine

                Login

                Register

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Acasa(current)

                Meniu

                    Pizza
                    Paste
                    Supe
                    Ciorbe
                    Desert

                Contact

0746117702

0742112452

0735212352

Related: Bootstrap 4 - Navbar items outside the collapse

A: Move your shopping cart outside of the nav collapse div and nest it and the nav collapse in a new div. Then style the shopping cart accordingly, but it won't go away with the nav collapse.

English Park Cuisine
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

</button>

            Acasa(current)

                Meniu

                Pizza
                Paste
                Supe
                Ciorbe
                Desert

            Contact

0746117702

0742112452

0735212352

            Login

            Register

    !!!


text:
Q: Using Objects in Multi-input in angular-formly How can i use
[{type:'Fred',link:'google.com'},
{type:'Ethel',link:'google.com'},
{type:'Rick',link:'google.com'},
{type:'Lucy',link:'google.com'}]

instead of
[Ethel,Rick,Lucy]

So now I see [object Object] in the URL input but I want to see the URL there.
I tried kids.url and kids.$.url but didn't worked
the original
http://jsbin.com/yuyawo/6/edit?html,js,output
the one I tried
http://jsbin.com/qiyiku/3/edit?html,js,output


text:
Q: understanding basic trick in math problem i would like  to know what is asked   in the following question:
A shopkeeper marks his goods at $20$% profit and gives discount  of $5$%,i would like to understand  what is main tricky in this problem,gives discount  of $5$%  is it same as  for example original cost was $100$ and after discount became   $95$,  but marks  goods at $20$ percent,it means that after he got  $20$% percent profit,he decrease price by $5$ %?thanks in advance

A: If the item costs him 100 and he sells it for 120, then he is making a 20 percent profit. If he takes off 5 percent of the cost, he cuts the item down to 114, and he is now making a 14 percent profit.

A: Any ambiguity in the order of applying mark-up/discount is irrelevant
If he buys something for 100, the final price is:$$P=100\times 1.20 \times 0.95$$no matter which is multiplied first...


text:
Q: Word count using fold How can a list of words be counted into a Map structure where Int is the count and String is the current word.
I'm attempting to use a fold for this but this is closest I've got :
val links = List("word1" , "word2" , "word3")
links.fold(Map.empty[String, Int]) ((count : Int, word : String) => count + (word -> (count.getOrElse(word, 0) + 1)))

Which causes error :
value getOrElse is not a member of Int

A: Maybe not the most efficient, but the clearest way for me would be:
val grouped = links groupBy { identity } // Map[String, List[String]]
val summed = grouped mapValues { _.length } // Map[String, Int]

println(grouped) // Map(word2 -> List(word2, word2), word1 -> List(word1))
println(summed) // Map(word2 -> 2, word1 -> 1)

A: If you take a look at the signature of fold, you can see that
links.fold(Map.empty[String, Int]) ((count : Int, word : String) => ???)

won't compile
fold on List[A] has type fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1
That's not something you can use; Map.empty[String, Int] is not a subtype of String
What you need is foldLeft: foldLeft[B](z: B)(op: (B, A) ⇒ B): B
Your A is String. Your B is Map[String, Int], but then in your second parameter list you have (Int, String) => ??? That doesn't conform to the signature. It should be (Map[String, Int], String) => Map[String, Int]
A solution immediate presents itself:
(map: Map[String, Int], next : String) => map + (next, map.get(next).getOrElse(0) + 1)

Putting it all together, you'll have
links.foldLeft(Map.empty[String, Int])
((map: Map[String, Int], next : String) => map + (next, map.get(next).getOrElse(0) + 1))

A: You need to use a foldLeft:
val links = List("word1" , "word2" , "word3", "word3")
val wordCount = links.foldLeft(Map.empty[String, Int])((map, word) => map + (word -> (map.getOrElse(word,0) + 1)))

A: This is an example where some of the abstractions of a library like cats or scalaz are useful and provide a nice solution.
We can represent a word "foo" as Map("foo" -> 1). If we can combine these maps for all our words we end up with the word count. The keyword here is combine, which is an function defined in Semigroup. We can use this function to combine all the maps of our word list together by using combineAll (which is defined in Foldable and which does the folding for you).
import cats.implicits._

val words = List("a", "a", "b", "c", "c", "c")

words.map(i => Map(i -> 1)).combineAll
// Map[String,Int] = Map(b -> 1, a -> 2, c -> 3)

Or in one step using foldMap :
words.foldMap(i => Map(i -> 1))
// Map[String,Int] = Map(b -> 1, a -> 2, c -> 3)


text:
Q: How to access an arraylist after 4 threads are finished i got 4 threads running and ech run increases the size of a global arraylist.But i cant access the resulting arraylist after the threads are finished. Is there a way to get access to the resulting arraylist..or how does it work with threads and resutling datastructures??
List<MyObject> head = a.subList(0, 2000);
    List<MyObject> body = a.subList(2001, 5000);
    List<MyObject> body2 =  a.subList(5001, 8000);
    List<MyObject> tail = a.subList(8001, a.size());
    //System.out.println(tail.size());
    createAndRunFirst(head);
    createAndRunFirst(body);

these are the calls
and this is the method which is called 4 times..and i need the currCDO arrylist
public void algo(List<MyObject>list){
    MyObject a = null;
    MyObject b = null;

    int e=0;
    String curr1="";
    String curr2="";
    for (int i = 0; i < list.size(); i++) {
        a =list.get(i);
        curr1= a.getStreetName();
        if(curr1.contains("-")){
            curr1=curr1.replace("-", " ");
        }

        if(curr1.contains("STRASSE")){
            curr1=curr1.replace("STRASSE", "STR.");
        }

        else{
            curr1=a.getStreetName();
        }

        for (int j = 0; j < lotse.size(); j++) {
            b = lotse.get(j);

            curr2=b.getStreetName();
            if(curr2.contains("-")){
                curr2=curr2.replace("-", " ");
            }

            if(curr2.contains("STRASSE")){
                curr2=curr2.replace("STRASSE", "STR.");
            }

            else{
                curr2=b.getStreetName();
            }

            int d = dL.execute(curr1,curr2);

            if(curr1.length()==curr2.length()){
                e=0;
            }
            if(curr1.length()< curr2.length()){
                 e=(curr2.length()*30)/100;
                //System.out.println(d);
            }
            if(curr1.length()> curr2.length()){
                 e=(curr1.length()*30)/100;
                //System.out.println(d);
            }

            if(d<e && a.getPcode().contains(b.getPcode())){
                int x=a.getInstituteName().length();
                int y=b.getInstituteName().length();

                if(x<y){

                    currCDO.add(a);

                }
                if(y<x){

                    currCDO.add(a);

                if(x==y){

                    currCDO.add(a);

                }
                break;}else{

                    //System.out.println(a.getInstituteName()+"******");
                    restCDO.add(a);
                }
            }//System.out.println(currCDO.size() +"*****");
        }
        }

}

public void createAndRunFirst(final List<CrawlerDataObject> list) {
       Thread thread = new Thread(new Runnable() {
          @Override
          public void run(){
              algo(list);

          }

       });
       thread.start();

    }

A: Assuming currCDO is global, are you waiting for all the threads to finish?
You might want to consider building an output list for each thread and then concactenating them at the end.  This would avoid locking.  You could use a threadsafe list too, but that might be slower.  I don't know c# specifically, but I assume there are threadsafe lists.
int i0 = 0;
int c = a.size()/cThread;
new List<MyObject>()[cThread];
for (int iThread=0 ; iThread<cThread ; ++iThread, i0+=c) {
    createAndRunFirst(a.subList(i0, i0 + c - 1), aOut[iThread]);
}

waitForAllThreads();  // i don't know the c# for this

for (int iThread=0 ; iThread<cThread ; ++iThread) {
    currCDO += aOut[iThread];
}

public void createAndRunFirst(final List<CrawlerDataObject> list, List<CrawlerDataObject> out) {
   Thread thread = new Thread(new Runnable() {
      @Override
      public void run(){
          algo(list, out);

      }

   });

public void algo(List<MyObject> list, List<MyObject> currCDO) {
}


text:
Q: Build with parameters for GitHub organization Is there a way we can add build with parameter option in jenkins for github organization project??
Appreciate for your answeres.

A: First, if you're using the GitHub Organization - It is deprecated and hasn't been updated in 2 years.
https://plugins.jenkins.io/github-organization-folder
So you might want to consider using the Multi Branch Pipeline (MBP) in conjunction with Job DSL instead.
Next - the idea is that the MBP is dynamically creating branch 'jobs' when it scans the repo you provide.  I'm not sure that you can't put a parameter block in the pipeline you create, but if you did and it worked, I wonder if the job can be automatically triggered.
https://jenkins.io/doc/book/pipeline/syntax/#parameters


text:
Q: How do I iterate over a nested JSON during Ajax? I have this JSON:
{
  "draw": 0,
  "recordsTotal": 90,
  "recordsFiltered": 41,
  "data": [
    {
      "id": "5",
      "art": "default/def2.jpg",
      "full_name": " ",
      "title": "Hellberg - The Girl | Atomik Remix",
      "tag": "music",
      "time": "2015-11-14",
      "": ""
    },
    {
      "id": "8",
      "art": "default/def2.jpg",
      "full_name": "Simon Deoro",
      "title": "Tim McMorris-On (Single)",
      "tag": "dance,popular,",
      "time": "2015-11-14",
      "": ""
    },
    ...
   ]
}

I want to return all id's inside data, so I tried this function:
function getPlaylist(id) {
    $.ajax({
        type: "GET",
        url: baseUrl+"/playlist.php?id="+id,
        cache: false,
        success: function(result) {
            var samples = JSON.parse( result );
            for (i in samples)
            {
              console.log(samples.data[i].id + "
");
            }
        }
    });
}

however I see this error from console

Uncaught TypeError: Cannot read property 'id' of undefined

I tried also this for loop (syntax error from console)
for(var i = 0; i < samples.data.length; i++)
{
    var product = samples.data[i];
    var productId = product.id;
    console.log(productId);
}

All I want is output 5, 8 (my id's)
I'm not very familiar with JSON, so how can I access and iterate over my structure correctly?

A: You can try using the map function to transform the array to another array.

 var dataJSON = {
      "draw": 0,
      "recordsTotal": 90,
      "recordsFiltered": 41,
      "data": [
        {
          "id": "5",
          "art": "default/def2.jpg",
          "full_name": " ",
          "title": "Hellberg - The Girl | Atomik Remix",
          "tag": "music",
          "time": "2015-11-14",
          "": ""
        },
        {
          "id": "8",
          "art": "default/def2.jpg",
          "full_name": "Simon Deoro",
          "title": "Tim McMorris-On (Single)",
          "tag": "dance,popular,",
          "time": "2015-11-14",
          "": ""
        },

       ]
    };

var obj = dataJSON.data.map((currentValue) => currentValue.id);
console.log(obj);

In the ajax function, you can replace the code like this

function getPlaylist(id) {
    $.ajax({
        type: "GET",
        url: baseUrl+"/playlist.php?id="+id,
        cache: false,
        success: function(result) {
            var samples = JSON.parse( result );
            var idArray = samples.data.map(x => x.id);
            console.log(idArray);
        }
    });

A: samples needs to be samples.data.
function getPlaylist(id) {
    $.ajax({
        type: "GET",
        url: baseUrl+"/playlist.php?id="+id,
        cache: false,
        success: function(result) {
            var samples = JSON.parse( result );
            for (i in samples.data)
            {
              console.log(samples.data[i].id + "
");
            }
        }
    });
}


text:
Q: Dealing with duplication in RavenDB Taking my first shot at NoSQL development using RavenDB.
One thing that is confusing me is how we should handle duplicates across documents that are stored.
Let's say I have a Story (think BDD/ATDD):
{
    Id: 10,
    Title: 'Story 1'
}

Then I decide that a story can have one or more sub-stories. I then create another story and make then above story a sub-story.
{
    Id: 15,
    Title: 'Title',
    Stories: [ { Id: 10, Title: 'Story 1' }]
}

Now I've got two stories. If I load the story with ID=15 and proceed to edit the first story in the Stories array, let's say, with a new title of 'Sub-story 1', the original story stays the same.
What I'm trying to understand: Do I care? If I do, what is the best way to make sure that everything stays in sync? When the sub-story is changed, I want the original story to change as well. What is the appropriate design/solution for this kind of thing?

A: The quick answer is that you shouldn't model things like that.
See: http://ayende.com/blog/156353/entities-associations-point-in-time-vs-current-associations


text:
Q: How to identify the internet status in ionic3 I am using the following code to check the network status but it works only when the internet is made on or off similar like a switch but i would like to know the status of the internet when loading the page is itself.
this.network.onConnect().subscribe(data => {
    console.log('Net status', data.type)
    if (data.type === 'online') {
      this.commonService.hideloader();
      console.log('data is online');
      const path = 'driver_user/vendor_allocations/bulk_create_update.json';
      const params = {'vendor_allocations': [save]};
      this._tokenService.post(path, params).map(res => res.json()).subscribe(
          res => {
            this.commonService.hideloader();
            console.log('res: ', res);
            this.sqliteService.update('entry', this.save_details, 'id', this.save_details.id).then(s => {
              console.log('Entry details saved in database', s);
              this.commonService.hideloader();
              this.commonService.presentToast('தகவல் சேமிக்கப்பட்டது');
              this.navCtrl.setRoot('FarmerlistPage');
            });
          },
          error => {
            console.log(error);
            this.commonService.hideloader();
          }
      );
    } else if (data.type !== 'online') {
      console.log('user seems to be offline');
      this.commonService.hideloader();
      this.commonService.presentToast('தகவல் சேமிக்கப்பட்டது');
    }
  }, error => console.error(error));

A: You can create a new method and use the network.type property to check that:
@Component({
  selector: 'home-page',
  templateUrl: 'home-page.html'
})
export class HomePage {

  constructor(private platform: Platform, private network: Network, //...) {}

  ionViewWillEnter() {
    this.platform.ready().then(() => {
      if(this.isOnline()) {
        // Code required to initialize the page if the user is online
      } else {
        // What to do when the user is offline
      }
    });
  }

  // Please notice that the type property will return one of the following
  // connection types: `unknown`, `ethernet`, `wifi`, `2g`, `3g`, `4g`,
  // `cellular`, `none`

  // Method that returns true if the user is connected to internet
  private isOnline(): boolean {
    return this.network.type.toLowerCase() !== 'none';
  }

  // Method that returns true if the user is not connected to internet
  private isOffline(): boolean {
    return this.network.type.toLowerCase() === 'none';
  }

}


text:
Q: How to change DrawingVisual Fill and Stroke I have a DrawingVisual object and I want to change its fill and its stroke.
I've tried this for Fill:
DrawingVisual MyDrawing = new DrawingVisual();
SetFill(Brushes.Red, MyDrawing.Drawing);

Where SetFill is:
private void SetFill(Brush fill, DrawingGroup group)
{
    foreach (Drawing drw in group.Children)
    {
        if (drw is DrawingGroup)
            SetFill(fill, drw as DrawingGroup);
        else if (drw is GeometryDrawing)
        {
            GeometryDrawing geo = drw as GeometryDrawing;
            geo.Brush = fill;

            using (DrawingContext context = MyDrawing.RenderOpen())
            {
                context.DrawDrawing(group);
            }
        }
    }
}

But in this way may happen that my DrawingVisual is drawn to a different position, as if the transformations have not been applied more (to MyDrawing).
Also, if I change this instruction: context.DrawDrawing(group);
with this other: context.DrawDrawing(MyDrawing.Drawing);
I get a strange effect: if I change the Fill the first time nothing happens, while the second the Fill is changed correctly without changing the positions of the figure.
How can I do?

A: A much simpler approach to your problem (dynamically changing the fill) would be to use an own SolidColorBrush for all fills and change its Color whenever needed.

A: You are indeed not required to re-draw the Visuals.
This should work.
private void SetFill(Brush fill, DrawingGroup group)
{
    foreach (Drawing drw in group.Children)
    {
        if (drw is DrawingGroup)
            SetFill(fill, drw as DrawingGroup);
        else if (drw is GeometryDrawing)
        {
            GeometryDrawing geo = drw as GeometryDrawing;
            geo.Brush = fill; // For changing FILL

            // We have to set Pen properties individually.
            // It does not work if we assign the whole "Pen" instance.
            geo.Pen.Brush = fill;
            geo.Pen.Thickness = 1.0;
        }
    }
}

A: probably you've already solved this problem but here is my solution of maybe same thing. I have my own DrawingVisual. It is fresh and not very tested code but for now it works very good:
public class MyDrawingVisual : DrawingVisual
{
    private bool myIsSelected = false;

    public VillageInfo VillageInfo { get; set; }

    public bool IsSelected
    {
        get { return myIsSelected; }
        set
        {
            if (myIsSelected != value)
            {
                myIsSelected = value;

                // Retrieve the DrawingContext in order to create new drawing content.
                DrawingContext drawingContext = this.RenderOpen();

                // Create a rectangle and draw it in the DrawingContext.
                Rect rect = new Rect(new System.Windows.Point(VillageInfo.X + 0.1, VillageInfo.Y + 0.1), new System.Windows.Size(0.9, 0.9));
                drawingContext.DrawRectangle(new SolidColorBrush(myIsSelected ? Colors.White : VillageInfo.Color), (System.Windows.Media.Pen)null, rect);

                // Persist the drawing content.
                drawingContext.Close();
            }
        }
    }
}


text:
Q: How should I handle lookups in my ViewModel? My database table for buildings stores the building type as a code.  In a separate lookup table the description for that code is stored.
How should I design my ViewModel and where will I need to make the call to get the associated description value?
I sort of can see one option. I want to know if there is a better option.
BuildingViewModel
{
 public string BuildingTypeCode { get;set;}
 ...other properties
}

Then in my view
code...

<p>@MyService.GetDescription(Model.BuildingTypeCode)</p>

...code

Am I incorrect in the way I am thinking? if I do the above I create a dependency in my View to the service?
Update 1
Working through some of the solutions offered.  I seem to run into another issue.  I can't access the constructor of each building directly...
    public ViewResult Show(string ParcelId)
    {
        var result = _service.GetProperty(ParcelId);
        var AltOwners = _service.GetAltOwners(ParcelId);
        var Buildings = _service.GetBuildings(ParcelId);

        ParcelDetailViewModel ViewModel = new ParcelDetailViewModel();
        ViewModel.AltOwnership = new List<OwnerShipViewModel>();
        ViewModel.Buildings = new List<BuildingViewModel>();

        AutoMapper.Mapper.Map(result, ViewModel);
        AutoMapper.Mapper.Map<IEnumerable<AltOwnership>, IEnumerable<OwnerShipViewModel>>(AltOwners,ViewModel.AltOwnership);
        AutoMapper.Mapper.Map<IEnumerable<Building>, IEnumerable<BuildingViewModel>>(Buildings, ViewModel.Buildings);
        ViewModel.Pool = _service.HasPool(ParcelId);
        ViewModel.Homestead = _service.IsHomestead(ParcelId);

        return View(ViewModel);
    }

public class ParcelDetailViewModel
    {
        public IEnumerable<OwnerShipViewModel> AltOwnership { get; set; }
        //public IEnumerable<ValueViewModel> Values { get; set; }
        public IEnumerable<BuildingViewModel> Buildings { get; set; }
        //public IEnumerable<TransferViewModel> Transfers { get; set; }
        //public IEnumerable<SiteAddressViewModel> SiteAddresses { get; set; }

        public string ParcelID { get; set; }
        //public string ParcelDescription { get; set; }
        //public int LandArea { get; set; }
        //public string Incorporation { get; set; }
        //public string SubdivisionCode {get;set;}
        public string UseCode { get; set; }
        //public string SecTwpRge { get; set; }
        //public string Census { get; set; }
        //public string Zoning { get; set; }
        public Boolean  Homestead {get;set;}

        //public int TotalBuildingArea { get; set; }
        //public int TotalLivingArea { get; set; }
        //public int LivingUnits { get; set; }
        //public int Beds { get; set; }
        //public decimal Baths { get; set; }
        public short Pool { get; set; }
        //public int YearBuilt { get; set; }

    }

A: My understanding is that the view model is meant for display ready data. I think the real problem here is putting model dependent logic into the view.
You can do your service lookup but keep that code in the controller. The view model should be considered display ready (save for some formatting).
class BuildingViewModel
{
    public string BuildingTypeCode { get;set;}
    ...other properties
}

and then do the lookup before you render:
public ActionResult Building()
{
    var typeCode = // get from original source?
    var model = new BuildingViewModel
    {
        BuildingTypeCode = MyService.GetDescription(typeCode)
    };
    return View("Building", model);
}

Having come from a long line of JSP custom tags I dread having any code hidden in the view layout. IMO, that layer should be as dumb as possible.

A: I would recommend having a helper that does that, or a DisplayTemplate
public class ViewHelpers
{
  public static string GetDescription(string code)
  {
    MyService.GetDescription(Model.BuildingTypeCode);
  }
}

or
@ModelType string
@Html.DisplayFor("",MyService.GetDescription(Model.BuildingTypeCode));

More info on templates: http://www.headcrash.us/blog/2011/09/custom-display-and-editor-templates-with-asp-net-mvc-3-razor/
Both of these approaches introduce a dependency on your service but you can test/change them in one single place, instead of the whole application (plus the usage looks cleaner).


text:
Q: I am importing layers from a DWG file into QGIS, and they are visible in the "Layers" panel, but they are not visible in the layout I am very new to QGIS. I have a DWG file containing vector layers and I am using Project>Import/Export>Import Layers from a DWG/DXF. Some layers are then visible in the map, but others are not. When I try to "zoom to layer" on the invisible layers, nothing happens.
When I click on the feature count for one of the "lines" layers, it says there are 124140 features. Almost every other "line" layer throughout all the groups has 124140 features. Could it be that the line layers are all overlapping?

The "lines" feature under I-LAB-FURN should be very prominent in this section of the map, but it is completely invisible.
Some things I've tried:
Merging layers
Checking CRS consistency (there might be something I'm missing here)
Unchecking "Expand block references" and "Use curves"
Converting DWG to DXF and then importing. This causes nothing to show up instead.
What else could be the problem?

A: A lot depends on how the original dwg was set up. Sometimes features that appear to be in a specific layer in CAD will end up on another layer because the block itself is on that other layer. Sometimes when a block is imported that way it retains the original colour feature (so you may have some white coloured lines). Sometimes the coordinates will end up all over the place because of xrefs and so on.
Here are some general troubleshooting ideas:

*

*Go to your QGIS Project Properties and change the background colour of your project to grey or black to see if anything shows up - the missing lines might be white in colour.

*Try going into the attribute table for your I-LAB-FURN lines and right click on a row and zoom to feature - see if it's ended up somewhere else. If so, may need to do something to the original dwg to get them all into the right place. Maybe explode blocks and bind all xrefs before importing to QGIS.

*Try the Another DXF Importer plugin to see if that makes a difference - sometimes it works better than the native dwg importer, sometimes worse.


text:
Q: Watcher is rarely auto-triggered, and does not always compile the code I have a couple of sites, and on one of these, just this one, the watchers are misbehaving.
The worst one is the SCSS watcher, its set to watch current file, track only root files and trigger regardless of syntax errors.
The behavior is very weird: sometimes it auto compiles the .css file on changes. Often it does not and I have to manually compile it with a binding. However often this does not compile anything though PhpStorm activated the process. Sometimes after 3 or 5 times it successfully adds the changes. So it's very sporadic and weird.
I have tried restarting everything, clear cache and so on. The SCSS compiler works fine on my other sites.
It's run in PhpStorm with these arguments:
--no-cache --update $FileName$:$FileNameWithoutExtension$.css

Only noticable thing in idea.log when the error occurs:
2018-03-26 10:08:36,560 [332106460]   INFO - agnostic.FrequentEventDetector - Too many events posted, #1. Event: java.awt.event.InvocationEvent[INVOCATION_DEFAULT,runnable=TransferToEDTQueue[Apply highlighting results],notifier=null,catchExceptions=false,when=1522051716560] on sun.lwawt.macosx.LWCToolkit@3f7d6f55

This is a purely local installation


text:
Q: Angular Wait For Promise To Result For Variable To Show In Template I am simply trying to pull data from a database and display it using angular tmeplate.
here is my view.ts
//Global variable
rec;

  async getStats(stats) {
    this.result = await this.userService.getStats(stats);
  }

here is my userService.ts
  getStats(stats) {
    console.log(stats);
    const url = "http://localhost:3000/get/stats";
    return this.http.post(url, {stats: stats}).toPromise();
  }

here is my view.html:
<h1 *ngIf="result">Rec</h1>

When the result finally gets a value, the H1 does not appear in the view.


text:
Q: How to handle switch conditions using java stream API I am trying to construct sql query based on request. I have different types of expressions:
"and" -> And Expression
"or" -> Or Expression
"eq" -> Equality Expression
"notEq" -> Not Equality Expression
"ge" -> Greater Than Equality Expression
"gt" -> Greater Than Expression
"lt" -> Less Than Expression
"le" -> Less Than Equality Expression
"between" -> Between Expression
"like" -> Like Expression
I have tried for two conditions. But I want to do multiple conditions based on type I have to select expression. Like if eq is type then I have expression is = or in if between type then I have expression like between.
searchQuery = listOfExpression.stream()
        .map(e -> e.getFilterName() + "" +
                (e.getType(). equalsIgnoreCase("eq") ? " in" : " like") + "(" +
                (e.getValues().stream()
                        .map(s -> "'" + s + "'")
                        .collect(Collectors.joining(","))) + ")")
        .collect(Collectors.joining(" " + searchType));


text:
Q: How are images handled in Microsoft Word I am trying to embed images in xml document and save the document as a single document and be able to distribute the file just like microsoft word where both the text and images are saved in single docx file.
How is it done in Microsoft word. Do they use base64 encoding ?

A: It is quite hard to do it by hand and would look something like that:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
            xmlns:v="urn:schemas-microsoft-com:vml"
            xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
            xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body>
    <w:p>
      <w:r>
        <w:drawing>
          <wp:inline distT="0" distB="0" distL="0" distR="0">
            <wp:extent cx="5943600" cy="3717290"/>
            <wp:docPr id="1" name="Picture 0" descr="vlcsnap-325726.png"/>
            <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
              <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
                <pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
                  <pic:nvPicPr>
                    <pic:cNvPr id="0" name="myImage.png"/>
                    <pic:cNvPicPr/>
                  </pic:nvPicPr>
                  <pic:blipFill>
                    <a:blip r:embed="rId4"/>
                    <a:stretch>
                      <a:fillRect/>
                    </a:stretch>
                  </pic:blipFill>
                  <pic:spPr>
                    <a:xfrm>
                      <a:off x="0" y="0"/>
                      <a:ext cx="5943600" cy="3717290"/>
                    </a:xfrm>
                    <a:prstGeom prst="rect">
                      <a:avLst/>
                    </a:prstGeom>
                  </pic:spPr>
                </pic:pic>
              </a:graphicData>
            </a:graphic>
          </wp:inline>
        </w:drawing>
      </w:r>
    </w:p>
  </w:body>
</w:document>

You don't want to do it that way. I would recommend to use an external library like OpenXML SDK 2.0 (by Microsoft) or OpenXML4J (especially for Java). They will make your life way easier


text:
Q: С# mvc 5 с базой данных Я создал две модели. Один для игроков, а второе для клубов. Создал базу и заполнил. При запуске, данных об игроках нету.
Код:
public class Player

{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string Position { get; set; }

    public int? TeamId { get; set; }

    public Team Team { get; set; }
}
public class Team

{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Coach { get; set; }

    public ICollection<Player> Players { get; set; }

    public Team()
    {
        Players=new List<Player>();
    }
}

public class HomeController : Controller
{

    SoccerContext db = new SoccerContext();
    public ActionResult Index()
    {
        var players = db.Players.Include(p=>p.Team);
        return View(players.ToList());
    }
}


text:
Q: android app not identifying Camera properties -In the top of the class i wrote :
 import android.graphics.Camera;
import android.hardware.Camera.Parameters;

-When creating a Camera object, it does not identify the next things:
Camera c;
Camera.Parameters parameters = c.getParameters();
Camera c = Camera.open();

-I wrote in manifest the following lines:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.CAMERA"
uses-feature android:name="android.hardware.camera2"


text:
Q: JSON Data not Displaying on Webpage I am trying - for the first time - to connect to a Blackbaud API, retrieve a JSON object, and display it on a web page. The request.open link I am using (not shown below because it contains user data) returns information with no error when I put it directly into browser.
An example of the JSON data return is here:
{"getConsTransactionsResponse":{"transaction":{"amount":{"formatted":"$50.00","decimal":"50.00"},"timestamp":"2016-02-01T09:43:54.458-06:00","pay_method":"ONLINE","billing_name":{"title":null,"last":"Smith","suffix":null,"middle":null,"first":"John","prof_suffix":null},"transaction_type":"DONATION","tender_type":"INVALID","confirmation_code":{},"donation_detail":{"value_of_goods":{"formatted":"$0.00","decimal":"0.00"},"tax_deductible_amount":{"formatted":"$0.00","decimal":"0.00"},"level":{"id":"9921","title":"API Donation Level"},"form":{"id":"9999","title":"API Form","description":"Sample form for API documentation."},"campaign":{"id":"9901","title":"API Campaign","description":"Sample campaign for API documentation."}},"billing_address":{"street2":null,"zip":null,"street1":null,"county":null,"state":null,"street3":null,"country":null,"city":null}}}}

The script I am using to retrieve and then display the data is here:

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

A: Check console (pressing F12) you might see an error "response undefined" . If this is true, then you have to put 'response' variable on 'onload' function, like this :
request.onload = function (response) {


text:
Q: How to use wordpress + django to build a website I have a wordpress website ,and i want to add more functionality with django framework.Is it posible to build a hybrid website with Wordpress and Django..???

A: Let's start with the configuration. The first thing is that you need to install WP REST API v1 plugin inside your WordPress site and enable it.
Then you need to install Django WordPress Api library inside your django application
pip install django-wordpress-api
After that, add wordpress_api inside the installed apps
INSTALLED_APPS += ('wordpress_api',)
Also, if you are using DWA Views (explained later) you need to add the wordpress_api urls in your application urls
url(r'^blog/', include('wordpress_api.urls')),
Finally, you need to set up the DWA required settings; WP_URL and BLOG_POSTS_PER_PAGE.
WP_URL = https://your-wordpress-app.com/
BLOG_POSTS_PER_PAGE = number-of-blogs-to-display-per-page
and that's it.
You can follow this link


text:
Q: Why did Paxton create the hybrid baby? In the final episodes of Enterprise, we discover

 that John Paxton used DNA from Tucker and T'Pol to create a half-human half-Vulcan baby.

It is unclear to me from the episodes why he actually did this. Is a clear explanation ever given?
He does reveal

  the baby

to the world in his big speech; showing how it is a threat to the future of humanity. But did he create

 the child

simply to have a prop to use during that speech? That definitely doesn't seem like a necessary part of his plan. Was he simply attempting to learn

 whether or not human and Vulcan DNA is compatible, to know if he had to fear the possible end of humanity through cross-breeding

?
Again, he had his reasons to fear contact with other alien species even if that had proved impossible.

A: You are pretty much answering your own question, seeing he only created the baby as proof that mixing between different species is possible, suggesting that it is eventually possible that there won't be a "pure" human left in the distance future.
This is an allegory for an issue that became prominent in the late 1800's (and is still referred to today) that by allowing "race-mixing" certain races would eventually disappear in to extinction.
And just as they used this in real life as an "argument" in favor of segregation,  Paxton uses this as a political point to further his anti-alien rhetoric's.
It's a common trope in SC-fi and fantasy works based on real life "racist" rhetoric's. (Like in Dragon Age where the child of an Human/Elven couple is always human, therefor elves who have relationships with humans are sometimes shunned by their community because they view their actions as helping the extinction of Elven kind.)


text:
Q: South: changing ForeingKey i had a profile field in todo models which a ForeignKey to Profile model
Instead of using profile i want to use the user field of User model as a ForeignKey .
Steps:

*

*I have removed the profile field from todo model, created and applied migration for that.
Works fine, profile field do not exist in database.

2, I added user field as a ForeignKey in todos models .
When doing python manage.py schemamigration todos --auto
gives response like:
Nothing seems to have changed.
what am missing here ?


text:
Q: Why aren't the angular EventEmitter subscribe method parameters strongly typed? Why aren't the angular EventEmitter subscribe method parameters strongly typed?
https://github.com/angular/angular/blob/a14dc2d7a4821a19f20a9547053a5734798f541e/packages/core/src/event_emitter.ts#L102
subscribe(generatorOrNext?: any, error?: any, complete?: any): Subscription {
  ...
}

instead of something like
subscribe(generator: DefForGenerator): Subscription;
subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
subscribe(generatorOrNext?: any, error?: any, complete?: any): Subscription {
  ...
}

A: @jonrsharpe 's comment sends you in the right direction.
According to this comment you shouldn't be using EventEmitter.subscribe() / its only designed to be consumed by the @Output() metadata. So the any typing may be the developers discouraging the use of the method.


text:
Q: Is UTF-8 acceptable for reading/writing Asian languages? I am accepting user input via a web form (as UTF-8), saving it to a MySQL DB (using UTF-8 character set) and generating a text file later (encoded as UTF-8). I am wondering if there is any chance of text corruption using UTF-8 instead of something like UCS-2? Is UTF-8 good enough in this situation?

A: UTF-8 can represent any unicode character. As such you should have no problem with UTF-8.
In fact, UTF-8 can even represent some characters that UCS-2 cannot (UCS-2 can only represent U+0000 through U+FFFF; UTF-8, UTF-16, and UCS-4 handle all unicode codepoints)

A: More than that, it is perhaps the only encoding you should ever consider using.
Some great reading on the subject:
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky

A: If you are working with a great deal of Asian text (more so than Latin text), you may want to consider UTF-16. UTF-8 can accurately represent the entire Unicode range of characters, but it is optimized for text that is mostly ASCII. UTF-16 is space-efficient over the entire Basic Multilingual Plane.
But UTF-8 is most certainly "good enough"—there will not be corruption arising simply because you are using UTF-8 over, say, UTF-16.

A: As far as I know, UTF-8 is designed to encompass all of these earlier Unicode variations, so yes it should be fine to use it over UCS-2. See http://www.unicode.org/versions/Unicode5.1.0/ and look down the sidebar for the 5.0 book chapters; parts 9-12 should be what you're after.

A: It works wonderfully with Devanagari.


text:
Q: FB api graphql : Calculate the number of messages with friends in facebook I am trying to use the fb graph api to get total messages with each friends.
I was looking at an app and found them doing the following (by seeing the XHR and fetch request in Network F12 developer)
Step 1: they get the token from link:
https://m.facebook.com/composer/ocelot/async_loader/?publisher=feed

Step 2: get the friend list from api:
https://graph.facebook.com/v9.0/me/friends?

Step 3: get the total message with each friend by api:
api
response
I am having the problem at the step 3, my code
var form = new FormData;
form.append("fb_dtsg", {fb_dtsg:I took in step 1});
form.append("q", "viewer(){message_threads{nodes{thread_key{thread_fbid,other_user_id},messages_count,thread_type,updated_time_precise}}}");
fetch("https://www.facebook.com/api/graphql/", {
    body : form,
    headers : {
      accept : "application/json, text/plain, */*"
    },
    method : "POST"
}).then(function(e) {
    return e.text();
}).then(function(savedC){
      /** savedC IS EMPTY */
});

The value of "saveC" is not as expected, it is empty.
Can anyone help me know where i am going wrong and how to fix it?


text:
Q: firefox chrome padding issue with button I have a problem with a project, i don't know way, chrome and firefox are not display the same height with my buttons. I'd been looking around and I found that firefox has an issue with buttons, so i add the code below, but still doesn't work. What could it be?
.button-type::-moz-focus-inner { border: 0; padding: 0; margin:0; }

.button-type {
  background: #a9a9a9;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -webkit-box-shadow: 0 2px 8px rgba(0,0,0,0.3), inset 0 3px rgba(255,255,255,0.2), inset 0 2px rgba(255,255,255,0.2), inset 0 28px 22px rgba(255,255,255,0.2), inset 0 -10px 28px rgba(0,0,0,0.2);
  box-shadow: 0 2px 8px rgba(0,0,0,0.3), inset 0 3px rgba(255,255,255,0.2), inset 0 2px rgba(255,255,255,0.2), inset 0 28px 22px rgba(255,255,255,0.2), inset 0 -10px 28px rgba(0,0,0,0.2);
  font: Arial, Helvetica, sans-serif;
  line-height: 1;
  padding: 8px 15px;
  width: auto;
  height: auto;
  border: none;
  text-align: center;
  font-size: 13px;
  color: #fff;
  cursor: pointer;
  display: block;
  text-decoration: none;
  text-shadow: -1px -1px #333;
}
.button-type.black {
  background: #000;
  color: #fff;
}
.button-type.gray {
  background: #a9a9a9;
}
.button-type.light-gray {
  background: #d3d3d3;
  color: #222;
}

A: Solve it the solution (and error) was:
display:block

replace it with:
display:inline


text:
Q: String Manipulation java So I have used this site a good deal, but I can't find an answer...
How can I manipulate specific chars/strings from a larger string. I'm trying to use string.substring(pos,amount) but when I try and use it in loops I get a string Index Error.
for instance- How could I remove 'e' at [4] from string "abcdefg" or just capitalize "cde"? Sorry for lack of formal code in my question, it's mainly a conceptual thing. Thank you.
Thanks for the suggestions I was trying to answer this question:
Write a program that takes as input a string of only letters and displays the string with
every third letter capitalized starting with the second letter, and all other letters lower-case.
With this code:
public class Test {
    public static void main(String[] arguments){
        Scanner fish = new Scanner(System.in);
        String a = fish.nextLine();
        int len=a.length();
        for (int i = 1; i < len; i += 3){
            String z = a.substring(i, 1);
            String q = a.substring(i + 1);
            a = z.toUpperCase() + q;
        }
        System.out.println(a);
    }
}

A: String itself is an immutable class, hence you cannot make modifications to it. When you make modifications a new object is returned back... But that is not always the best way (in terms of performance) to manipulate Strings especially when you have a large String.
Java has some other classes like StringBuffer and StringBuilder which exposes many more String manipulation operations. Following is a snippet :
`public String manipulateStr(String sourceStr) {
    StringBuffer sb = new StringBuffer(sourceStr);
    sb.delete(5,7); // Delete characters between index 5-7
    sb.insert(10, "<inserted str>"); // Insert a new String
    return sb.toString();
}`

Hope the above helps.

A: There is no easy way to do what you're looking for, unfortunately. Substring is not meant for replacements. For example, some languages allow you to do this:
str.substring(2,3).toUpperCase();

Java doesn't work that way. If you're looking for things like that, you're going to be best off writing a small function library that takes strings and coordinates and does the work manually. It's not baked into the String class. Look at what all is already baked into the String class! It doesn't need more functionality that only a small subset of users would use.

A: replaceAll() could be a good option here, as per the Java API:

Replaces each substring of this string that matches the given regular expression with the given replacement.

This seems to do what you want, since you could do something like:
str.replace('e', ''); // remove 'e' from the string, or
str.replaceAll("cde", "CDE");

The problem most people have with replaceAll() is that the first parameter is not a literal String, it is regex that gets interpreted and used as a pattern to be matched against.
This is just a quick example, but using replace() and replaceAll() effectively does what you want. Granted it isn't by any means the most efficient or easiest to write.

A: If you know what you want to remove, say the letter "e", but you do not where it is in the string, you can use
stringName.indexOf("e");

It will return an integer of the index of the first occurrence of the string "e" within stringName. You will then have to create a new string that takes in substrings of your original string. You will have to specify the beginning and end indexes for your substrings based on the the returned integer from indexOf().
If you are using indexOf() to find a string that is longer than one character, for example indexOf("ef"), you will also need to take into account the length of this string.

A:
How could I remove 'e' at [4] from string "abcdefg"

As Ameya already said, if you're dealing with String objects then you can't really "remove" the e, because the String is fixed.  What you have to do instead is build a new String object containing all the bits except the e:
String input = "abcdefg";
String output = input.substring(0, 4) + input.substring(5);
//                     "abcd"         +       "fg"

or just capitalize "cde"?

Again, you can take the bit before, add the upper case of "cde", and then add the rest:
String output = input.substring(0, 2) + input.substring(2, 5).toUpperCase()
                + input.substring(5);
//            = "ab" + "CDE" + "fg"

Write a program that takes as input a string of only letters and displays the string with every third letter capitalized starting with the second letter, and all other letters lower-case.

In this case you need to loop over the characters, so it's better to use a StringBuilder rather than adding the Strings together (for performance reasons).  Here's an example of adding each character one by one, and for every third character converting it to upper case:
StringBuilder sb = new StringBuilder();
for (int i=0; i<input.length(); i++)
{
    char c = input.charAt(i);
    if (i%3 == 1) {
        c = Character.toUpperCase(c);  // every third character upper case
    }
    else {
        c = Character.toLowerCase(c);
    }
    sb.append(c);
}
String output = sb.toString(); // aBcdEfg


text:
Q: Incompatible types issue when compiling - void to MimeMessage I have encountered an issue while compiling my app, the error is:
incompatible types: void cannot be converted to javax.mail.internet.MimeMessage
It occurs in this part of the code:
getEmailService().parseEmail(parseEmailRequest.getFileName(), parseEmailRequest.getFileContent());

and the methods are as follows:
private EmailService getEmailService() {
return new EmailService();
}

and
public MimeMessage parseEmail(String fileName, Part fileContent) {
        return getParseEmailUseCase()
                .withEmailFileStorage(getEmailFileStorage())
                .withFilePathBuilder(getFilePathBuilder())
                .withEmailParser(getEmailParser())
                .withFileName(fileName)
                .withFileContent(fileContent)
                .run();
    }

This is strange to be because I wanted it as a variable message
private void setEmailMessage(ParseEmailRequest parseEmailRequest) {
    message = getEmailService()
            .parseEmail(parseEmailRequest.getFileName(), parseEmailRequest.getFileContent());
}

message is a field
private MimeMessage message;

and this is when I get error and when I remove message and keep only:
getEmailService().parseEmail(parseEmailRequest.getFileName(), parseEmailRequest.getFileContent());

program is compiled. What is more, when I use my IDE (intellij) for assigning a variable to above code, MimeMessage is automatically selected so it means getEmailService().parseEmail(parseEmailRequest.getFileName(), parseEmailRequest.getFileContent()); returns MimeMessage as I wanted.
All of the above is happning in class EmailHandler.
I don't understand where the void comes from in the error message since my methods return specified types. What am I missing here?

A: getEmailService().(parseEmailRequest.getFileName(), parseEmailRequest.getFileContent());
should be:
getEmailService().parseEmail(parseEmailRequest.getFileName(), parseEmailRequest.getFileContent());
You didn't provide much context to your code, but from what I assume, you intend to create the message object within EmailService. getEmailService() returns you an instance to the object EmailService which then lets you call the parseEmail() method. Note that if EmailService is intended as a factory class of some sort, other classes won't be able to use its methods if they are using the publicity modifier private.


text:
Q: [sqlalchemy]SyntaxError: non-keyword arg after keyword arg @classmethod
def get(cls, id=None, **kwarg):
    return con_sesison.query(cls).filter_by(or_(id=id, and_(**kwarg))).scalar()

theh I get the error:

SyntaxError: non-keyword arg after keyword arg

A: By using id=id you are passing an id argument with the value equals to id variable. Instead you need to pass filter conditions to or_ in format field == value.
Just replace id=id with id==id.

A: filter_by is just a shorthand function to do equal comparison via keyword arguments. Instead almost always it is clearer to use filter which allows expressions:
exprs = [cls.k == v for k, v in kwarg.items]
con_session.query(cls).filter(or_(cls.id==id, and_(*exprs))).scalar()

The filter_by method is not very flexible but with the above you should be able to achieve the same (untested).


text:
Q: How can I set the BLE connection timeout of gatttool on Raspberry Pi? I connect to a bluetooth le peripheral with the following command:

*

*gatttool -t random -b xx:xx:xx:xx:xx:xx -I

*and connect

If the given MAC-address exists, I have no problem.
If the given MAC-Address does not exist, the gatttool trys to connect about 40 seconds, till the gatttool response is "Error: connect error: Connection refused (111)".
My question is, how and where can i change the 40 seconds connection timeout of gatttool?

A: The connection timeout is defined in the bluetooth module of the Linux kernel (L2CAP_CONN_TIMEOUT) and there is no way to change it in userspace.  (There's another constant, HCI_LE_CONN_TIMEOUT, but I don't think that's used for this purpose.) However, I believe that if you close the connection or kill the process, the kernel should send the proper LE Create Connection Cancel command so that you can connect to someone else shortly thereafter.

A: Unfortunately I don't think there is anyway to do this unless you want to change the gatttool code. I had a look previously and can see in the code that gatttool does a blocking socket "connect" call.

A: If you are ready to change the gatttool code then you will need to add a timeout on the connection socket in Bluez.
I had to do the same workaround when I wrote GattLib to avoid to block the retry.
You can see my change in this commit: https://github.com/labapart/gattlib/commit/ee58e4cb64af6c698dea1fabb5b6d5e0fc174883
But the main changes are these lines:
    if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
        fprintf(stderr, "l2cap_connect: Failed to setsockopt for receive timeout.\n");
        return -1;
    }

    if (setsockopt (sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
        fprintf(stderr, "l2cap_connect: Failed to setsockopt for sending timeout.\n");
        return -1;
    }

You might be interested by the GattLib example ble_scan if you want to write your own code.


text:
Q: Design Patterns for Data Access Layer I have an application which uses a database (MongoDB) to store information. In the past, I have used a class full of static methods to save and retrieve data but I have since realised this is not very object-oriented or future-proof.
Even though it is very unlikely I will change the database, I would rather have something that does not tie me too strongly to MongoDB. I would also like to be able to cache results with the option to refresh the cached object from the database, but this is not essential and can be done in another place.
I have looked at data access objects, but they do not seem very well-defined and I can't find any good examples of implementation (In Java or a similar language). I also have many one-off cases such as finding usernames for tab completion that seems not well suited and would make the DAO large and bloated.
Are there any design patterns that would facilitate getting and saving objects without being too database-specific? Good examples of implementation would be helpful (preferably in Java).

A: Well, the common approach to data storage in Java is, as you noted, not at all very object-oriented. This is in and of itself neither bad nor good: "object-orientedness" is neither an advantage nor disadvantage, it's just one of many paradigms, that sometimes helps with good architecture design (and sometimes not).
The reason DAOs in Java aren't usually object-oriented is exactly what you want to achieve – relaxing your dependency on the database. In a better-designed language, that allowed for multiple inheritances, this, of course, can be done very elegantly in an object-oriented way, but with Java, it just seems to be more troublesome than it is worth.
In a broader sense, the non-OO approach helps decouple your application-level data from the way it is stored. This is more than (non-)dependency on the specifics of a particular database, but also the storage schemas, which is especially important when using relational databases (don't get me started on ORM): you can have a well-designed relational schema seamlessly translated into the application OO model by your DAO.
So, what most DAOs are in Java nowadays are essentially what you mentioned in the beginning – classes, full of static methods. One difference is that, instead of making all the methods static, it is better to have a single static "factory method" (probably, in a different class), that returns a (singleton) instance of your DAO, which implements a particular interface, used by application code to access the database:
public interface GreatDAO {
    User getUser(int id);
    void saveUser(User u);
}
public class TheGreatestDAO implements GreatDAO {
   protected TheGreatestDAO() {}
   ...
}
public class GreatDAOFactory {
     private static GreatDAO dao = null;
     protected static synchronized GreatDao setDAO(final GreatDAO d) {
         final GreatDAO old = dao;
         dao = d;
         return old;
     }
     public static synchronized GreatDAO getDAO() {
         return dao == null ? dao = new TheGreatestDAO() : dao;
     }
}

public class App {
     void setUserName(final int id, final String name) {
          final GreatDAO dao =  GreatDAOFactory.getDao();
          final User u = dao.getUser(id);
          u.setName(name);
          dao.saveUser(u);
     }
}

Why do it this way as opposed to static methods? Well, what if you do decide to switch to a different database? Naturally, you'd create a new DAO class, implementing the logic for your new storage. If you were using static methods, you would now have to go through all your code, accessing the DAO, and change it to use your new class, right? This could be a huge pain. And what if then you change your mind and want to switch back to the old DB?
With this approach, all you need to do is to change the GreatDAOFactory.getDAO() and make it create an instance of a different class, and all your application code will be using the new database without any changes.
In real life, this is often done without any changes to the code at all: the factory method gets the implementation class name via a property setting, and instantiates it using reflection, so, all you need to do to switch implementations is to edit a property file. There are actually frameworks – like spring or guice – that manage this "dependency injection"  mechanism for you, but I won't go into details, first, because it is really beyond the scope of your question, and also, because I am not necessarily convinced that the benefit you get from using those frameworks is worth the trouble integrating with them for most applications.
Another (probably, more likely to be taken advantage of) benefit of this "factory approach" as opposed to "static" is testability. Imagine that you are writing a unit test that should test the logic of your App class independently of any underlying DAO. You don't want it to use any real underlying storage for several reasons (speed, having to set it up, and clean up afterwards, possible collisions with other tests, the possibility of polluting test results with problems in DAO, unrelated to App, which is actually being tested, etc.).
To do this, you want a test framework, like Mockito, that allows you to "mock out" the functionality of any object or method, replacing it with a "dummy" object, with predefined behavior (I'll skip the details, because, this again is beyond the scope). So, you can create this dummy object replacing your DAO, and make the GreatDAOFactory return your dummy instead of the real thing by calling GreatDAOFactory.setDAO(dao) before the test (and restoring it after). If you were using static methods instead of the instance class, this would not be possible.
One more benefit, which is kinda similar to switching databases I described above is "pimping up" your DAO with additional functionality. Suppose that your application becomes slower as the amount of data in the database grows, and you decide that you need a cache layer. Implement a wrapper class, that uses the real DAO instance (provided to it as a constructor parameter) to access the database, and caches the objects it reads in memory so that they can be returned faster. You can then make your GreatDAOFactory.getDAO instantiate this wrapper, for the application to take advantage of it.
(This is called "delegation pattern" … and seems like a pain in the butt, especially when you have lots of methods defined in your DAO: you will have to implement all of them in the wrapper, even to alter behavior of just one. Alternatively, you could simply subclass your DAO, and add caching to it this way. This would be a lot less boring coding upfront, but may become problematic when you do decide to change the database, or, worse, to have an option of switching implementations back and forth.)
One equally broadly used (but, in my opinion, inferior) alternative to the "factory" method is making the dao a member variable in all classes that need it:
public class App {
   GreatDao dao;
   public App(final GreatDao d) { dao = d; }
}

This way, the code that instantiates these classes needs to instantiate the DAO object (which could still use the factory) and provide it as a constructor parameter. The dependency injection frameworks I mentioned above, usually do something similar to this.
This provides all the benefits of the "factory method" approach, that I described earlier, but, as I said, is not as good in my opinion. The disadvantages here are having to write a constructor for each of your app classes, doing the same exact thing over, and over, also not being able to instantiate the classes easily when needed, and some lost readability: with a large enough code base, a reader of your code, not familiar with it, will have hard time understanding which actual implementation of the DAO is used, how it is instantiated, whether it is a singleton, a thread-safe implementation, whether it keeps state, or caches anything, how the decisions on choosing a particular implementation are made etc.