text:
Q: TypeScript error in passing props to child component in react I am building a expense tracker app using react + typescript
expense_type.ts
    export  type IState = {
    id : number,
    text : string,
    amount : number

}

export type IinitialStateType =  {
    transactions : IState[]
}

export type IActions =  {
    type : string,
    payload : any
}

export type contextProps = {
    transactions : IState[];
    addTransaction: (trans: IState) => void;
    deleteTransaction: (id: number) => void;
}

Then I have used API Context and reducer and initialize my initial states in Global State file
GlobalState.tsx
import React , {createContext,useReducer} from 'react'
import {IinitialStateType,contextProps} from '../Types/expense_type'
import AppReducer from './AppReducer'

const initailState : IinitialStateType = {
    transactions : [
          { id: 1, text: 'Flower', amount: -20 },
          { id: 2, text: 'Salary', amount: 300 },
          { id: 3, text: 'Book', amount: -10 },
          { id: 4, text: 'Camera', amount: 150 }
    ]
}

export const GlobalContext = createContext<Partial<contextProps>>({})

export const GlobalProvider : React.FC = ({children}) : JSX.Element => {

    const [state,dispatch] = useReducer(AppReducer,initailState)

    return(
        <GlobalContext.Provider value={{
            transactions : state.transactions
        }}>
            {children}
        </GlobalContext.Provider>
    )
}

Then I have used context in TransactionList.tsx component and map all the initial state values and pass those values to child component Transaction.tsx where those values are receiving
TransactionList.tsx
import React ,{useContext}from 'react'
import {GlobalContext} from './../Context/GlobalState'
import {contextProps,IinitialStateType,IState} from '../Types/expense_type'
import {Transaction} from './Transaction'

export const TransactionList : React.FC = () : JSX.Element => {

    const {transactions} : any = useContext(GlobalContext)
    return (
        <>

History

                {
                    transactions.map( (transaction : IState , index : number)  =>
                        (<Transaction key={index} transaction={transaction} />
                    ))
                 }

        </>
    )
}

Transaction.tsx
    import React from 'react'
    import {IinitialStateType} from '../Types/expense_type'
    export const Transaction : React.FC<IinitialStateType>= (props : any) : JSX.Element => {

    let sign : string = props.transaction.amount > 0 ? '+' : '-'

    return (
        <>
            <li className={props.transaction.ammount < 0 ? "minus" : "plus"}>
                {props.transaction.text}{" "}

                    {sign}${Math.abs(props.transaction.ammount)}

                <button
                    className="btn-delete"
                >
                    x
                </button>

        </>
    )
}

But while compiling it gives error in TransactionList.tsx file
TypeScript error in C:/Users/Abdul Rehman Aziz/Desktop/New folder/expense-tracker-ts/src/Components/TransactionList.tsx(14,88): Type '{ key: number; transaction: IState; }' is not assignable to type 'IntrinsicAttributes & IState & { children?: ReactNode; }'.   Property 'transaction' does not exist on type 'IntrinsicAttributes & IState & { children?: ReactNode; }'.  TS2322

    12 |
History

    13 |

  > 14 |                  { transactions.map( transaction => (<Transaction key={transaction.id} transaction={transaction} />)) }
       |                                                                                ^
    15 |

    16 |         </>
    17 |         </>

A: You have to specify the type of Props for React.FC, not state. Like this:
export const Transaction: React.FC<{ transaction: IState }> = (
  props: any

I have also made a working sample: https://codesandbox.io/s/focused-sanderson-e6zlm?file=/src/App.tsx

A: Your Transaction component is expecting props of type IinitialStateType and as per your definition of that type it does not has a property called transaction and as well it does not receive one item but an array. If you change the Type of your props in the Transaction component to something like
export const Transaction : React.FC<IState>= (props : any) : JSX.Element => {
...
}

it should help.


text:
Q: Deducing linear combinations of column matrices I've a $m \times n$ column matrix $A$ that can contain values {0,0.5,1}. i.e $\Omega = \{0,0.5,1\}$
$A$ =
$\begin{bmatrix}
0 & 0.5 & 0.5 & 1 & 1 & \cdots & 0 \\
0.5 & 0 & 1 & 1 & 0 & \cdots & 1 \\
\vdots & \vdots & \vdots & \vdots & \vdots  & \vdots \\
0 & 0 & 0.5 & 0.5 & 1 & \cdots & 0
\end{bmatrix}$
let the column matrix $x$ be equal to $\mathbb{R_0^{+ n \times 1}}$ (non-negative real numbers including 0)
$x$ =
$\begin{bmatrix}
 1 \\ 2 \\ 0 \\ 0.5 \\ 3 \\ \vdots \\ 0.3
\end{bmatrix}$
We know that $Ax = b$. So given $b$ we can find $x$ by $x = A \backslash b$ (performing matrix left division). 99.9% the matrix A is full rank (because it can contain only 3 values and $m$ is very large) but if not I could always use $x$ = pseudo-inverse$(A) \times b$.
My question is now if we are given $b$ and a matrix $A^{\prime}$ such that $A^{\prime} \supseteq A$ where $A^{\prime} \in \mathbb{R^{m \times \textbf{N}}}$ and $\textbf{N} \supseteq n$ and belong to the same domain as $A$ (pardon my math explanation. $A$ and $A^{\prime}$ has same rows but the columns of $A$ are $\subseteq$ of $A^{\prime}$  ), is it possible to find $x$ ? (Note that we do not need $A$, if a column in $A^{\prime}$ is involved in the linear combination it gets a value or else it can just be $0$).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why Z3 always return unknown when assertions have power? Here is the input
Example 1
(declare-var a Int)
(declare-var b Int)
(declare-var n Int)
(assert (= b (* a a)))
(assert (not (= b (^ a 2))))
(check-sat)

Example 2
(declare-var a Int)
(declare-var b Int)
(declare-var n Int)
(assert (= b (* (^ a n) a)))
(assert (not (= b (^ a (+ n 1)))))
(check-sat)

It returns unknown almost instantaneously.

A: Your problem falls into the fragment known as non-linear integer arithmetic, which is undecidable. That is, there is no decision procedure to determine the satisfiability of your query. (Non-linear means, basically, there is a multiplicative term involving at least two variables.)
Having said that, most solvers do have heuristics to answer queries involving non-linear arithmetic, and Z3 is no exception. Of course, being a heuristic, it may or may not produce an answer. This is what you are observing, alas it appears the default tactics Z3 uses is just not sufficient for your problems.
As a common trick, you can try Z3's non-linear real-arithmetic solver for these sorts of problems. Instead of check-sat, use:
(check-sat-using qfnra-nlsat)

In this case, Z3 tries to solve the benchmark assuming the inputs are reals, and sees if the solution is actually integer. This trick can successfully resolve some integer-nonlinear arithmetic queries, though of course not always. For instance, if you try qfnra-nlsat on your first example you'll see that it successfully solves it, but it still answers unknown for the second one.
For details on non-linear integer arithmetic and Z3, see here: How does Z3 handle non-linear integer arithmetic?


text:
Q: Makefile doesn't "stack" my output in a .txt file So, I'm trying to create a makefile that runs my program 5x for each of my parameters (that is 6), and for each of these 6 parameters, the makefile creates a new .txt (my output). But for some reason all of my outputs shows only one result.
for t in 2 4 8 16 32 64 ; do \
        #n=1 ; while [ $${n} -le 5 ] ; do \
        for n in 'seq 1 5' ; do \
            OMP_NUM_THREADS=$$t ./cowichan_openmp norm >> normOut$$t.txt ; \
        done ; \
    done ;

A: Transferring gist of comments into an answer.
On the face of it, you have for n in 'seq 1 5' ; do and the single quotes mean that the loop is executed once and n has the value "seq 1 5".
You need back-ticks `…` or $$(…) (the double-dollar gets around make expanding macros; the shell sees $(…)).  Or even just:
for n in 1 2 3 4 5; do \

Where's the typo — in the question or the makefile you copied it from?
If you add a line:
echo $$t $$n; \

before (or after) the OpenMP line (to the recipe copied from the question), you'll see what I mean.


text:
Q: How to fix the error that "input tensor must have rank 4"? X_train shape :  (13973, 100, 6, 5)
X_test shape :  (3494, 100, 6, 5)
y_train shape :  (13973, 6, 5)
Y_test shape :  (3494, 6, 5)

Code:
model = Sequential()
model.add(TimeDistributed(Conv2D(32,5,5,input_shape=(100,6,5))))
model.add(TimeDistributed(MaxPooling2D(pool_size=(4,4))))
model.add(Activation('relu'))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(256, return_sequences=True))
model.add(TimeDistributed(Dense(5)))
model.add(Activation('softmax'))
model.compile(loss="mse",optimizer="adam")

Getting the error of

input tensor must have rank 4?


text:
Q: How do I make an instance of a class availabile in different methods? I have created an instance of the class DownloadManager in a method (private void jButton2ActionPerformed) and need to access it in another method?
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    //need to access the instance dman here
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    DownloadManager dman = new DownloadManager();
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
    dman.setVisible(true);
}

A:
"If you want to be able to access a variable from two different methods, define the variable in the enclosing scope of the method." -Sweeper

Which basically means you should "drag" the variable outside of the methods:
DownloadManager dman = new DownloadManager(); //Should put the variable here!
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    //need to access the instance dman here
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    //DownloadManager dman = new DownloadManager(); I moved this line to above!
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
    dman.setVisible(true);
}

That's very simple isn't it?
Alternatively, you can create a class for getting the download manager:
public final class DownloadManagerUtility {
    private DownloadManagerUtility () { // private constructor so that people don't accidentally instantiate this

    }

    private DownloadManager dman = new DownloadManager();
    public static void getDownloadManager() { return dman; }
}

The advantage of this is that you can add more methods that are related to download manager in a separate class, which increases maintainability.


text:
Q: Replacing multiple classes in multiple HTML DOM elements with JavaScript? So I have a few elements:
HTML:
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>

As you can see, these buttons have the class btn-post and when someone clicks a button and activates an event.
I want to replace all the btn-post classes with btn btn-success (btn and btn-success)
Any helpful advice?

A: Try something like this

const btns = document.querySelectorAll(".btn-post")

btns.forEach(btn => {
  btn.onclick = () => btns.forEach(_btn => _btn.className = "btn btn-success")
})
.btn-post {
  background-color: black;
  color: white;
}

.btn-success {
  background-color: green;
}
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>

A: You can use javascript to do so.
var elems = document.getElementsByClassName("btn-post");

for(var i = 0; i < elems.length; i++) {
    elems[i].className = "btn btn-success";
}

A: You can get all the elements with class bln-post, and create an array from it. You can then edit the class names using classList API.

const elems = document.getElementsByClassName('btn-post')

Array.from(elems).forEach(el => {
  el.classList.remove('btn-post');
  el.classList.add('btn');
  el.classList.add('btn-success');
})
.btn-success {
  color: green
}
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>


text:
Q: How to implement connection failover in client side I am trying to implement connection failover in android application. Basically I have list of URLs which application connect using websocket, In case of unable to connect with any url I need to try a second connection. API which I am using to connect with websocket in android side is not synchronous. so when I start connect to websocket after executing this method I dont know either connection establish or not until OnOpen method called and then I set some boolean there to use further.
What I tried: One solution in my mind is to start to call connect method from a thread and sleep this for certain time if OnOpen method called within timespan is ok otherwise try to use second connection url.
Can someone give me hint how I can resolve this. Here is a sample code (without thread implementation):
 private DataUploader() {

    // test list of url
    urlList = new ArrayList<String>();
    urlList.add("192.168.220.197:9001/observation/");
    urlList.add("192.168.220.197:9002/observation/");
    urlList.add("echo.websocket.org");

    connectWebSocket();
 }

public void connectWebSocket() {
    if (urlList.size() > -1) {
        String url = urlList.get(index);
        this.connect(url);
        index++;

    }
}

private void connect(String websocketEndPointUrl) {
    URI uri;
    try {
        websocketEndPointUrl = "ws://" + websocketEndPointUrl;
        uri = new URI(websocketEndPointUrl);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }

    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");
             isReady = true;
        }

        @Override
        public void onMessage(String s) {
           ///

        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };

    mWebSocketClient.connect();

}


text:
Q: Using a join in Hibernate HQL update query string query = "update User u set u.PointsTotal = 1 join u.Rounds r where r.RoundId = :round and (r.Row1 & :val) > 0";

NHibernateSession.CreateQuery(query)
    .SetByte("val", (byte)val)
    .SetInt32("round", roundId)
    .ExecuteUpdate();

Just gives me "The given key was not present in the dictionary."
And yes, the relations works as expected, can do selects....

A: Ok solved this one, seems like you have to do a subquery...
string query = "update User u set u.PointsTotal = 1 where u.Id in (select u2.Id from User u2 join u2.Rounds r where r.RoundId = :round and (r.Row1 & :val) > 0)";

NHibernateSession.CreateQuery(query)
    .SetByte("val", (byte)val)
    .SetInt32("round", roundId)
    .ExecuteUpdate();


text:
Q: How can i make my C++ code buildable with clang on Mac? I have a bunch of .cpp and .c files and i use gcc/make to build a project. On Mac there is only gcc 4.2. It is very old and puts a lot of limitations on the language. I've heard clang is the default compiler for Mac. How can i change my makefiles to use clang?

A: For starters, GCC 4.2 is not "very old and puts a lot of limitations on the language."
That being said, your Mac, if it has GCC 4.2 installed, should also have clang installed.  Xcode includes both clang and GCC (built with LLVM), as clang and gcc/g++ respectively.  Either:

*

*change your makefiles to point to clang directly

*set the CC environment variable to clang

*soft link g++ to clang if you want to be really hamfisted about it.

Any one should do the trick.

A: You could try replacing CC=g++ with CC=clang in you makefiles or doing
CC=clang make instead of make
and see if it compiles.
If you use gnu c/c++ extensions or gcc command line options it may not compile, in that case you can try googling for help.


text:
Q: Can I do prompt-learning on HuggingFace Transformers? I'm trying to solve a Prompt Learning task, but I'm not finding information on how to do it with HuggingFace Transformers. However, I've been thinking about it, and doing prompt-learning is basically fine-tuning a masked language model, but only over a set of possible values for those masks, instead of using the masks provided by the tokenizer straight out of the box. Is there a way of doing that, e.g., to fine-tune a masked language model that only calculates the logits for a set of predefined words?
I've tried OpenPrompt, but I didn't quite like it, that's why I'm trying to use Huggingface.
Cheers!


text:
Q: .htaccess: Redirect from subdomain to domain with get-request I'm trying to redirect from m.subsub.subdomain.tld to subsub.subdomain.tld?m=true. So basically, I want to add a GET-request. The existing GETs should stay like they are, so m.subsub.subdomain.tld?abc=def to subsub.subdomain.tld?abc=def&m=true.
I tried the following code but it doesn't work:
RewriteEngine On
ReWriteCond %{HTTP_HOST} m.subsub.subdomain.tld
ReWriteCond %{REQUEST_URI} ^m/
ReWriteRule ^(.*)$ ?=m=true[L]

I tried to understand how the ReWriteCond and ReWriteRule works, but I didn't get that, so I need your help.

A:
ReWriteCond %{HTTP_HOST} m.subsub.subdomain.tld
ReWriteCond %{REQUEST_URI} ^m/
ReWriteRule ^(.*)$ ?=m=true[L]

This has a number of issues:

*

*The REQUEST_URI holds the URL-path (starting with a slash), so I'm not sure what you are trying to match with ^m/?

*m.subsub.subdomain.tld - The second argument to the RewriteCond directive is a regular expression. The dots need to be backslash escaped in order to match a literal dot, otherwise it matches any character.

*You are capturing the URL-path with (.*) - is this required? It's not required in your example. Your example source and target URLs have an empty URL-path.

*?=m=true[L] - You have an erroneous = before the m. You are missing a space delimiter before the RewriteRule flags ([L]) - this will be seen as part of the substitution.

*Since you don't specify a (valid) R flag, or a scheme+hostname, this will result in an internal rewrite, not a redirect.

*If you want to redirect to a different host, you need to specify this in the substitution.

*The original query string will be discarded unless you explicitly include the QSA (Query String Append) flag.

*ReWriteCond and ReWriteRule should be written RewriteCond and RewriteRule respectively. Although that is just convention, it's not an error.

Try something like the following instead:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^m\.subsub\.subdomain\.tld [NC]
RewriteRule ^ http://subsub.subdomain.tld?m=true [R=302,QSA,L]

The existing GETs should stay like they are, so m.subsub.subdomain.tld?abc=def to subsub.subdomain.tld?abc=def&m=true

Note that this will result in the query string being the other way round. ie. the existing query string from the request will be appended, not prefixed onto the new query string. Is that a problem? ie. ?m=true&abc=def, not ?abc=def&m=true.
This is also a temporary (302) redirect. Change it to 301 (permanent) only when you are sure it's working OK (if this intended to be permanent).


text:
Q: Object Variable or With block variable not set mid-loop The issue I've got here is that
iRow = PullRange.Find(What:=a(x, 0)).Row - 1

Throws above mentioned error in the middle of a loop. The thing is it works for the first handful of iterations of x, but at x = 11/iRow = 30 it breaks and I've no clue why. There's nothing unique about that particular row and yet it crashes, has anyone any clue as to why?
Let me know if more info is needed.
Public Sub DataDump(Sql As String, PullColumn As String)
Dim a() As Variant
Dim iRow As Integer
Dim PullRange As Range
Dim DumpRange As Range
Dim x As Integer
Dim y As Integer

Set PullRange = Range(PullColumn & ":" & PullColumn)
Set DumpRange = Range("H1")

Set recs = New ADODB.Recordset

recs.Open Sql, con, adOpenDynamic

a = recs.GetRows

'a(y, x)

For x = 0 To UBound(a, 2)
  If IsNull(a(0, x)) Then GoTo none
    iRow = PullRange.Find(What:=a(0, x)).Row - 1
        If iRow = 0 Then GoTo none
    For y = 1 To UBound(a, 1)
        Debug.Print a(y, x)
        If IsNull(a(y, x)) Then GoTo Err
        DumpRange.Offset(iRow, y) = a(y, x)
Err:
    Next y
none:
Next x

End Sub

A: @Rory Was right. Unclean data caused the loop to break and I couldn't see the difference because the difference was minute, after inserting data set anew from the same source it fixed itself. Lesson learned.


text:
Q: Separar conteúdo de uma coluna em outras colunas Tenho um arquivo em forma de tabela. Preciso separar o conteúdo de uma coluna específica em outras colunas, os dados são separados por ;.
Bem eu consegui fazer isto, mas o problema é que o conteúdo resultará para cada linha um número diferente de colunas. E por este código ele replica até o conteúdo até atingir o número de colunas. Eu queria que ele exibisse NA.
Pelo meu código obtenho isto:
  v1      v2      v3    p/sep  sep sep  sep sep
dados1  dados2  dados3  a;b;c   a   b   c   a
dados1  dados2  dados3  a;c     a   c   a   c
dados1  dados2  dados3  a       a   a   a   a
dados1  dados2  dados3  a;b     a   b   a   b
dados1  dados2  dados3  a;b;c;d a   b   c   d
dados1  dados2  dados3  a;b     a   b   a   b

Mas o resultado que espero ter é:
  v1      v2      v3 separar  sep sep   sep sep
dados1  dados2  dados3  a;b;c   a   b   c   NA
dados1  dados2  dados3  a;c     a   c   a   c
dados1  dados2  dados3  a       a   NA  NA  NA
dados1  dados2  dados3  a;b     a   b   NA  NA
dados1  dados2  dados3  a;b;c;d a   b   c   d
dados1  dados2  dados3  a;b     a   b   NA  NA

library(reshape)
file_split = data.frame(file,colsplit(file$separar,split=";",names="buffer",))

A: Você esteve muito próxima da solução. Se ao invés do reshape utilizar o reshape2, utilizando a mesma função (trocando o argumento split por pattern), você chega próxima do que gostaria:
> file <- read.table(text="  v1      v2      v3    separar  sep sep  sep sep
dados1  dados2  dados3  a;b;c   a   b   c   a
dados1  dados2  dados3  a;c     a   c   a   c
dados1  dados2  dados3  a       a   a   a   a
dados1  dados2  dados3  a;b     a   b   a   b
dados1  dados2  dados3  a;b;c;d a   b   c   d
dados1  dados2  dados3  a;b     a   b   a   b", header=T, as.is=T)[,1:4]
> library(reshape2)
> file_split = data.frame(file, colsplit(file$separar, pattern=";", names=paste0("sep", 1:4)))

Resultando em
> file_split
      v1     v2     v3 separar sep1 sep2 sep3 sep4
1 dados1 dados2 dados3   a;b;c    a    b    c
2 dados1 dados2 dados3     a;c    a    c
3 dados1 dados2 dados3       a    a
4 dados1 dados2 dados3     a;b    a    b
5 dados1 dados2 dados3 a;b;c;d    a    b    c    d
6 dados1 dados2 dados3     a;b    a    b

Isso é uma questão de definição padrão da função. Em ambos pacotes, não é possível controlar o comportamento para número de colunas diferentes, mas o reshape usa reciclagem, enquanto o reshape2completa com strings vazias. Para substituir os espaços vazios por NA, você pode fazer, por exemplo:
> file_split[file_split == ""] <- NA
> file_split
      v1     v2     v3 separar sep1 sep2 sep3 sep4
1 dados1 dados2 dados3   a;b;c    a    b    c <NA>
2 dados1 dados2 dados3     a;c    a    c <NA> <NA>
3 dados1 dados2 dados3       a    a <NA> <NA> <NA>
4 dados1 dados2 dados3     a;b    a    b <NA> <NA>
5 dados1 dados2 dados3 a;b;c;d    a    b    c    d
6 dados1 dados2 dados3     a;b    a    b <NA> <NA>

Só é importante tomar cuidado aqui pois essa substituição troca todos os valores "" da tabela, talvez seja mais seguro usar os nomes/índices das colunas para não correr o risco de alterar outros dados que deveriam se manter vazios e não NA (se houver).

Antes de achar essa diferença do reshape2 eu fiz uma alternativa usando base e seguindo essa dica. Não é tão sucinta, mas já que está pronta, segue abaixo:
> file.split <- strsplit(file$separar, ";")
> n.obs <- sapply(file.split, length)
> seq.max <- seq_len(max(n.obs))
> resultado <- cbind(file, t(sapply(file.split, "[", i = seq.max)))
> resultado
      v1     v2     v3 separar 1    2    3    4
1 dados1 dados2 dados3   a;b;c a    b    c <NA>
2 dados1 dados2 dados3     a;c a    c <NA> <NA>
3 dados1 dados2 dados3       a a <NA> <NA> <NA>
4 dados1 dados2 dados3     a;b a    b <NA> <NA>
5 dados1 dados2 dados3 a;b;c;d a    b    c    d
6 dados1 dados2 dados3     a;b a    b <NA> <NA>

A: A maior dificuldade é fornecer nomes para as novas colunas. Vou adotar a mesma variável file e o mesmo esquema para os nomes das colunas que o Molx utilizou.
Caso saiba de antemão o número de colunas contido em separar. (4, nesse caso)
colunas <- paste0("sep", 1:4)

O número de colunas pode ser obtido por meio da função str_count do pacote stringr.
library(stringr);
colunas <- paste0("sep", 1:(max(str_count(file$separar, ';')) + 1));

Agora é possível dividir a coluna separar utilizando a função separate do pacote tidry.
library(tidyr);
separate(file, separar, into = colunas, sep = ';', remove = FALSE,
         extra = "merge");

A: library(reshape)
file_split = data.frame(file,colsplit(file$separar,split=";",names="buffer",))

Para colocar nome nas duas colunas precisa alterar o final names = c("Buffer", "Buffer2"))
Ou seja, fica assim
library(reshape)
file_split = data.frame(file,colsplit(file$separar,split=";",names= c("buffer","Buffer2")))


text:
Q: Kill all running threads I can do show full processlist to get all the data of the running threads. However, is there a way to just get the thread_id so I can do a concat to generate a "kill" statement? Currently, I have to copy and paste everything into a text editor to append the "kill" command for each thread id. For example, to do something like:
select concat('call mysql.rds_kill(', id, ');') from (
    show full processlist
);

Then I could copy paste what it generates to kill all the running threads.

A: If you want to kill all running mysql processes, try this:
for process in `ps -ef|grep mysql |awk -F" " '{print $2}'`
do
kill -9 $process
done

Let me know if it works.


text:
Q: DllImport - function not returning the correct value in ASP.Net when deployed to IIS I have a web service that I need to make a call to a function in some unmanaged code, I import the dll like:
     class myClass
    {
      [DllImport("mydll.dll")]
      public static extern int FetchMyData(int DataType, int DataIndex);
    }

The web page does an AJAX callback to a WebService which calls the imported function like:
    [WebMethod]
    public int FetchData(int IndexValue)
    {
      return  myClass.FetchMyData(DATA_TYPE, IndexValue);
    }

When I run this from VisualStudio using the development IIS Express, everything works fine, and the function returns a positive integer. However, when I deploy to my local IIS, the function always returns -1. It doesn't even throw an exception which seems a bit odd.
Things I have tried but didn't make any difference:

*

*added the "IIS AppPool\DefaultAppPool" to the parent directory with full permissions

*set the "Enable 32-Bit Applications" property to True
EDIT
After further investigation and help from the various comments below it became clear that the issue here was not the function failing, rather a permissions related issue with what the dll function was doing, namely accessing a Memory Mapped File. I have created this follow-up post which replicates the core problem with sample code.


text:
Q: How can I grab a URL parameter from a response using AWS API Gateway? I am trying to use AWS API Gateway to call an external API endpoint in order to perform an oauth2 handshake.
The remote API responds to a GET request with a URL with a code parameter in the URL.
I would like to be able to grab that code parameter content in order to use it for the second part of the handshake, but I don't see a way to get the content in the Integration Response method of AWS API Gateway.
Any tip in the right direction will be appreciated

A: Use API Gateway. If you'd like, you can get very detailed about what parameters are accepted, how they are parsed and in turn passed to Lambda, but at its simplest, you can define your resource method to simply 'proxy' the request for Lambda by selecting Use Lambda Proxy integration at the Integration Request portion of the method definition.
With this configuration, the Lambda function receives the entire request, query parameters and all, in the event object. Query parameters can be accessed in the queryStringParameters attribute.


text:
Q: android: How to get item's attributes from its string-array in strings.xml My dad likes to watch his movies and he has a lot of them.  He keeps his discs in several binders but there is no system of cataloging at all.
I thought I'd make an android app to help him find them
So i thought id store the information in a string array in strings.xml
        <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MovieFinderActivity!</string>
    <string name="app_name">MovieFinder</string>
    <string name="movie_prompt">Choose Movie</string>
    <string-array name="all_movies_array">
        <item binder="1" page="1">Star Wars Episode 1: The Phantom Menace</item>
        <item binder="1" page="1">Star Wars Episode 2: Attack of the Clones</item>
        <item binder="1" page="1">Star Wars Episode 3: Revenge of the Sith</item>
        <item binder="1" page="1">Star Wars Episode 4: A New Hope</item>
        <item binder="1" page="2">Star Wars Episode 5: The Empire Strikes Back</item>
        <item binder="1" page="2">Star Wars Episode 6: Return of the Jedi</item>
        <item binder="1" page="2">Dr Zhivago Side A</item>
        <item binder="1" page="2">Dr Zhivago Side B</item>

    </string-array>

</resources>

then i did this
    movie_spinner = (Spinner) findViewById(R.id.search_movie_spinner);
    movie_spinner.setAdapter(adapter2);
    movie_spinner.setOnItemSelectedListener((OnItemSelectedListener) this);

and this gets called here
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {

    //movie_title is a textview
    movie_title.setText( movie_spinner.getSelectedItem() + "");

}

so whenever a movie gets selected in the spinner, the TextView of movie_title changes to the movie's name
What i want to know is how to retrieve the attributes of binder and page from the node item

A: AFAIK, you are not able to get attribute values for the resources string array.
The way I see it is that you can have the following options

*

*Create an xml file with you data as sherif mentioned.
Eg,
<movies>
   <item binder="1" page="1">Star Wars Episode 1: The Phantom Menace</item>
   <item binder="1" page="1">Star Wars Episode 2: Attack of the Clones</item>
   <item binder="1" page="1">Star Wars Episode 3: Revenge of the Sith</item>
   <item binder="1" page="1">Star Wars Episode 4: A New Hope</item>
   <item binder="1" page="2">Star Wars Episode 5: The Empire Strikes Back</item>
</movies>

You could use any f the avaliable parsers like DOM,SAX to parse this and create an arraylist or object of your choice.

*Create json data instead of xml and use GSON to parse to to a usable object.


text:
Q: Please be sure a sound file exists at the specified location i developed a simple app to play music.
When i run it on debug it works just fine. But after i published it as an application and install it on another machine, it won't run because the file paths is not recognized.
Here is my code:
SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"C:\Users\chris\source\repos\Aplikasi Reminder\Aplikasi Reminder\Resources\mixkit-correct-answer-tone-2870.wav";
player.Play();

I tried to change the paths into:
player.SoundLocation = @"Aplikasi_reminder.Properties.Resources.mixkit-correct-answer-tone-2870.wav";

and it won't too..
Please can someone tell me how to fix that, thank you..

A: Include your files in the project`s resources folder by right-clicking on your project name>>properties>>Recources>>select audio>>drag your .wav file.
Then you can play the file from Memory Stream:
public void Play()
{
    SoundPlayer player = new SoundPlayer();
    player.Stream = YOUR_PROJECT_NAME.Properties.Resources.YOUR_FILE_NAME;
    player.Play();
}


text:
Q: Nginx error page when error page does not exist I would like to have custom error pages for each domain that is hosted on my server.
I have a directory structure like the following
data
   defaults
      error.html
   example.com
      misc
         error.html
   example.net
   ...

Now i would like to show misc/error.html if it is there for the domain name being accessed and else display default/error.html.
What i currently have what isn't working is the following. It doesn't work because it just displays the default nginx 404 page if the error page (misc/error.html) is not found (even when the error isn't even a 404 error).
    server_name ~^(www\.)?(?<domain>.+)$;

    location / {
        root /data/$domain;
        try_files $uri $uri/ =404;
        index index.html index.htm index.php;
    }

    error_page 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 421 422 423 424 425 426 428 429 431 451 500 501 502 503 504 505 506 507 508 510 511 @error;
    location @error {
        internal;
        ssi         on;
        auth_basic  off;
        root        /data;
        try_files   /$domain/misc/error.html /defaults/error.html;
    }

A: The very last try_files parameter is treated differently from all the others. If you read the documentation carefully you'll find it can be an HTTP error code, a named location ID or a new URI to re-evaluate, and your /defaults/error.html is treated as a new URI. Then nginx tries to serve it via the main location / { ... } searching the error.html file under the /data/$domain/defaults directory. And since the /data/$domain/defaults/error.html file does not exists, it returns a built-in 404 error page (it will not try the custom error page twice). Changing your try_files directive from the error handler to something like
try_files /$domain/misc/error.html /defaults/error.html =404;

should fix the situation.


text:
Q: Is it advisable to have a dedicated count field in a SQL table? I'm working in a GraphQL API that queries a PostgreSQL database.
Two of the tables that are already created are:

*

*users

*users_follow

In the second table we store two foreign keys for two distinct users, which means that the first one is following the second one.
My colleague in the front end told me that would be handy for him to have a "followersCount" field in the user schema in order not to query all the followers of a user just to know how many he has.
My naive (or not) solution was to set up two triggers in the db, one increments the counter in the table user if one new follower was inserted in "users_follow" and one decrements it if one deletion happens.
Is it ok for scalability to have such a setup? Should I just "count()" to satisfy the "followersCount" in the schema?

A: There is an old saying:

Premature performance optimization is the root of all evil.

Well, I suppose the world would be a much better place if this were literally true.  But there is a grain of truth.
So, start by creating the code and trying to optimize the queries, using indexes and partitions.
Then, you can address other solutions, including triggers, materialized views, and wrapping DML operations in stored procedures (similar to triggers but easier to maintain in my opinion).

A: well this should be optimal:
select count(user_2) as cnt from users_follow where user_1 = ?.

you could wrap it as a callable function get_user_follower_count( x ) to make it easy on the other guy.


text:
Q: Should all business logic be in domain models or? ASP.NET MVC4 - Basically I used to have all my business logic in my controllers (which I'm trying to put into the domain models instead).
However I don't quite know if ALL my business logic should be put into the domain models or if some should remain in the controllers?
For instance I got a controller action as shown below:
[HttpPost]
    public ActionResult Payout(PayoutViewModel model)
    {
        if (ModelState.IsValid)
        {
            UserProfile user = PublicUtility.GetAccount(User.Identity.Name);
            if (model.WithdrawAmount <= user.Balance)
            {
                user.Balance -= model.WithdrawAmount;
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();

                ViewBag.Message = "Successfully withdrew " + model.WithdrawAmount;
                model.Balance = user.Balance;
                model.WithdrawAmount = 0;
                return View(model);
            }
            else
            {
                ViewBag.Message = "Not enough funds on your account";
                return View(model);
            }
        }
        else
        {
            return View(model);
        }
    }

Now should all the logic be put into a method in a domain model so the action method looks like this?
[HttpPost]
    public ActionResult Payout(PayoutViewModel model)
    {
        var model = GetModel(model);
        return View(model);
    }

Or how would you go around doing it?

A: For me, the separation of concerns is the most important guiding principle for these decisions.  So, it depends on how complex your domain is and what benefit you get from complicating the code.
Anyway, as a general rule, I tend to give Controllers the following concerns:

*

*Instantiation and mapping of view models (unless there is considerable mapping)

*View model validation

And, I tend to refer to a model (or service) for non-application specific domain knowledge:

*

*Can withdraw money

*Make withdrawal

So, this is how I would split the code:
    [HttpPost]
    public ActionResult Payout(PayoutViewModel model)
    {
        if (ModelState.IsValid)
        {
            var account = accountRepository.FindAccountFor(User.Identity.Name);

            if (account.CanWithdrawMoney(model.WithdrawAmount))
            {
                account.MakeWithdrawal(model.WithdrawAmount);

                ViewBag.Message = "Successfully withdrew " + model.WithdrawAmount;
                model.Balance = account.Balance;
                model.WithdrawAmount = 0;
                return View(model);
            }

            ViewBag.Message = "Not enough funds on your account";
            return View(model);
        }
        else
        {
            return View(model);
        }
    }

The saving of the application state, I usually wrap up in an interceptor.  That way you can wrap a unit of work transaction around the entire request.

A: I would put all the logic in the domain model, and do two calls to the domain, one for validation, one for executing the use case.
So the entity looks like this:
public class User
{
    public double Balance { get;set; }

    public ValidationMessageCollection ValidatePayout(double withdrawAmount)
    {
        var messages = new ValidationMessageCollection();

        if (withdrawAmount > Balance)
        {
            messages.AddError("Not enough funds on your account");
        }

        return messages;
     }

     public void Payout(double withdrawAmount)
     {
         balance -= withdrawAmount;
     }
 }

And your controller would look like this:
[HttpPost]
public ActionResult Payout(PayoutViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var user = PublicUtility.GetAccount(User.Identity.Name);
    var validationMessages = user.ValidatePayout(model.WithdrawAmount)

    if(validationMessages.Any())
    {
        ViewBag.Message = validationMessages.ToSummary();
        return View(model);
    }

    ViewBag.Message = "Successfully withdrew " + model.WithdrawAmount;
    model.Balance = user.Balance;
    model.WithdrawAmount = 0;
    return View(model);
}

There are other things I would do, like insert an application/service layer, use viewModels and do all the resetting of the ViewModel in a ViewModelBuilder/Mapper or simmilar, but this shows the basic idea.

A: We put our application and business logic into separate layers (csproj file) a domain layer for business logic and a service layer for application logic.  This abstracts them out from the MVC project completely.  This has two big benefits for us.  The first is that the business logic isn't tied to a pattern that could change. A few years ago none of us would have imagined the popularity of MVC today, and in a a few years we don't know if there will be some new thing that will come along and replace MVC so getting the vast majority of your code to be "un-tied" to MVC would help should you ever want to abandon MVC for something else.
The second benefit is it makes having different presentation layers very easy to implement.  So if you wanted to present your business logic as a WCF service you could do that very easily by creating a new WCF project and making that a façade for your Service and domain layers.  It makes maintenance very easy since both your MVC project and your WCF service would be using the same Business Logic classes.
Example
Below is some example code of what I would do.  This is quick and dirty and there should be more to it like adding logging if the user doesn't save back to the database etc...
public enum PayoutResult
{
    UserNotFound,
    Success,
    FundsUnavailable,
    DBError
}

public class UserProfile
{
    public float Balance { get; set; }

    public string Username { get; set; }

    // other properties and domain logic you may have

    public bool Withdraw(PayoutModel model)
    {
        if (this.Balance >= model.Amount)
        {
            this.Balance -= model.Amount;
            return true;
        }

        return false;
    }
}

public class PayoutService
{
    IUserRepository userRepository;

    public PayoutService()
    {
        this.userRepository = new UserRepository();
    }

    public PayoutResult Payout(string userName, PayoutModel model)
    {
        var user = this.userRepository.GetAll().SingleOrDefault(u => u.Username == userName);
        if (user == null)
        {
            return PayoutResult.UserNotFound;
        }

        // don't set the model properties until we're ok on the db
        bool hasWithdrawn = user.Withdraw(model);
        if (hasWithdrawn && this.userRepository.SaveUser(user))
        {
            model.Balance = user.Balance;
            model.Amount = 0;

            return PayoutResult.Success;
        }
        else if (hasWithdrawn)
        {
            return PayoutResult.DBError;
        }

        return PayoutResult.FundsUnavailable;
    }
}

Your controller would now look like this
[HttpPost]
public ActionResult Payout(PayoutModel model)
{
    if (ModelState.IsValid)
    {
        var result = service.Payout(User.Identity.Name, model);
        // This part should only be in the MVC project since it deals with
        // how things should be presented to the user
        switch (result)
        {
            case PayoutResult.UserNotFound:
                ViewBag.Message = "User not found";
                break;
            case PayoutResult.Success:
                ViewBag.Message = string.Format("Successfully withdraw {0:c}", model.Balance);
                break;
            case PayoutResult.FundsUnavailable:
                ViewBag.Message = "Insufficient funds";
                break;
            default:
                break;
        }
    }

    return View(model);
}

And if you had to expose the payout in a web service (I work in an enterprise environment so this happens a lot for me)  You do the following...
public class MyWCFService : IMyWCFService
{
    private PayoutService service = new PayoutService();

    public PayoutResult Payout(string username, PayoutModel model)
    {
        return this.service.Payout(username, model);
    }
}

A: The approach which we follow has required business cases enclosed within ViewModel (Your case: PayoutViewModel) and exposed through method and these method will be consumed within controller actions. In addition, we have a clear seperation on model and view model where viewmodel refer model within it.

A: It is recommended that you have a thin code on controllers , it's better you handle business logic in another layers like serviceLayer that i have used it before which the returns you a view model of what you have wanted to return to your view/controller. Even define your ajax methods inside a service layer class.Which decrease code complexity and maintainability problems.Even it is more readable ..
In you Controller you can use DI to inject the serviceLayer class or instansiate it as
  ServiceLayer test = new ServiceLayer() ;

then in you controller
  test.registerCustomer(model); // or
  test.registerCutomer(CustomerViewModel);


text:
Q: Passing variable to cut() in ggplot2's aes() I'm trying to use ggplot2 to draw a histogram that has different colour-bars for different intervals of x.
After referring to Hadley's solution in: how to define fill colours in ggplot histogram?, I arrived at the following:
library(ggplot2)

set.seed(1)
a <- seq(from=1, to=10000)
b <- rnorm(10000)
c <- data.frame(a,b) # Convert to DF

ggplot(c, aes(x=b, fill=cut(..x.., breaks=c(-2, -1, -0.5, 0, 0.5, 1, 2)))) +
  geom_histogram(binwidth=0.1, color="steelblue")

However, when I try to define the break points into a variable, MyBreaks, to be passed into aes(), I get an error: "Error in cut.default(x, breaks = MyBreaks) : object 'MyBreaks' not found."
My code that generated the error:
MyBreaks <- c(-2, -1, -0.5, 0, 0.5, 1, 2)
ggplot(c, aes(x=b, fill=cut(..x.., breaks=MyBreaks))) +
  geom_histogram(binwidth=0.1, color="steelblue")

I did some research on similar errors encountered by other users, but the solutions did not seem to work for me.
For instance, the solution in How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.) gave: "Error: Aesthetics must either be length one, or the same length as the dataProblems:MyBreaks". My code is:
ggplot(c, aes(x=b, MyBreaks1=MyBreaks, fill=cut(..x.., breaks=MyBreaks1))) +
  geom_histogram(binwidth=0.1, color="steelblue")

I then tried the solution in Local Variables Within aes but this gave the same: "Error in cut.default(x, breaks = MyBreaks) : object 'MyBreaks' not found". My code is:
.e <- environment()
ggplot(c, aes(x=b, fill=cut(..x.., breaks=MyBreaks)), environment = .e) +
  geom_histogram(binwidth=0.1, color="steelblue")

I have done basic programming before but R's learning curve is real steep! Would appreciate if someone can help!
Thanks in advance!

A: This is from Roland's comment here How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.).
ggplot(c, aes(x=b, fill=cut(..x.., breaks=get("MyBreaks", envir=.GlobalEnv)))) +
geom_histogram(binwidth=0.1, color="steelblue")


text:
Q: Mysql MySQL or PHP Transform rows to two columns dynamically I have the same scenario as I have in MySQL or PHP Transform rows to columns
But I have to restructure my table now and this is the output

It's pretty much the same with the link above but I to include the AS_amount.anyone can help me?
I want the result below but with AS_month_2016...etc in the right side of each FA_mont2016

This is my code:
CREATE DEFINER=`root`@`localhost` PROCEDURE `display_annualize_table`()
BEGIN
SET group_concat_max_len=10028;
SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT CONCAT(
      'MAX(IF(month = ''',
      month,
      ''' and year(date) = ',
      year(date),

      ', FS_amount, NULL)) AS `',
      CONCAT('FA_',month),
      '_',
      year(date),

      '`')
    order by date
  ) INTO @sql
  FROM tmp_results;

  if coalesce(@sql,'') != '' then
    set @sql = concat(', ', @sql);
  end if;

  SET @sql = CONCAT(
    'SELECT r.account as Account,
     r.region as Region ',
     coalesce(@sql,''),
    'FROM tmp_results r
     LEFT JOIN accounts AS a
     on r.account_id = a.id
     GROUP BY r.account, r.region
     ORDER By r.account_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

Need your help please. Thank you in advance!

A: It's works the same way as FS_amount, just add the new columns to your code that generates the dynamic columns:
  SELECT GROUP_CONCAT(DISTINCT CONCAT(
      'MAX(IF(month = ''',
      month,
      ''' and year(date) = ',
      year(date),
      ', FS_amount, NULL)) AS `',
      CONCAT('FA_',month),
      '_',
      year(date),
      '`, ',
      'MAX(IF(month = ''',
      month,
      ''' and year(date) = ',
      year(date),
      ', AS_amount, NULL)) AS `',
      CONCAT('AS_',month),
      '_',
      year(date),
      '`'
      )
    order by date
  ) INTO @sql
  FROM tmp_results;

You should have a look at the code the statements create (e.g. by temporary adding a select @sql;), although it should be pretty straight forward to add even more columns in case you'll need them.


text:
Q: new operator and array in C++ What is the meaning of this line:
int* p = new int[2,2];

in the following c++ code?
#include <iostream>
using namespace std;

int main()
{
    int* p = new int[2,2];
}

A: int* p = new int[2,2];

effectively means
int* p = new int[2];

When comma operator is used, right most value is considered as final result.

A: That comma between the two 2 is a "comma operator". It is rarely used in C++ and its semantic is to evaluate left part, ignore the result, and then evaluate right part. It is one of the few operators in which the order of evaluation of the operands is guaranteed (if you don't overload it).
A good compiler sould have emitted a warning because in your example the first expression has no side effects and new int[2,2] is exactly the same as new int[2].
Note that other commas in C++ are NOT the comma operator... for example the commas between arguments in a function call are not commas operators and the order of evaluation of the arguments expression is not guaranteed. Worse than that may be an "order of evaluation" doesn't exist at all:
foo(f(g()), h());

in the line above the sequence in which the functions can be called could be for example g, h, f so you cannot say neither that the first argument was evaluated before the second nor that the second was evaluated before the first.

A: It's creating an integer pointer and setting it to a new array.


text:
Q: Paired-sample t test for usability scores I have conducted an empirical study as a part of my master thesis. Each test subject filled out a questionnaire where some questions were regarding usability of different features. What is the best/correct way to calculate if a feature got a significant better usability score than another feature? (I used a 10-point Likert scale).
I had 14 test subjects, and I want to compare the usability score for a feature called "bubble" and a feature called "hull".
This is the scores:
Bubble: 6,  3,  7,      9, 7, 8, 7,  9, 8, 8, 6, 10, 3, 7
Hull:   9, 10, 10, 8.6154, 9, 6, 8, 10, 8, 8, 6, 10, 9, 9

(One subject did not rate "hull", I have therefore inserted the mean (8.6154) in its place.)
I have run a paired-sample t test which indicates that there is a significant difference in the usability scores for bubble (M=7.0, SD=2.04) and hull (M=8.62, SD=1.33); t(13)=2.43, p=0.0305.
Is this the correct way to do it? My statistical knowledge is quite limited, but I think I should say if there was a significant difference or not.

A: I agree with @Error404 about the assumption, esp. because the one other person who rated bubble '9' gave hull a 10. If you wanted to get fancy you could do multiple imputation; if you want to keep it simple, just drop that person.


text:
Q: What is the correct way to grant permissions using SAML tokens in Sharepoint 2013 Hi We have a sharepoint 2013 instance and we are setting up claims based authentication with SAML assertions (ADFS 3.0 IDP). I am able to grant access to a user by adding the user's email address to the web application's user policy. This works fine however I am unable to grant access by group.
I created claim type mappings for email,UPN,Role, and SID.
$emailClaimMap = New-SPClaimTypeMapping -IncomingClaimType   "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming
$upnClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" -IncomingClaimTypeDisplayName "UPN" -SameAsIncoming
$roleClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" -IncomingClaimTypeDisplayName "Role" -SameAsIncoming
$sidClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid" -IncomingClaimTypeDisplayName "SID" -SameAsIncoming

Here are the ADFS claim rules

What is the correct way to grant access to a user based on group membership?

A: I figured it out. The group I was using was configured as a Distribution group and not a Security group.
Also, when using the picker for adding a user/group to a sharepoint group I had to mouse over the search result and make sure I selected the entry with the Role claim.


text:
Q: Multiple domains for one website with multiple languages I have 3 domains in 3 different languages and I want to point them to one website.
I want to ask hosting provider to point all domains to one application (code - same place/folder on hosting/server). Is this a right solution for this case, or should I proceed differently?

*

*domain.tech - english

*domain.sk - slovak

*domain.es - spanish

I think it doesn't affect SEO since for every domain there would be different content (same content but different language).
I want .sk and .es domain to be geographically oriented.
I want .tech to be international domain with CDN service.
I want to approach same database and use same local assets (images).
Are there any negatives in option I am considering? Or is there any better solution?


text:
Q: chrome tts word event. works on Windows not on Chromebook I'm working on a Chrome app that uses the tts API. When i call chrome.tts.getVoices() all the voices returned on the chromebook list 'word' as one of the event types. Like in the image below.

The problem I'm having is that even though the chromebook voices report that they support the word event i am not getting them in the onEvent callback. All I am getting is the start and end events. When i run this app in Windows it works fine. I get all the events that the "native" windows voice says it supports ("word", "sentence", etc...)
I'm hoping someone can help shed some light on this ???


text:
Q: Further Investigation of $\tau_1 \lor \tau_2$ This is a continuation of my previous post, Properties of $\tau_1 \lor \tau_2$
Let $X$ be a set equipped with any topology $\tau_1$, let $\tau_2$ be the cocountable topology (i.e. a subset $U$ of $X$ is open if either $U=\emptyset$ or $X\setminus U$ is finite or countable), and let $\tau=\tau_1\lor \tau_2$ be defined as the subsets $W\subseteq X$ such that for every $x \in W$, there exist subsets $U,V \subseteq X$ with $x \in U$, $x \in V$, $U \in \tau_1$, $V \in \tau_2$, and $U \cap V \subseteq W$.

1.) Which sequences in $X$ converge with respect to $\tau$?

My thought is that a sequence which is eventually constant will converge, but I'm not sure how to go about proving this.

2.) Prove or disprove: $(X, \tau)$ is a $T_1$-space.

My intuition is that $(X, \tau)$ is in fact a $T_1$-space, but I'm not sure if this is correct. By definition, $(X, \tau)$ is $T_1$ if for every $x,y \in X$ with $x \neq y$, there exists an open set $U \subseteq X$ such that $x \in U$ but $y \notin U$.

3.) Suppose that $(X, \tau_1)$ satisfies the local countability condition at a point $p \in X$. Show that if $p$ is a condensation point of $X$ with respect to $\tau_1$, then $(X, \tau)$ does not satisfy the local countability condition at $p$.

Since $(X, \tau_1)$ satisfies the local countability condition at $p$, there exists a sequence of subsets $\{U_i\}_{i=1}^{\infty}$ such that
1) $U_i \in \tau_1$ for all $i$,
2) $ x \in U_i$ for all $i$, and
3) If $V$ is an open subset of $X$ with $x \in V$, then $U_i \subseteq V$ for some $i$.
Since $p$ is a condensation point of $X$ with respect to $\tau_1$, $p$ is a limit point of $X$ with respect to $\tau$. Where do I go from here?

4.) Suppose again that $(X, \tau_1)$ satisfies the local countability condition at $p$. Under what condition will $(X, \tau)$ satisfy the local countability condition at $p$?

I have no idea about this part of the question, so a gentle nudge in the right direction would be appreciated.

A: Indeed, the only convergent sequences of $\tau:= \tau_1 \lor \tau_2$ are the eventually constant ones. This follows as this holds for the co-countable topology $\tau_2$ and $\tau_2 \subseteq \tau$ (because we can take $U =X$ from $\tau_1$ in the definition of $\tau_1 \lor \tau_2$ or because $\tau_1 \cup \tau_2$ is a subbase for $\tau$ etc.); If $x_n \to x$ in $\tau$ then a fortiori (we can take open sets in $\tau_2$ to use in the definition of convergence w.r.t. $\tau$) $x_n \to x$ in $\tau_2$ so $(x_n)$ is eventually constant. (The latter I showed in this answer).

For all $x \in X$, $X \setminus \{x\} \in \tau_2$, by definition (a singleton is at most countable) and so $X \setminus \{x\} \in \tau$, so that all $\{x\}$ are closed in $(X,\tau)$ and thus $X$ is $T_1$, regardless of $\tau_1$.

Suppose $p$ is a condensation point of $X$ in that $(X,\tau_1)$. Then $p$ is a condensation point of $(X,\tau)$: Let $O$ be open in $\tau$. Then there are open sets $U \in \tau_1$ and a co-countable $V= X \setminus N \in \tau_2$ (so $N \subseteq X$ is at most countable) such that $p \in U \cap V = U\setminus N \subseteq O$.
As $p$ is a $\tau_1$-condensation point, $U$ is uncountable so surely $U \setminus N$ is infinite (uncountable even) and so, as $O$ is any open neighbourhood of $p$ in $\tau$, $p$ is a condensation point of $(X,\tau)$.
If $(X, \tau)$ were first countable at $p$ then as $p$ is a condensation point of $X$ in $\tau$ we can always define a sequence $(x_n)$ of distinct points unequal to $x$ such that $x_n \to_\tau x$. (just use a simple recursive definition, we could already do this in a $T_1$ space of which $p$ is a non-isolated point, so condensation point is overkill). But this contradicts 1) and so $p$ cannot be first countable in $(X, \tau)$.

Suppose $p$ is first countable at $(X,\tau)$, let $O_n$ be a countable local $\tau$-base at $p$. As $(X,\tau)$ is $T_1$, we can define a sequence $x_n$ of all distinct points, all $x_n \neq x$, with $x_n \to_\tau x$ iff $x$ is not an isolated point of $X$ (i.e. $X$ is a limit point of $(X,\tau)$. This is a standard argument. But we already saw such sequences cannot exist, so this means that if $p$ is $\tau$-first countable, it must be a $\tau$-isolated point, or equivalently $p$ has a neighbourhood $O \in \tau_1$ such that $O \cap (X\setminus N_p) = \{p\}$ for some $N_p \subseteq X$ at most countable. This means exactly that $p$ has a countable neighbourhood in $\tau_1$. First countability of $p$ in $(X,\tau_1)$ I don't see any effect of.
So $p$ is first countable at $(X,\tau)$ iff $p$ has a countable neighbourhood in $(X,\tau_1)$ iff $p$ is isolated in $(X,\tau)$.

A: For 1: Almost by definition, $\tau_1 \cup \tau_2$ is a subbasis for the topology $\tau_1 \vee \tau_2$.  Now, think of a relevant result related to subbasic sets and sequence convergence.
For 2: $T_1$ is equivalent to every singleton set being closed, and therefore also to $X \setminus \{ x \}$ being open for every $x \in X$.  Now, I would just look at the definition of open sets for $\tau_1 \vee \tau_2$.


text:
Q: Rails Tutorial Ch 12 - follow!() method not working I'm new to Rails, and thought I'd managed to get right through Michael Hartl's tutorial (RoR3 ed1) without asking for help, but I'm finally stumped.  Can anyone offer any suggestions?
My problem is with the follow!() method of the Users model in section 12.1.  When I pass a user to the method and try to store the foreignID in the relationship it comes through as nil.
1.9.2p290 :023 > user1=User.find(1)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
 => #<User id: 1, name: "Example User", email: "example@railstutorial.org", created_at: "2012-10-20 18:48:38", updated_at: "2012-10-20 18:48:38", encrypted_password: "cd8e8ad53b1157789cb004de14bc14112786981004b51bd1576...", salt: "d947c9bcb6563fd8c70d3d1c64c9d82507a89b936ea0cbfd3e4...", admin: false>
1.9.2p290 :024 > user2=User.find(4)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]
 => #<User id: 4, name: "Mrs. Carmelo Witting", email: "example-2@railstutorial.org", created_at: "2012-10-20 18:48:38", updated_at: "2012-10-20 18:48:38", encrypted_password: "c0f2c8f998bc1b9bf76c9196176828dc543ceeb2a28f7b81c2d...", salt: "3c134e8fd391db0b9b21f0e08ddda7bfd8d16b3abe6726d517d...", admin: false>
1.9.2p290 :025 > user1.follow!(user2)
  SQL (1.9ms)  INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Mon, 22 Oct 2012 11:16:38 UTC +00:00], ["followed_id", nil], ["follower_id", 1], ["updated_at", Mon, 22 Oct 2012 11:16:38 UTC +00:00]]
 => #<Relationship id: 8, follower_id: 1, followed_id: nil, created_at: "2012-10-22 11:16:38", updated_at: "2012-10-22 11:16:38">

Here are the relevant bits of the user model.  What might be causing this?
class User < ActiveRecord::Base
.
.
  has_many :relationships, :foreign_key => "follower_id",
                           :dependent => :destroy
  has_many :following, :through => :relationships, :source => :followed
.
  def follow!(followed)
    relationships.create!(:followed_id => followed.id)
  end

end

A: Worked it out. I had written attr_accessor instead of attr_accessible for followed_id in the Relationship model.
Doh


text:
Q: Binding list to Datagridview issue c# I have a list which is populated with data from a CSV file, but when I set that list to datagridview data source property, no data is shown. Can you suggest where I might have made a mistake?
Here is my code
        var csvlines = File.ReadAllLines(filename);   // IEnumerable<string>
        var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray());  // IEnumerable<string[]>
        var users = csvLinesData.Select(data => new User
        {
            CSRName = data[6],
            CallStart = data[0],
            CallDuration = data[1],
            RingDuration = data[2],
            Direction = data[3],
            IsInternal = data[4],
            Continuation = data[5],
            ParkTime = data[7]
        }).ToList();

        dataGridView1.DataSource = users;

EDIT
Now I did it this way instead, and the data is showing.
    var csvlines = File.ReadAllLines(filename);   // IEnumerable<string>
    var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray());  // IEnumerable<string[]>
    var users = csvLinesData.Select(data => new User
    {
        CSRName = data[12],
        CallStart = data[0],
        CallDuration = data[1],
        RingDuration = data[2],
        Direction = data[4],
        IsInternal = data[8],
        Continuation = data[10],
        ParkTime = data[18]
    }).ToList();

    DataTable dt = new DataTable();
    dt.Columns.Add("CSRName",typeof(string));
    dt.Columns.Add("CallStart", typeof(string));
    dt.Columns.Add("CallDuration", typeof(string));
    dt.Columns.Add("RingDuration", typeof(string));
    dt.Columns.Add("Direction", typeof(string));
    dt.Columns.Add("IsInternal", typeof(string));
    dt.Columns.Add("Continuation", typeof(string));
    dt.Columns.Add("ParkTime", typeof(string));

    DataRow dr = null;
    foreach (var user in users)
    {
        dr = dt.NewRow();
        dr["CSRName"] = user.CSRName;
        dr["CallStart"] = user.CallStart;
        dr["CallDuration"] = user.CallDuration;
        dr["RingDuration"] = user.RingDuration;
        dr["Direction"] = user.Direction;
        dr["IsInternal"] = user.IsInternal;
        dr["Continuation"] = user.Continuation;
        dr["ParkTime"] = user.ParkTime;
        dt.Rows.Add(dr);
    }

    //dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = dt;

A: Bind your gridview to a BindingList, instead of List.
var bindlist = new BindingList<User>(users);

And then create a binding source and bind that to the gridview.
 var source = new BindingSource(bindlist, null);
 dataGridView1.DataSource = source;


text:
Q: Django save to DB: TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' I have a problem in def that save data into database.
    @staticmethod
    def _save(account, proxy,
              proxy_provider_id, period,
              country, start_date,
              price, meta,
              account_type, ip):
        try:
            period = int(period)
            end_date = start_date + timedelta(days=period)
            prx = Proxy()
            prx.account = account
            prx.proxy = proxy
            prx.proxy_provider_id = proxy_provider_id
            prx.period = period,
            prx.country = country,
            prx.start_date = start_date
            prx.end_date = end_date
            prx.price = price
            prx.meta = meta
            prx.ip = ip
            print('\n')
            print('Save proxy {}'.format(prx))
            print('account: {} type {}'.format(account, type(account)))
            print('proxy: {} type {}'.format(proxy, type(proxy)))
            print('proxy id: {} type {}'.format(proxy_provider_id, type(proxy_provider_id)))
            print('country: {} type {}'.format(country, type(country)))
            print('start date: {} type {}'.format(start_date, type(start_date)))
            print('end date: {} type {}'.format(end_date, type(end_date)))
            print('price: {} type {}'.format(price, type(price)))
            print('meta: {} type {}'.format(meta, type(meta)))
            print('ip: {} type {}'.format(ip, type(ip)))
            print('\n')
            prx.save() # exception raised there

            payment = [start_date.strftime('%Y/%m/%d'),
                       end_date.strftime("%Y/%m/%d")]
            payments = json.loads(account.history_of_payments)
            payments.append(payment)
            account.history_of_payments = json.dumps(payments)
            account.account_type = account_type

            print('\n')
            print('Save account {}'.format(prx))
            print('payment: {} type {}'.format(payments, type(payments)))
            print('account type: {} type {}'.format(account_type, type(account_type)))
            print('\n')

            account.save(update_fields=['history_of_payments', 'account_type'])
            log.debug('Update account {}'.format(account))
        except Exception:
            raise ProxyException('Exception, when trying to save proxy {} {} for {} '
                                 'date {} price {} meta {} '
                                 .format(proxy, country, account.username,
                                         start_date, price, meta))
        else:
            log.info('Save new proxy {} {} for {} from {} to {} price {} meta {} '
                     .format(proxy, country, account.username,
                             start_date, end_date, price, meta))
            return True

I don't know, what cause this exception, because I don't try to save any tuple. You can check log. There are only srting, float, object, datetime and int types.
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

Full log is:
Save proxy Proxy object
account: InstagramAccount object type <class 'models.models.InstagramAccount'>
proxy: jFdDVV:BxorDV@107.191.105.212:17160 type <class 'str'>
proxy id: 762064 type <class 'int'>
country: us type <class 'str'>
start date: 2017-05-26 16:09:31.604467+00:00 type <class 'datetime.datetime'>
end date: 2017-05-29 16:09:31.604467+00:00 type <class 'datetime.datetime'>
price: 3.6 type <class 'float'>
meta: {"2017/05/26": {"time": "16:09:13", "proxy_type": "http", "account_type": "trial", "country": "us", "proxy": "jFdDVV:BxorDV@107.191.105.212:17160", "price": 3.6, "currency": "RUB"}} type <class 'str'>
ip: 109.86.13.23 type <class 'str'>

[2017-05-26 16:09:31,604] DEBUG Proxy jFdDVV:BxorDV@107.191.105.212:17160 check is successful
--- Logging error ---
Traceback (most recent call last):
  File "/usr/instafy_py/src/service/views.py", line 130, in create_instagram_account
    username=username)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/query.py", line 385, in get
    self.model._meta.object_name
models.models.DoesNotExist: InstagramAccount matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/instafy_py/src/proxy/manager.py", line 208, in _save
    prx.save()
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 796, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 824, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 908, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 947, in _do_insert
    using=using, raw=raw)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/query.py", line 1045, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1053, in execute_sql
    for sql, params in self.as_sql():
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1006, in as_sql
    for obj in self.query.objs
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1006, in <listcomp>
    for obj in self.query.objs
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1005, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 945, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 747, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1832, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/instafy_py/src/service/views.py", line 169, in create_instagram_account
    3, 'trial')
  File "/usr/instafy_py/src/proxy/manager.py", line 156, in buy
    account_type, ip)
  File "/usr/instafy_py/src/proxy/manager.py", line 229, in _save
    start_date, price, meta))
proxy.manager.ProxyException: Exception, when trying to save proxy jFdDVV:BxorDV@107.191.105.212:17160 us for guv.vop date 2017-05-26 16:09:31.604467+00:00 price 3.6 meta {"2017/05/26": {"time": "16:09:13", "proxy_type": "http", "account_type": "trial", "country": "us", "proxy": "jFdDVV:BxorDV@107.191.105.212:17160", "price": 3.6, "currency": "RUB"}}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/python/lib/python3.5/logging/__init__.py", line 980, in emit
    msg = self.format(record)
  File "/opt/python/lib/python3.5/logging/__init__.py", line 830, in format
    return fmt.format(record)
  File "/opt/python/lib/python3.5/logging/__init__.py", line 567, in format
    record.message = record.getMessage()
  File "/opt/python/lib/python3.5/logging/__init__.py", line 330, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
  File "/opt/python/lib/python3.5/threading.py", line 882, in _bootstrap
    self._bootstrap_inner()
  File "/opt/python/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/opt/python/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/opt/python/lib/python3.5/socketserver.py", line 625, in process_request_thread
    self.finish_request(request, client_address)
  File "/opt/python/lib/python3.5/socketserver.py", line 354, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/opt/python/lib/python3.5/socketserver.py", line 681, in __init__
    self.handle()
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 174, in handle
    handler.run(self.server.get_app())
  File "/opt/python/lib/python3.5/wsgiref/handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 170, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in get_response
    response = self._middleware_chain(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/src/middlewares/startup_middleware.py", line 13, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/instafy_py/src/service/views.py", line 171, in create_instagram_account
    log.exception('Something wrong with proxy', e)
Message: 'Something wrong with proxy'
Arguments: (ProxyException('Exception, when trying to save proxy jFdDVV:BxorDV@107.191.105.212:17160 us for guv.vop date 2017-05-26 16:09:31.604467+00:00 price 3.6 meta {"2017/05/26": {"time": "16:09:13", "proxy_type": "http", "account_type": "trial", "country": "us", "proxy": "jFdDVV:BxorDV@107.191.105.212:17160", "price": 3.6, "currency": "RUB"}} ',),)

All data types are match with model
class InstagramAccount(models.Model):
    username = models.CharField(max_length=45, primary_key=True)
    password = models.CharField(max_length=45)
    account_id_account = models.ForeignKey(Account, models.DO_NOTHING, db_column='account_id_account')
    expired_date = models.DateTimeField(null=False)
    history_of_payments = models.TextField(blank=True, null=True)
    account_type = models.TextField(default='trial')

    class Meta:
        managed = False
        db_table = 'instagram_account'
        unique_together = (('account_id_account', 'username'),)

class Proxy(models.Model):
    id_proxy = models.AutoField(primary_key=True)
    proxy = models.CharField(max_length=45, blank=False, null=False)
    meta = models.TextField(null=True)
    start_date = models.DateTimeField(null=False)
    end_date = models.DateTimeField(null=True)
    country = models.CharField(max_length=45, null=False)
    period = models.PositiveIntegerField()
    price = models.FloatField(validators=[MinValueValidator(0.0), ])
    # It can confuse, but our proxy provider have it own id for proxy
    proxy_provider_id = models.PositiveIntegerField()
    ip = models.CharField(max_length=45, null=False, blank=False)
    account = models.ForeignKey(InstagramAccount, models.DO_NOTHING,
                                db_column='instagram_account_account_id_account')

    class Meta:
        managed = False
        db_table = 'proxy'
        unique_together = (('id_proxy', 'account'),)

if I use raw SQL query, it would be better?

A: You have a comma at the end of the line where you set prx.country, which turns it into a tuple.
There are quite a few strange things in this code. Most importantly, you really should not catch all exceptions only to raise your own; you should catch the errors you know you can handle (and actually handle them, not raise another error); everything else you should let Django handle itself.


text:
Q: Decimals not passing properly with JSON postback to C# I'm passing a product price back from my front end using JSON and the jQuery AJAX call.  Whenever I pass a decimal back that is just an integer (21, instead of 21.50) the JSON object doesn't include the decimal point and it isn't filling in my decimal property on the resulting action method.  Is there a simple way to force the jscript to always explicitly include the .00 for round numbers?

A: If you want to force it to have a decimal, just call the toFixed function on the number when you're building your data for the callback.
var flatNum = 21;

$.ajax({
  data: {
    name: "Name",
    num: flatNum.toFixed(2);
  },
  ...
});

Doing that will pad the number out to two decimal places (and round if the precision is longer than that).


text:
Q: How to check integrity of an encrypted string then converted to Base64? I encrypt and decrypt a string with a private key and following functions.
so I encrypt a string with Encrypt function and decrypt the encrypted string with decrypt function.
If someone can change the encrypted string and then it decrypts with decrypt function, the decrypted string isn't equal to plain text before encrypting.
I want to know how can I check is decrypted string equals to plain text before encrypting?
 public string Encrypt(string plainText, string password)
    {
        GenerateKey(password);
        return Encrypt(plainText);
    }
    public string Encrypt(string plainText)
    {
        if (Key == null)
        {
            throw new InvalidOperationException("Password must be provided or set.");
        }
        byte[] data = new UnicodeEncoding().GetBytes(plainText);
        RijndaelManaged crypto = new RijndaelManaged();
        ICryptoTransform encryptor = crypto.CreateEncryptor(Key, Vector);
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream crptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
        crptoStream.Write(data, 0, data.Length);
        crptoStream.FlushFinalBlock();
        crptoStream.Close();
        memoryStream.Close();
        return Convert.ToBase64String(memoryStream.ToArray());
    }
    public string Decrypt(string encryptedText, string password)
    {
        GenerateKey(password);
        return Decrypt(encryptedText);
    }
    public string Decrypt(string encryptedText)
    {

        if (Key == null)
        {

            throw new InvalidOperationException("Password must be provided or set.");
        }
        byte[] cipher = Convert.FromBase64String(encryptedText);
        RijndaelManaged crypto = new RijndaelManaged();
        ICryptoTransform encryptor = crypto.CreateDecryptor(Key, Vector);
        MemoryStream memoryStream = new MemoryStream(cipher);
        CryptoStream crptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Read);
        byte[] data = new byte[cipher.Length];
        int dataLength = crptoStream.Read(data, 0, data.Length);
        memoryStream.Close();
        crptoStream.Close();
        return (new UnicodeEncoding()).GetString(data, 0, dataLength);
    }

A: Embed a checksum. Take e.g. a SHA1 hash of the plaintext, base64 it, prepend it to the text and encrypt. After decrypting, extract the SHA1 part and verify it against the remainder of the string.

A: You need to include a message authentication code (MAC).
The details of doing this correctly are beyond the scope of a SO answer so I suggest consulting an expert before starting an implementation.
A good starting point would by Practical Cryptography (not specific to .NET or any other platform, but will show you what you need to do—and why it is very hard to get right).


text:
Q: Angular 6 library: ng build library in CI pipeline to create lib release I'm trying to build an Angular 6 library for CI integration without integrate it into an Angular App. (for numerous reasons)
What i have done so far is:

*

*create a package.json in order to install all the lib's dependencies

*create an angular.json like regular angular6 app refering to ci files (see below)

*duplicate all ng-packages.\*.json to ng-package.ci.\*.json and update their paths to refer to the right files and directories (node_modules, entryfiles, etc..)

*duplicate all ts-config.\*.json to tsconfig.ci.\*.json and update their paths to refer to the right files and directories (src, dist, etc..)

I was expected by running ng build to be able able to build the library but instead i have this message:

Versions of @angular/compiler-cli and typescript could not be
  determined.

( But all packages are installed; i check it twice)
Does anyone has ever tried to build its Angular 6 library without using the library inside an app?
Thx

A: It currently isn't possible, but there is an open issue for it here:
https://github.com/angular/angular-cli/issues/10751

A: I reply to your answer because i was able to solve all my problems.

*

*I'am now able to build (test, lint) an angular Library in a CI pipeline

*I can integrate this library into an angular project.

Here is the way i done it. I generated a library in an almost empty directory.
To do ng generate library my-lib --skip-package-json --skip-ts-config you need to have a package.json file, and an angular.json file in this directory. I picked the these files from a fresh new app ng new app and  remove the app reference from the workspace into the angular.json (in the projects section)
Once the library was generated i created a folder ci at the root where i copied the files tsconfig.*.json, karma.json, ng-package.json and package.json. I keepted the original files at root in order to be able to use the library in integrated mode into an app. (just need to add the lib reference into the angular.json of your app, like if it was generated + path in stconfig of your app)
I updated the paths in all files in the ci folder in order to be able to run a command such as :

*

*ng lint --format stylish --tslint-config ci/tslint.ci.json

*ng build by setting the default project in angular.json to my-lib anf pointing to tsconfig and ng-package in the ci folder

One tip, the package.json at the roots needs to have all the dependencies from an new angular app to be able to build or test the library.
Hope this brief explanation will help.


text:
Q: SQL Server: How to get physical partition number of a row? We all know for each row in a table, there will be a partition to store this row.
I searched the stackoverflow, and find there is a post "Get A records current partition"
https://dba.stackexchange.com/questions/22638/get-a-records-current-partition
However I am not quite clear how to do that.
Could someone give a concrete example?
If I have a table Employee, which has a non cluster index on EmployName and cluster index on EmployID, then how to find the partition number of the index and the cluster index where the row whose EmployID is 41245 resides in?
More information:
CREATE TABLE Employee
(
    EmployeeID int identity(1,1) not null
    , EmployeeName varchar(200) not null
    , constraint PK_Employee_1 primary key clustered
        (
            EmployeeID
        )
    , INDEX NONCLUSTERED IX_EmployeeName ON Employee (EmployeeName)
)


text:
Q: Purge command discord.js I am trying to create a purge command and it works, but I want the bot to not delete the pinned messages when I use the command. What do I include in the code to prevent it from delting the pinned messages? Currently this is the code -
if(message.content.toLowerCase().startsWith("s!purge")) {
let arg = message.content.split(" ")
  message.delete()
let clear = arg[1];
if(!clear) return message.channel.send(`:x: | \`Incorrect usage of command you need to provide an amount of messages to Clear.\`
**Example:** \`s!purge 50\` `)
if(isNaN(clear)) return message.channel.send(":x: | ``Please Put a Valid Number to Clear messages.``")
if(clear > 100) return message.channel.send(":x: | ``I can't Clear more than 100 messages.``")
if(clear < 1) return message.channel.send(":x: | ``You cannot Clear less than 1 message.``")
message.channel.bulkDelete(clear)
message.channel.send(`:white_check_mark: | \`Succesfully cleared ${clear} messages! \` `)
.then(message =>
 setTimeout(()=> message.delete(), 2000)
 )
}

A: There is a method to check if a message is pinned or not. Which is message.pinned.
And do
if (!message.pinned) {
    // delete the message
}

I hope that solves your issue!
or else you can do const nonPinnedMsgs = await message.channel.messages.fetch({ limit: thePurgeAmount }).filter(m => m.pinned) and bulk delete (nonPinnedMsgs)


text:
Q: Nested Form: link_to_add: customizing to work with multiple fields_for builders I have a nested form with a nested child object type which is repeated on the form so that I can apply various different defaults in the form elements.  It doesn't make sense for me to separate them into different classes of child objects because I am only separating them for the purposes of organizing them in a way that makes sense to the user and for populating different defaults; they are otherwise identical.
In my partial, I have something like this:
Children 1
<%= f.fields_for :children do |builder| %>
  <% next if not builder.object.type == 1 %>
  ... fields for type 1 children ...
<% end %>
<%= f.link_to_add( "add child", :children ) %>

Children 2
<%= f.fields_for :children do |builder| %>
  <% next if not builder.object.type == 2 %>
  ... fields for type 2 children ...
<% end %>
<%= f.link_to_add( "add child", :children ) %>

... etc ...

This works fine, except that the link_to_add always gives fields having the defaults of the final fields_for/builder block (i.e. Type N Children), rather than using the defaults for the fields_for/builder block immediately above them.  How can I give link_to_add the right functionality?
From https://github.com/ryanb/nested_form#enhanced-jquery-javascript-template :

You can override default behavior of inserting new subforms into your form. For example:
 window.nestedFormEvents.insertFields = function(content, assoc, link) {
   return $(link).closest('form').find(assoc + '_fields').append($(content));
 }

It seems to me that there must be some small adjustment to this insertFields function that would have it duplicating the desired form elements, instead of just the final ones on the page.  I have only the barest experience with javascript, so I'm hoping someone can please point out what that is!
FYI, the full jquery file is here:
https://github.com/ryanb/nested_form/blob/master/vendor/assets/javascripts/jquery_nested_form.js
Many thanks,
Scott

A: I neglected to post the solution I found for this problem.  Belatedly, here it is.
I ended up using Single Table Inheritance (STI) for my child types, making each one a class, even though that was overkill for me. Then, the following worked:
<h>ClassOneChild form</h>
<%= f.fields_for :class_one_children do |builder| %>
  ...
<% end %>
<%= f.link_to_add( "add child", :class_one_children ) %>

<h>ClassTwoChild form</h>
<%= f.fields_for :class_two_children do |builder| %>
  ...
<% end %>
<%= f.link_to_add( "add child", :class_two_children ) %>

...

<%= f.submit "Save Children" %>


text:
Q: Windows RT IE10 vs Windows 8 IE10 What is the difference between IE10 on Windows RT and IE10 on Windows 8? Is the IE10 on both the platform has same HTML, CSS and Script engine?

A: It is the same browser. The main difference is the User Agent string. On Windows RT the architecture token is "Arm", while on Windows it is either absent, "WOW64" or "Win64; x64":
http://blogs.msdn.com/b/ie/archive/2012/07/12/ie10-user-agent-string-update.aspx
You can see on sites like HTML5test that Windows RT and Windows 8 browsers have the same score.