text:
Q: Weak convergence in $L^p$ space
Let $(\Omega,\mathfrak{B},\mu)$ be a measure space and  $1<p<\infty$. Consider a sequence $f_n\in L^p(\Omega,\mathfrak{B},\mu))$ s.t $f_n\to f$ a.e and $\operatorname{Sup}\{\|f_n\|_p:n\in\Bbb{N}\}=C<\infty$. Prove that for every $\phi\in (L^p(\Omega,\mathfrak{B},\mu))^*, \phi(f_n)\to\phi(f)$.

My attempt: By Riesz representation theorem, every $\phi\in (L^p(\Omega,\mathfrak{B},\mu))^*$ corresponds to a $g\in L^q(\Omega,\mathfrak{B},\mu)$. So let $g\in  L^q(\Omega,\mathfrak{B},\mu)$, I want to prove that $\int_{\Omega}f_ngd\mu\to\int_{\Omega}fgd\mu$.
My attempt: It's easy to show, using Fatou's lemma, that $\|f\|_p\leq C$. Moreover, if we assume that $\mu$ is finite, then using Egoroffs theorem proves the claim.
Now I want to use similar arguments to the case $\mu$ is not finite. Since $\|g\|_q<\infty$, I know that the sets $E_N=\{\omega:|g(\omega)|>\frac{1}{N}\}$ are of finite measure. So I define $E=\bigcup_{N\in\Bbb{N}}E_N$. It suffices to show that $\int_{E}f_ngd\mu\to\int_{E}f_gd\mu$. I know this is true for every $E_N$, but I wasn't able to conclude it for $E$. Any help would be appreciated.
**edit:
I realize this has been asked several times, but not in this generality and I wasn't able to follow the solutions suggested or verify them

A: In order to prove that $\int_{\Omega}f_ngd\mu\to\int_{\Omega}fgd\mu$, it suffices to deal with the case where $g$ takes the form  $\mathbf{1}_{A_i}$, where $A\in \mathfrak B$ and has finite measure. Indeed, let $N\in\mathbb N$ and $c_1,\dots,c_N\in\mathbb R$, $A_1,\dots,A_N\in\mathfrak B$. From
$$
\left\lvert \int_{\Omega}f_ngd\mu-\int_{\Omega}fgd\mu\right\rvert
\leqslant \left\lvert \int_{\Omega}f_n\left(\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right)d\mu-\int_{\Omega}f\left(\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right)d\mu\right\rvert+\left\lvert \int_{\Omega}f_n\left(g-\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right) d\mu\right\rvert +\left\lvert \int_{\Omega}f\left(g-\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right) d\mu\right\rvert
\\
\leqslant \left\lvert \int_{\Omega}f_n\left(\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right)d\mu-\int_{\Omega}f\left(\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right)d\mu\right\rvert+2C\left\lVert g-\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right\rVert_q,
$$
we would  get that
$$
\limsup_{n\to\infty}\left\lvert \int_{\Omega}f_ngd\mu-\int_{\Omega}fgd\mu\right\rvert
\leqslant 2C\left\lVert g-\sum_{i=1}^Nc_i\mathbf{1}_{A_i}\right\rVert_q
$$
and the fact the class consisting of functions of the form $\sum_{i=1}^Nc_i\mathbf{1}_{A_i}$ is dense in  $\mathbb L^q$ would give the wanted convergence.
You are thus reduced to the case where the measure is finite.


text:
Q: Como imprimir o saldo em ordem crescente e calcular juros no python Pessoal eu tenho um trabalho na qual eu devo reproduzir a seguinte tabela:

Eu não tenho muito conhecimento em python e estou dando o meu melhor para tentar reproduzir ela. Mas estou conseguindo retornar somente desta maneira.

Minhas dúvidas são as seguintes:

*

*O mês eu não sei como colocar na ordem crescente e nem retirar o 0
no final.

*Do saldo inicial ao saldo final eu consigo imprimir, o problema é
que ele imprime até 0.

*Não sei a lógica da prestação.

*Não sei a lógica dos Juros (quadro verde).

*Não sei a lógica dos juros mensais (quadro vermelho).

*Não sei como imprimir o saldo final (que nesse caso é o inverso do
saldo inicial).

Segue abaixo o meu código:
# enconding: utf-8
########################################
# VERSÃO UTILIZADA: Python 3.6.5       #
# DISCIPLINA: Introdução à Programação #
########################################

#########################################
# Informações de entrada dada pelo user #
#########################################

import os

valor_financiamento = float ( input ("1. Informe o valor a ser financiado: "))
os.system("cls")
prazo = int ( input ("2. Informe o prazo de quitação do financiamento (em meses): "))
os.system("cls")
taxa_juros_anual = float (input ("3. Informe a taxa de juros anual (em %): "))
os.system("cls")

# Início da programação e cálculo
# USO DO SISTEMA SAC

# O cálculo da amortização é realizado pelo valor do financiamento divido pela quantidade de meses
amortizacao = valor_financiamento / prazo

saldo_devedor = valor_financiamento - amortizacao

taxa_mensal = taxa_juros_anual / prazo

juros_mes = (taxa_juros_anual - 1 + 1 ) * amortizacao * taxa_mensal

prestacao = amortizacao + juros_mes
#valor_financiamento = str (valor_financiamento).replace('.',',')

#print ("AMORTIZAÇÃO: R$ %.2f" % amortizacao)
#print ("VALOR DO FINANCIAMENTO: R$ %.2f\n\n" % valor_financiamento)
print ("\t FINANCIAMENTO = R$ %.2f \t MESES: %i meses \t TAXA: %i%% ano (%.f%)" % (valor_financiamento, prazo, taxa_juros_anual, juros_mes))
print ("\t","-"*80,"\n")
print ("\t MÊS\tSALDO INICIAL\tPRESTAÇÃO\tAMORTIZAÇÃO\tJUROS\tSALDO FINAL")
print ("\t ---\t-------------\t---------\t-----------\t-----\t-----------")

print ("\t%4.i \t %12.2f \t\t\t %10.2f" % (prazo, valor_financiamento, amortizacao))
for p in range(prazo):
    while (valor_financiamento > 1):
        valor_financiamento = valor_financiamento - amortizacao # Saldo devedor
        prazo = prazo - 1 # Referência do mês
        saldo_devedor = valor_financiamento - amortizacao
        saldo_final = saldo_devedor - amortizacao
        print ("\t%4.i \t %12.2f \t\t\t %10.2f" % (prazo, valor_financiamento, amortizacao)) #% valor_financiamento)
        #print (prazo)

Essa questão é uma questão de financiamento imobiliário segundo o sistema SAC:
Questão
Construa um programa que gere uma tabela com os valores das prestações mensais de um financiamento, discriminando os valores referentes à amortização e aos juros a serem pagos até a amortização total do financiamento. Este programa deve apresentar um menu de opções e pedir as seguintes informações ao usuário: Valor financiado, Prazo (em meses) para quitação do financiamento, Taxa de juros anual (em percentual) e o Sistemática de pagamento mensal das prestações (Sistema de Amortização Constante – SAC ou Sistema PRICE - ver nota explicativas em anexo). Funcionalidades adicionais serão bem vindas!
O valor de um financiamento deve ser restituído (amortizado) ao financiador em certo período de tempo, acrescido dos juros. Amortizar significa reduzir o valor da dívida, ou seja, pagar uma parte da dívida periodicamente para que ela reduza de tamanho até a sua eliminação. Como a dívida implica em cobrança de juros, para amortiza-la é necessário que a prestação seja maior que os juros cobrados em cada período, ou seja, AMORTIZAÇÃO = PAGAMENTO – JUROS (o valor amortizado é o que sobra depois de descontados os juros). Os juros só incidem sobre o saldo devedor, onde SALDO DEVEDOR = DÍVIDA INICIAL – VALOR AMORTIZADO. As formas de amortizar financiamentos são denominados de "Sistemas de Amortização".
Sistema de Amortização Constante (SAC): Neste sistema, o saldo devedor é reembolsado periodicamente em valores de amortização iguais. Desta forma, o valor das prestações é decrescente, já que os juros diminuem a cada prestação. O valor da amortização é calculado dividindo-se o valor do principal (valor do
financiamento) pelo número de períodos de pagamento, ou seja, de parcelas. Assim,
 Valor da amortização: AMORTIZAÇÃO = PRINCIPAL / N
 Valor dos juros no mês T: JUROST = (N - T + 1) * AMORTIZAÇÃO * TAXA
 Valor da parcela em T: PRESTAÇÃOT = AMORTIZAÇÃO + JUROST
onde: PRINCIPAL é o valor do financiamento, N é o número de meses do financiamento, T denota o
mês em questão e TAXA é a taxa de juros mensal (que deve ser obtida a partir da taxa anual).
Se alguém puder me ajudar pelo menos com a lógica. Já é um grande começo.

A: Leia o enunciado do seu próprio problema, fazendo o grandíssimo favor,
import os

principal = float ( input ("1. Informe o valor a ser financiado: "))
os.system("cls")
n = int ( input ("2. Informe o prazo de quitação do financiamento (em meses): "))
os.system("cls")
taxa_juros_anual = float (input ("3. Informe a taxa de juros anual (em %): ")) / 100.0
os.system("cls")

Valor da amortização: AMORTIZAÇÃO = PRINCIPAL / N

amortizacao = principal / n

Uma busca por taxa mensal a partir da taxa anual juros compostos, no Google, devolve a seguinte fórmula,

1 + TAXA ANUAL = (1 + TAXA MENSAL) ^ 12 Fonte: aqui

taxa_juros_mensal = pow(1.0 + taxa_juros_anual, 1.0 / 12) - 1.0;

print ("AMORTIZAÇÃO: R$ %.2f" % amortizacao)
print ("VALOR DO FINANCIAMENTO: R$ %.2f\n\n" % principal)
print ("\t FINANCIAMENTO = R$ %.2f \t MESES: %i meses \t TAXA: %i%% ano (%.f%%)" %
    (principal, n, taxa_juros_anual, taxa_juros_mensal))
print ("\t","-"*80,"\n")
print ("\t MÊS\tSALDO INICIAL\tPRESTAÇÃO\tAMORTIZAÇÃO\t  JUROS\tSALDO FINAL")
print ("\t ---\t-------------\t---------\t-----------\t-------\t-----------")

saldo_inicial = principal
for t in range(1, n + 1):
    saldo_final = saldo_inicial - amortizacao
    juros = juros_t(t, n, amortizacao, taxa_juros_mensal)
    prestacao = amortizacao + juros

    print ("\t%4.i\t%13.2f\t%9.2f\t%11.2f\t%7.2f\t%11.2f" %
        (t, saldo_inicial, prestacao, amortizacao, juros, saldo_final))
    saldo_inicial = saldo_final

Valor dos juros no mês T: JUROST = (N - T + 1) * AMORTIZAÇÃO * TAXA

def juros_t(t, n, amortizacao, taxa):
      return (n - t + 1) * amortizacao * taxa

redpajama_set_name: RedPajamaStackExchange


text:
Q: My File Browser App Doesn't show any files, other than LOST.DIR I have made an app in Android, which is basically a File Browser. It shows all the files correctly in all devices perfectly, but not in one of my phones - Xperia SL.
It used to work properly in that phone, before I used ASYNC Task to load files asynchronously. After I did that, id doesn't show any file or any folder, just the LOST.DIR folder.
It works in all other phones perfectly, I have tested in 4-5 devices.
Can any one please suggest something?


text:
Q: getting "*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber compare:]: nil argument'" Though we have lot of people asked same question , none of the answers are helping to fix my issue. So here is my code ,
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"Response: %@", text);

    //The NSJSONSerialization method to transform the NSData responseObject into a dictionnary does work
    NSJSONSerialization *jsonResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];

    //This NSLog makes the app crash with an unrecognized selector sent error
    NSLog(@"JSON: %@",jsonResponse);

    NSArray *result1=(NSArray *)[jsonResponse valueForKeyPath:@"result"];

    NSLog(@"result1: %@",result1);

    NSMutableString  *shipPrice =[[NSMutableString alloc]init];
    NSMutableString  *freeLimitString =[[NSMutableString alloc]init];

    if(result1!=Nil && ![result1 count]==0)
    {
               for (int i=0; i<result1.count; i++)
               {
                    NSNumber *totalShippingPrice = [[result1  objectAtIndex:i] valueForKeyPath:@"totalShippingPrice"];
                    if( totalShippingPrice != nil && totalShippingPrice && [totalShippingPrice isEqualToNumber:0]&& [totalShippingPrice intValue]==0) // ISSUE LINE
                                {
                                    shipPrice = (NSMutableString*)@"FREE";
                                } } } }

I kept breakpoint and exactly its happening in this above line. Im new to AFNetworking. Im not sure how to fix it. Help me with working code sample :) Thanks

A: You need to use this:
[totalShippingPrice isEqualToNumber: [NSNumber numberWithInt:0]]

In the line that crashes.
You need to compare the object with another one of the same type, if you use 0 is the same as if you were sending nil to it, so you need to create a NSNumber as I wrote.
Or just do:
[totalShippingPrice intValue] == 0


text:
Q: SDL2 Key repeat delay I'm trying to develop a robust game input system with SDL 2.0.1. I want there to be no input lag at all.
I used to do this with SDL_GetKeyboardState(), but I switched over to using SDL_Event and SDL_PollEvent() to have a uniform interface for Keyboard, Mouse and Joystick input (everything done with events).
This works fine, but if I want a continuous input when the key is held down (e.g. to move a character), there is a slight delay before SDL notices that the key is being repeated.
In SDL 1.2, it was possible to set this delay using a function call. Now it is no longer (as far as I'm aware).
How can I remove this delay? Should I switch back to reading the Keyboard state directly?
For reference, here is how I'm currently getting input...
SDL_Event sdlEvent;
while (running)
{
    SDL_PollEvent(&sdlEvent);
    switch (sdlEvent.type)
    {
    case SDL_QUIT:
        running = false;
        break;
    case SDL_KEYDOWN:
        printf("Key down!\n");
        break;
    default:
        break;
    }
}

The application prints "Key down!", then nothing for a small time (about a second), and then repeatedly prints until the key is released.
So how do I get rid of this delay?

A: Since you're not getting an SDL_KEYUP you can just have a bool that's true until you get a SDL_KEYUP
SDL_Event sdlEvent;
while (running)
{
    bool keyDown = false;
    while ( SDL_PollEvent(&sdlEvent) )
    {
        switch (sdlEvent.type)
        {
            case SDL_QUIT:
                running = false;
                break;
            case SDL_KEYDOWN:
                keyDown = true;
                break;
            case SDL_KEUP:
                keyDown = false;
                break;
            default:
                break;
        }
    }
    if ( keyDown )
        printf("Key down!\n");
}

Of course you'll need something to store all keys, like an array. ( Or even better; use C++ with std::map) Then you can use the SDL_Keycode ( event.key.keysym.sym ) as key.

A: First, you should Poll your event into a loop, else you will just get one event per frame
so
SDL_Event sdlEvent;
while (running)
{
    while(SDL_PollEvent(&sdlEvent))
    {
        switch (sdlEvent.type)
        {
        case SDL_QUIT:
            running = false;
            break;
        case SDL_KEYDOWN:
            printf("Key down!\n");
            break;
        default:
            break;
        }
    }
}

And, to handle your Key Delay, should create a struct with the key pressed, and the timestamp when the key down was launch. You can put those struct into a vector and then remove them when key up is catched for this key. And to handle key delay just iterate your key down, and check the difference between the current timestamp and the key down inital timestamp.

A: As is noted here, the correct procedure to make this work cross-platform is using SDL keystates instead of events:
const Uint8* keystates = SDL_GetKeyboardState(NULL);

if(keystates[SDL_SCANCODE_DOWN])
{
    printf("Key down!\n");
}

In this way you bypass any OS-based keyboard delays.
A full tutorial:
http://lazyfoo.net/tutorials/SDL/18_key_states/index.php


text: Q: Creating a Rectangle object and attaching an Image to it in Java so I have this homework assignment where I have to create an rectangular object that can move around in a GUI and it must have a certain image specific to it (depending on the class) pasted on to the object. We haven't learned any graphics stuff stuff so i'm not sure what mehtods or anything to use. One the shapes are created I assume to move them I just change the x and y positions and draw them again or something like that. Someone suggested using imageicon or something. But could anybody give me some more specific advice?


text:
Q: How to store a unique filepath in database, too long for unique key I have a volume where I need to store the filepaths in a database. However, the filepaths are longer than the max length for a mysql index, so I'm not sure how I can store them and ensure uniqueness. An example path would be:
/Volume/00_ARCHIVE/Discovery/Alaska_The_Last_Frontier/2014-01-01/Alaska_The_Last_Frontier/DISC00000000927664/DISC00000000927664.mp4

How could I store this in mysql and ensure uniqueness on the path? The reason I need to do this is to see which paths have been removed (by doing a set diff), which paths are already there ( by doing a union) and which paths are new. How could I store this?
My first thought is to save an md5 checksum of the path?

A: Just hash it. MD5 or SHA1 is just fine, since you don't have to worry about security here.


text:
Q: HIVE UDF keep value from previous row I have a UDF that should return the content of the previous row. I implemented it with the following code. Unfortunately it always returns the value of the current row of parameter second. Does anyone have an idea what I am doing wrong?
@UDFType(stateful = true)

public class Strip extends UDF {

private Text result = new Text();
private static ArrayList<Text> lst;
int count=0;

public Strip(){
    result.set("");
}
public Text evaluate(Text first, Text second) {

    if (str == null | stripChars == null) {
return null;
}
if (lst == null)
{
    lst = new ArrayList<Text>();
    lst.add(second);
    return first;
}

result=lst.get(lst.size()-1);
lst.add(second);
return result;

}

Thanks in advance.


text:
Q: jQuery Horizontal image slider I need an images slideshow like this: http://livedemo00.template-help.com/wt_51115/
But without scrolling feature on mouse position. Did you know a plugin to recommend me? Thanks!

A: Check this one: FlexSlider 2
Easy to use. Has a lot configuration parameters. I think it is quite good.


text:
Q: Is that necessary to register scripts with @Html.Requires() if I am using @Styles.Render()? I is a asp net mvc 4 application and I am integrating an asp net mvc 3 app in it.
I have imported all js and css scripts and reference it using bundles.
Thing is this asp net mvc 3 application has a couples of @Html.Requires() (one for each js and css file.).
As I have never developed using asp net mvc 3, I am not sure those @Html.Requires() are nescessary. Also the documentation I found in microsoft msdn did not help much.


text:
Q: Best practices in two class if i need use a global class what is the best option and why?
public class Global {

    public static JSONObject GetJsonResquest(String url){
        ....
    };
}

and then call Global.GetJsonResquest(url) in my activity
OR
  public class Singleton {
    private static Singleton ourInstance = new Singleton();

    public static Singleton getInstance() {
        return ourInstance;
    }

    private Singleton() {
    }
    public JSONObject GetJsonResquest(String url){
      .....
    }
}

and then use via Singleton.getInstance().GetJsonResquest("Asd");

A: When I need a global static variable, I like to group them into a class like
public class MyConstants {
    public static final int TIMEOUT = 10000;
}

To use it, i can call it like
long tick = System.currentThreadMillis();
while((System.currentThreadMillis() - tick) < MyConstants.TIMEOUT){
    Thread.sleep(1000);
}

So that when I change the TIMEOUT value, I don't have to change other classes that calls it
For global static method, I use them like
public class Utility{
     public static boolean isStringValidJson(String jsonString){
         return false;
     }
}

Same reason as above. When I change isStringValidJson, other classes that calls it don't change
I do use the singleton pattern but only when I override the Application class. However, I set the instance value in OnCreate instead. This means that if OnCreate was not called, getInstance will return null
public class MyApplication extends Application {

    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static synchronized MyApplication getInstance(){
        return instance;
    }
}


text:
Q: while & foreach loop to group output of array I have an array of locations very similar to the below. What i would like to do is group by items that have the same SiteNumbers (See desired outcome), however im unsure of the best method to check the current sitenumber against the next to see if its different, currently i am checking if sitenumber = sitenumber. Any suggestions welcome
array ($locationList):
SiteNumber = 1001, Location = Kitchen, Position = Cupboard
SiteNumber = 1001, Location = Kitchen, Position = Fridge
SiteNumber = 1002, Location = Bedroom, Position = Bed
SiteNumber = 1002, Location = Bedroom, Position = Draws
SiteNumber = 1002, Location = Bedroom, Position = Wardrobe

Current code:
@while($locationList[0]->SiteNumber = $locationList[0]->CardNumber)

{{ $locationList->SiteNumber }}

                    Location
                    Position

                @foreach($locationList as $loclist)

                        {{ $loclist->Location }}
                        {{ $loclist->Position }}

                @endforeach

            @endwhile

The desired outcome, would look something like this:
Site Number = 1001
Location | Position
Kitchen | Cupboard
Kitchen | Fridge

Site Number = 2002
Location | Position
Bedroom | Bed
Bedroom | Draws
Bedroom | Draws

A: You can group the results by sitenumber using SQL.
"SELECT * FROM sites
 ORDER BY siteNumber"

You can go further by creating a new table for each sitenumber.
$siteNumber = 0;

if($siteNumber !== $locationList->SiteNumber) {
    $siteNumber = $locationList->SiteNumber;
    //Create new table
}

Of course you will have to convert the above to Laravel's templating system syntax.


text:
Q: How to remember username for next time on iPhone app? I am working on an iPhone/iOS app. It has a login page with two text fields "email" & "Password".Now i want to save email.
i.e When I logged out it should remember the email address so it doesn't have to be input again.
Please tell me how can I save email.

A: If you don't consider email sensitive. Use NSUserDefaults...
Saving
[[NSUserDefaults standardUserDefaults]setObject:@"example@email.com" forKey:@"email"];
[[NSUserDefaults standardUserDefaults]synchronize];

Retrieving
// getting an NSString
NSString *emailString = [[NSUserDefaults standardUserDefaults] stringForKey:@"email"];\

IMPROVE ANSWER
If you consider email sensitive. Use keychain instead.
To store
KeychainItemWrapper *keychain =
 [[KeychainItemWrapper alloc] initWithIdentifier:@"MyAppLoginData" accessGroup:nil];
[keychain setObject:loginStr forKey:(id)kSecAttrAccount];
[keychain setObject:pwdStr forKey:(id)kSecValueData];

To query
NSString *login = [keychain objectForKey:(id)kSecAttrAccount];
NSString *pwd = [keychain objectForKey:(id)kSecValueData];

To Delete:
[keychain resetKeychainItem];

To do this you will first need to add KeychainItemWrapper in you project.
Another important aspects of using keychain to store data is
The data is persistent even after app uninstall-install
Data can be shared across apps too. Read more here

A: In this case email is a part of user credentials, needed to login. So i would say it is sensitive information. Please do not ever use NSUserDefaults for storing sensitive data, that belongs to user. These defaults are stored as plist in binary format, they are not encrypted. Use Keychain Services API
provided by iOS instead.


text:
Q: Get a Content URI from a File URI? I am using the DownloadManager to download an image to the system's gallery and then in the Broadcast receiver (once the download succeeds) using an Intent to set the image as the wallpaper.
Everything was working fine but then recently on 4.4 I started to get an exception in the Photos/Google+ app because it is expecting a content URI and not a file URI.
So my question is if anyone knows how to convert a full file path/URI (file://) into a content style URI (content://)?
Sorry for the lack of source code, I am away from the computer that has the source, but I hope the question makes sense without it, get a content style uri from a full path.
EDIT:
The image is copied into the system's gallery or media gallery, not saved within my apps internal storeage.
Here is an example of what I want to convert:
file:///storage/emulated/0/Pictures/Rockstar/image.jpg

to
content://media/internal/images/media/445

EDIT 2:
Here is the error that I get from the Google+ app:
04-21 10:50:35.090: E/AndroidRuntime(7220): FATAL EXCEPTION: main
04-21 10:50:35.090: E/AndroidRuntime(7220): Process: com.google.android.apps.plus, PID: 7220
04-21 10:50:35.090: E/AndroidRuntime(7220): java.lang.RuntimeException: Unable to resume activity
{com.google.android.apps.plus/com.google.android.apps.photos.phone.SetWallpaperActivity}:
java.lang.IllegalArgumentException: Image URI must be of the content scheme type

Here is the code that I use to let the user set the wallpaper:
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Uri u = Uri.parse(uriString);
Intent wall_intent =  new Intent(Intent.ACTION_ATTACH_DATA);
wall_intent.setDataAndType(u, "image/*");
wall_intent.putExtra("mimeType", "image/*");
Intent chooserIntent = Intent.createChooser(wall_intent,
    "Set As");
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
    context.startActivity(chooserIntent);
}

Where uriString is:
file:///storage/emulated/0/Pictures/Rockstar/image.jpg

A: I was able to figure it out. It was a combination of the code found here: Converting android image URI and scanning the media file after downloading.
So after the file finished downloading I get the path and do the following:
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

//Update the System
Uri u = Uri.parse(uriString);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, u));

//Get the abs path using a file, this is important
File wallpaper_file = new File(u.getPath());
Uri contentURI = getImageContentUri(context, wallpaper_file.getAbsolutePath());

For some reason starting the media scanner, newing the file, and getting the absolute path are important, I'm not exactly sure why but I can't spend any more time on this!
The way to convert from a file URI to a content URI is as follows (taken from the linked StackOver flow post:
public static Uri getImageContentUri(Context context, String absPath) {
    Log.v(TAG, "getImageContentUri: " + absPath);

    Cursor cursor = context.getContentResolver().query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        , new String[] { MediaStore.Images.Media._ID }
        , MediaStore.Images.Media.DATA + "=? "
        , new String[] { absPath }, null);

    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
        return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , Integer.toString(id));

    } else if (!absPath.isEmpty()) {
         ContentValues values = new ContentValues();
         values.put(MediaStore.Images.Media.DATA, absPath);
         return context.getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    } else {
        return null;
    }
}

Maybe this will help someone in the future.

A:
So my question is if anyone knows how to convert a full file path/URI (file://) into a content style URI (content://)?

Implement a ContentProvider. FileProvider offers an out-of-the-box solution for serving up local files.

A: I'm not sure about the technique you are using to set the wallpaper but the easiest way is probably to use WallpaperManager.setStream() which doesn't require any URI.
Also note that a file URI only works between apps if the file is publicly accessible so a content URI is a more general solution.
Using a content URI implies that a ContentProvider will serve the file. Which one depends on where your file is located.
If your app has a direct read access to the file, you can implement a content provider in your app by using for example the FileProvider class of the support library, but this should really only be used if the file is located in the private data storage of your app.
If the image is added to the system media gallery, you should probably use the URI provided by the MediaStore.


text:
Q: Comparing items of two lists to scoop out the desired portion There are two lists- one contain list of states and the other contain list of addresses. What I'm trying to do is compare each of the state to each of the address in order to find if there is a match. When a match is found then the script should scoop out that portion from the addresses.
Here is what i did (working one):
state_list = ['AL', 'AK', 'AZ', 'AR', 'CO', 'CT', 'IL', 'MI']
addresses = ['Downers Grove IL 60515','Duarte CA 91010','Ann Arbor MI 48108']

for item in state_list:
    for address in addresses:
        if item in address:
            state = address
            print(state.split(" ")[-2])

Output:
IL
MI

Can I do the same making one liner approach rather than this clumsy looking loop?

A: You could also use regex for this.
import re

pattern = re.compile('|'.join(state_list))

[pattern.search(address).group(0) for address in addresses if pattern.search(address)]

['IL', 'MI']

Or using higher order functions
[m.group(0) for m in filter(None, map(pattern.search, addresses))]

['IL', 'MI']

A: print([state for state in state_list
       if any(state in addr for addr in addresses)])

Output:
['IL', 'MI']


text:
Q: Converting a Stream to String is returning void I am trying to write a program that will convert a Stream<String> into a String<Record> where everytime there is a comma in the string, it puts that data into one section of the data. My first thought on doing this was to use split() like so:
return fileToStream("data.csv").forEach(s -> s.split(","));

The fileToStream function is simply taking the data.csv and converting it into a Stream
I don't quite understand why this is returning void, any help would be greatly appreciated.
I expected it to take something like 123,hello,hello,hello,123,123 and instead of it all being one string, turning it into a record of int, string, string, string, double, double, etc.

A: forEach doesn't return anything (it is declared as public void forEach(Consumer<? super T> action)). You want to use Stream#map instead:

Returns a stream consisting of the results of applying the given function to the elements of this stream.

However, s.split will return a String array (String[]), not any sort of record. If you want to have instances of a class, you need to construct them, for instance with new Record(s.split(",")) or Record.fromArray(s.split(","))
The Record constructor/factory could then parse the array:
public static Record fromArray(final String[] array) {
  return new Record(
      Integer.parseInt(array[0]),
      array[1],
      array[2],
      array[3],
      Double.parseDouble(array[4]),
      Double.parseDouble(array[5]));
}

But since you are parsing a CSV file, you are better off using a CSV parser such as opencsv.

A: Assuming fileToStream is returning each record of the CSV as a stream what you wanna do is probably map to a record and then collect the result.
Foreach only loops throgh the Collection like an iterator, it doesn't return anything.
fileToStream("data.csv").forEach(s -> s.split(","));

is equivalent to:
for(String s : fileToStream("data.csv")) {
 s.split(","); // note that you are splitting and ignoring the return result
}

(It actually is a bit different as stream uses the default iterator and the collection iterator will use the forEach method of the collection, but in this use case we can ignore this fact for now, the result in this case is the same)
return fileToStream("data.csv").forEach(s -> s.split(","))
        .map(***your conversion logic***).collect(Collectors.toList()); //or toList() depending on your Java version


text:
Q: how to center a single element in slick.js jquery plugin I am using slick plugin and I have problem with centering items when there is only one element. My code:
$('#divId').slick({
   dots: false,
   infinite: true,
   speed: 300,
   slidesToShow: 1,
   centerMode: true,
   variableWidth: true
});

If I have few elements in the container everything is OK (centerMode works great) but when I have only one element in slick queue - it goes to the right hand side.
Real example
I couldn't reproduce that problem on jsfiddle. I coppied my code there but everything seems to be ok there: jfFiddle
Does anybody know where is the problem ?
Thanks in advance.


text:
Q: Should std::vectors be used extensively for embedded systems? When writing C++ code for an embedded system with limited CPU and Memory resources, the common rule of thumb is to instantiate objects in the stack, and avoid using the heap unless it is really necessary.  Doing this of course has many known benefits, but with the emergence of STL and folks recommending std::vectors as an efficient data structure, does it violate the rule of thumb that I mentioned, since the vector will be using the heap?
Example:  In the old days, one would declare static arrays with known sizes that will satisfy the usage. Nowadays, one would just use vectors.
I'm not really comfortable with this transition, since there is always a possibility of the vector failing to allocate the required memory (reminder: this is for embedded systems with limited memory). Using arrays with known sizes in the stack guarantees that there will be space for allocation during compile-time.
Calling reserve() kind of helps, but this is done during run-time.
So, is this a cause for concern, or am I just being paranoid?  It's definitely much more easier to use these vectors, but for an embedded environment, it might not be a good idea?
Note: This is not about dynamic vs fixed arrays, but more on how the data is allocated in memory, which is a big deal for my environment. As an example, some folks would do this: Say the array can grow or shrink between 1 to 10 elements. Some folks would create an array that covers this size in the stack, and NULL terminate depending on current size. This way, fragmentation is avoided, and we are guaranteed allocation during compile time.  However, switching to vector made it much more cleaner, but at the expense of using the heap, and potentially having to deal with exceptions if allocation fails. This is what I am concerned about.

A: "Depends" may be an understatement here. By using reserve with vectors, you can efficiently allocate space for the data and prevent unnecessary copies. The vector data structure itself will boil down to a heap allocated array with a size if the compiler is good enough.
Also, note I said heap. If you would rather allocate the data to the stack, your stuck with fixed sized arrays (including std::array).
And it also depends heavily on the compiler how vector is put together. Older compilers may (big emphasis on may) be less efficient. This is why for embedded systems you really need to know the architecture and compiler before making sweeping generalizations about what is "good" and what is "bad" to use.

A: std::vector should be used for dynamically resized arrays. If you know the size at compile time, you can use std::array instead.
If you know the only approximate size of array, since C++14 you may use std::dynarray. This array has fixed size which cannot be changed during object lifetime. When the std::dynarray without allocator is used additional optimisations are possible, the operator new may not be called and stack-based allocation will be used.

A:
Using arrays with known sizes in the stack guarantees that there will be space for allocation during compile-time.

Wrong assumption.
When your got a lot of call (not even recursive but a stack with a lot of level), you cannot be sure that there is enough space for your stack to hold the object that have to be created on.
There are basic checks (if the size of your object exceed size_t at least), but I do not even think they are made mandatory by the standard.
A -- somewhat excessive -- example is here:
#include <iostream>

template <unsigned long size>
struct BigObject
{
    unsigned long array[size * size];
    BigObject<size - 1> object;
};

template <>
struct BigObject<0>
{
    unsigned long array[1];
};

BigObject<900>& recurse(BigObject<900>& object1, unsigned long n)
{
    if (n == 0)
    {
        return object1;
    }

    BigObject<900> object;

    return recurse(object, n);
}

int main(int argc, char const *argv[])
{
    BigObject<900> object;
    recurse(object, 20);

    std::cout << sizeof(object) << std::endl;
    return 0;
}

http://ideone.com/pkHo43
It does crash.
And it is not such a special case. I had the problem in a 32 bit desktop oriented application  (so none of your memory constraint) allocating a too big array on the stack.

A: I believe that you have forgotten one very important property of the STL containers: allocators.
A STL container (whether a vector or otherwise) obtain all its memory from its allocator (apart from the very basic stack footprint that you can check with sizeof). Therefore, it is perfectly suitable in embedded development to provide a dedicated allocator that:

*

*will allocate from a pre-reserved memory area

*will bound the maximum resource consumption to prevent OOM

*...

With the advent of C++11, you may even use stateful allocators, so that a single allocator type can point to different pools of memory.
Therefore, the use of std::vector, or even std::set or std::map, is not incompatible with a pre-allocation strategy; do remember though that apart from std::vector other STL containers generally have some per-item overhead which must be taken into account when sizing the memory area they should draw upon.

A: A std::vector is just a pointer and two size_t when compiled with sufficient optimization flags. Now the memory for the size_t is a waste when your know the size of the vector in advance and it will never change.
I would say:

*

*Fixed (small) size => simple array or std::array

*Dynamic size or huge number of elements => std::vector
And as mentioned in the comments, you can use most of the functionality of e.g. <algorithms> on fixed size arrays by using pointers for the begin/end iterators.
For example:
int array[8] = { 1,2,3,4,5,6,7,8 };
std::random_shuffle(array, array+8);


text:
Q: How to read value from website I just want to read (-1) value which is the only value in website but I am not able to fetch this value Can any buddy guide me how to do that. I am getting the value of API url when I am pasting it in web browser and android is not fetching it. Link of API is given below.
Link OF API
Code I am trying is:
    private void getWebsite() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder builder = new StringBuilder();

            try {
                Document doc = Jsoup.connect("https://api.thingspeak.com/channels/411172/feeds.json?results=1").get();
                String title = doc.title();
                Elements links = doc.select("[pre]");

                builder.append(title).append("\n");

                for (Element link : links) {
                    builder.append("\n").append("Link : ").append(link.attr("pre"))
                            .append("\n").append("Text : ").append(link.text());
                }
            } catch (IOException e) {
                builder.append("Error : ").append(e.getMessage()).append("\n");
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.setText(builder.toString());
                }
            });
        }
    }).start();
}

Screen shot of web API call in browser

Error I am getting is Error: HTTP error fetching URL

A: As I see response from your API is JSON formatted you have to modify your code as follow
private void getWebsite() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder builder = new StringBuilder();

            try {
                Document doc = Jsoup.connect("https://api.thingspeak.com/channels/411172/feeds.json?results=1")
                        .ignoreContentType(true)
                        .get();
                String json = doc.body().text();
                builder.append(json);

            } catch (IOException e) {
                builder.append("Error : ").append(e.getMessage()).append("\n");
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.setText(builder.toString());
                }
            });
        }
    }).start();
}


text:
Q: How to open overlay menu from oncomplete of p:commandButton with Primefaces? I'm using Primefaces 3.3.1 and have question.
I have p:commandButton inside p:column of p:dataTable. I can show overlay menu when button is clicked with xhtml shown below.
    <p:commandButton id="btnID" icon="ui-icon-circle-triangle-s" style="height: 16px;">
        <f:setPropertyActionListener value="#{searchItem}" target="#{bean.selectedSearchItem}" />
    </p:commandButton>
    <p:slideMenu overlay="true" trigger="btnID" my="left top" at="left bottom"
            model="#{bean.menuModel}"/>

In this case, bean.menuModel can return menu data instantly. But I have another case also which pre-procsessing is required to make menu data ready. So I have this one too.
    <p:commandButton ajax="true" id="historyButton" action="#{bean.getHistory()}"
        icon="ui-icon-note" style="height: 16px;"
        onstart="workingDialog.show();"
        oncomplete="workingDialog.hide(); historyMenu.show();">
        <f:setPropertyActionListener value="#{searchItem}" target="#{bean.selectedSearchItem}" />
    </p:commandButton>
    <p:menu overlay="true" widgetVar="historyMenu" my="left top" at="left bottom"
            model="#{searchBean.menuModel}"/>

What I meant is, when button is clicked, it calls bean.getHistory() which starts loading menu data for that row, and show modal dialog with circling icon. When loading is finished, dialog will go away and overlay menu will be shown. What I can't do is a last part of this scenario. Above code fires exception.
java.lang.NullPointerException
    javax.faces.component.UIComponentBase.findComponent(UIComponentBase.java:561)
    org.primefaces.component.menu.BaseMenuRenderer.encodeOverlayConfig(BaseMenuRenderer.java:138)
    org.primefaces.component.menu.MenuRenderer.encodeScript(MenuRenderer.java:45)
    org.primefaces.component.menu.BaseMenuRenderer.encodeEnd(BaseMenuRenderer.java:39)
    javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)

Code shown below works fine, without menu related code.
    <p:commandButton ajax="true" id="historyButton" action="#{searchBean.getHistory()}"
        icon="ui-icon-note" style="height: 16px;"
        onstart="workingDialog.show();"
        oncomplete="workingDialog.hide();">
        <f:setPropertyActionListener value="#{searchItem}" target="#{bean.selectedSearchItem}" />
    </p:commandButton>

I guess this is easy question for experts. How can I open overlay menu from oncomplete?
Thanks in advance.

A: I could not find a solution for this issue but I came up with conclusion that what I wanted to do is not a good idea with the environment I'm working on.
First, I noticed that menu gets data from bean when row of data table is populated, not when menu is shown. And there is no lazy loading mechanism for menu. So button click -> get data for menu from server -> open menu cannot be done as I expected (at least it seems to me).
Second, I noticed putting menu in DataTable (under TabView in my case) causes very strange problem. When I update DataTable, some ajax related function stops working. I can't explain this problem to make you understand or believe, but app I'm working on is having this problem.
So, I gave up putting menu in DataTable in my app. Thank you for your attention.
I accept this answer not to lower my already LOW accept rate.


text:
Q: Rotate an array clockwise Say I have multidimensional array like this:
int arr[3][3] = {{1, 2, 3},
                 {4, 5, 6},
                 {7, 8, 9}};

I'd like to rotate the array clockwise so it looks like this:
{{7, 4, 1},
 {8, 5, 2},
 {9, 6, 3}};

I tried swapping each of the values in turn with their previous value:
    swap(&arr[0][0],&arr[0][1]);
    swap(&arr[0][1],&arr[0][2]);
    swap(&arr[0][2],&arr[1][2]);
    swap(&arr[1][2],&arr[2][2]);
    swap(&arr[2][2],&arr[2][1]);
    swap(&arr[2][1],&arr[2][0]);
    swap(&arr[2][0],&arr[1][0]);
    swap(&arr[1][0],&arr[0][0]);

This didn't rotate correctly. It left a few values where they were and put the others in the wrong places.
What am I doing wrong, and how can I achieve this?

A: You might note that after rotation, the elements of the first row of the rotated array come from the first column of the original array, in reverse order with respect to the indices. Similarly, the second row of the rotated array comes from the second column of the original array, and so on. With this in mind, you can write a function that fills a new array with appropriate values from the original array, before copying the new values into the original array.
The function rotate_array() iterates over the array rotated. The elements of the ith row of rotated come from the ith column of the input array a. The jth element of ith row of rotated is the n-j-1th element of the ith column of a. The memcpy() function is then used to copy the contents of the rotated array into the original array.
#include <stdio.h>
#include <string.h>

void print_array(size_t n, int a[n][n]);
void rotate_array(size_t n, int a[n][n]);

int main(void)
{
    size_t arr_sz = 5;
    int arr[arr_sz][arr_sz];

    for (size_t i = 0; i < arr_sz; i++) {
        for (size_t j = 0; j < arr_sz; j++) {
            arr[i][j] = i * arr_sz + j + 1;
        }
    }

    puts("Before rotation:");
    print_array(arr_sz, arr);
    putchar('\n');

    rotate_array(arr_sz, arr);
    puts("After rotation:");
    print_array(arr_sz, arr);
    putchar('\n');

    return 0;
}

void print_array(size_t n, int a[n][n])
{
    for (size_t i = 0; i < n; i++) {
        for (size_t j = 0; j < n; j++) {
            printf("%5d", a[i][j]);
        }
        putchar('\n');
    }
}

void rotate_array(size_t n, int a[n][n])
{
    int rotated[n][n];
    for (size_t i = 0; i < n; i++) {
        for (size_t j = 0; j < n; j++) {
            rotated[i][j] = a[n - j - 1][i];
        }
    }
    memcpy(a, rotated, sizeof a[0][0] * n * n);
}

Before rotation:
    1    2    3    4    5
    6    7    8    9   10
   11   12   13   14   15
   16   17   18   19   20
   21   22   23   24   25

After rotation:
   21   16   11    6    1
   22   17   12    7    2
   23   18   13    8    3
   24   19   14    9    4
   25   20   15   10    5

A: You do not need eight swaps to rotate the matrix, because the last two swaps put two items in their places. The additional swaps put their operands into wrong spots again.
The center item is left in its place. First four swaps place four items in their new spots; the last two pairs are taking each others' new spots, so only two swaps are sufficient to complete the rotation.
swap(&arr[0][0], &arr[2][0]);
swap(&arr[0][1], &arr[1][0]);
swap(&arr[0][2], &arr[2][0]);
swap(&arr[1][0], &arr[2][1]);
swap(&arr[1][2], &arr[2][1]);
swap(&arr[2][2], &arr[2][0]);

Demo.


text:
Q: How to write a webscript to returns the ticket for the current user? I need to implement a web script that generates a returns the ticket for the current user. This web script is addressed by the URI I use to setup a URLConncetion. The ticket should be contained in the response body, which I need to evaluate in my JSP (or Java code) to extract the ticket. How can be done by a simple JavaScript / FreeMarker web script, using the JavaScript session root scope object to retrieve the ticket, i.e. session.getTicket() ?
Can any one pls write the steps to do?

A: ticket.get.html.ftl (or json or whatever you want):
${session.ticket}


text:
Q: How to adjust width of the image on the slick-track I have a problem about the width of slick.js Where the box on the slick-track exceeds the page on the website.
Please pay attention to the image I uploaded this:

for the use of my program code more or less like this:

jQuery('.image-slider').slick({
  slidesToShow: 1.7,
  slidesToScroll: 1,
  autoplay: true,
  autoplaySpeed: 2000,
  arrows: false,
  dots: false,

});
.image-slider .slick-slide {
  margin: 0 2px;
  display: inline-block;
}

.image-slider a {
  display: block;
  width: 100%;
}

.image-slider img {
  width: 860px;
  height: auto;
  margin-top: 0px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" />

A: I couldn't work this out for ages myself. I was changing the

in the div's but that didn't work. Also I'm using tables so its even more complicated. This can create lots of white space after the images.
Because the whole thing is responsive you need to use width with a percentage to make them work correctly, so that it scales as you change your screen width.

or some percentage of the screen.


text:
Q: How to change visibility of a div slidely with jQuery? A div is required to be hidden with the following style:
.result-container
{
    visibility: hidden;
}

I would like to show this div by applying a sliding down animation.
$(".result-container").slideDown("slow"); would work if the div had display: none;, but it doesn't.
How do I have .slideDown() toggle the visibilityproperty instead of display?

A: Just set the container to be visible and undisplayed and then apply .slideDown().
$button = $('.button');
$container = $('.container');

$button.click( function(event) {
  event.preventDefault();
  $container
    .css({
      visibility: 'visible',
      display: 'none'
    })
    .slideDown();
});

Demo: http://jsbin.com/sefor/1/edit


text:
Q: How can i select a specific column of Entity Dynamically? JPA/querydsl can i implement the following through querydsl or Spring Data JPA?

*

*I have a Table(Column: A,B,C)

*I want to select a specific column of Entity(Table)

*Specific columns are defined as List. (Each element matches column name)

Thank you.

A: @Query(value = "select ?1 from Tablename")
public List<String> readAColumn(String columnname);

A: in your service you could have a method similar to
private List<Object[]> selectByColumnNames(ArrayList<String> columnNames) {
    return entityManager.createQuery("select " + StringUtils.join(columnNames, ",") + " from YourEntityName")
            .getResultList();
}


text:
Q: replace whitespaces in array using javascript. simple but a twist I have a very odd error. Here is the output of a array if i do a console.log(array);
[" TRUE ", " FALSE "]

I want the output to be
["TRUE", "FALSE"]

There should not be any whitespaces between the quotes. I hope you get my point. so the array elements doesnt have spaces actually.
Could anyone pls let me know how to remove the whitespace. If there are whitespaces between the double quotes, i am not able to display the details to checkbox in jqgrid.

A: var arr = [" TRUE ", " FALSE "]
for(var i=0; i< arr.length; i++) {
    arr[i] = arr[i].trim();
}

A: an alternative to @jrath's answer:
var arr = [" TRUE ", " FALSE "];
arr = arr.map(function(value){
  return value.trim()
});

BTW you should almost certainly fix this problem where you make the array, not where you display the array

A: function format(arr){
 $.each(arr, function(index,item){ arr[index] = arr[index].trim()});
}


text:
Q: Exported Azure Resource Group Template has null parameters Trying to recreate a resource group from template I previously exported but getting this error :
The value of deployment parameter 'Redis_polyrediscachegraphicsxp_name' is null. Please specify the value or use the parameter reference.
Indeed the parameters.json file has null values :
 "parameters": {
    "Redis_polyrediscachegraphicsxp_name": {
        "value": null
    },
    "storageAccounts_polystorgraphicsxp_name": {
        "value": null
    },
    "databaseAccounts_polycosmosgraphicsxp_name": {
        "value": null
    }
}

How can this be fixed ?

A: The error already shows the mistake you made. Your parameters are null. So you need to change your parameters.json file with the right values like this:
"parameters": {
    "Redis_polyrediscachegraphicsxp_name": {
        "value": "xxxxxx"
    },
    "storageAccounts_polystorgraphicsxp_name": {
        "value": "xxxxxx"
    },
    "databaseAccounts_polycosmosgraphicsxp_name": {
        "value": "xxxxxx"
    }
}

Take the example here.


text:
Q: processing large data file from s3 I have a large data files in parquet format stored on s3. The files can contain upto 48 million records, which need to be processed.
My current stack in Spring boot/K8, but i dont think this will work in this context.
The data is updated once a week, so processing it and storing in a DB seems pointless.
I could potentially be doing: Millions of single row queries OR 100's of queries which return 100K rows. So if the latter i would need to send this across the wire..
What could i potentially use to query the data efficiently? EMR? Athena?


text:
Q: Why does using square brackets cause a subscripted value is neither array nor pointer nor vector error? I'm new to C and I'm trying to become familiar with the basics, I thought id make a program that just takes an array and uses a function to print the information in the array. However, when I try to compile this program I get the following error:
error: subscripted value is neither array nor pointer nor vector
           printf(" %d", data[i]);
                             ^

The code I'm currently using is below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int maxReturn(int a, int b, int c, int d);

int main(){

    int arr[4] = {1,4,8,2};

    int max = maxReturn(arr[0],arr[1],arr[2],arr[3]);

    printf("%d\n", max);

    return 0;
}

int maxReturn(int a, int b, int c, int d){

    int data = {a,b,c,d};

    for(int i; i < 4; i++){
        printf(" %d", data[i]);
    }
    printf("\n");

    return data;

}

I'm at a bit of a loss as to what is wrong here because in the tutorials I'm following they print out values by using data[i]. Why is this not ok?

A: You are declaring an int using the {...} construct as if you were initializing an array. Probably, you forgot to declare data as an array of int.
Replacing the line:
int data = {a,b,c,d};

with:
int data[4] = {a,b,c,d};

should fix your problem.
EDIT:
You might not even define the size of the array in this case, because using the {...} construct the compiler computes the size of the array at build-time.


text:
Q: Which he doesn't or does? Here's the context:
A dying man has guilt, and one of the voices in his head is claiming he will experience hell, if he dies with it (the guilt). One voice hints that 'hell is a hoax', and the other then replies:

Only if he has no guilt, which he doesn't.

Should that have been phrased:

Only if he has no guilt, which he does.

To indicate that the dying man does actually have guilt, which he mustn't.
Thanks!

A: The very fact that this question comes up indicates that the phrasing is confusing, and a complete rephrasing is in order.
Perhaps "Only if he is free of guilt, which he isn't."


text:
Q: Alternatives to secure WCF service I need to build a WCF service which will be consumed by several clients, including mobile apps, web client, IVR (voice recognition) etc. I want to create separate user credentials database, moreover, I want .net to create it for me along with all authentication mechanism. So far I know that such technologies as Web Matrix, ASP.NET Membership offer what I need, but is there any alternatives? What I need is:

*

*Auto-created membership database

*Authentication/authorization out of box (by this I mean ready-to-use methods which I can apply as attributes etc.)

*Possible social networks support ( as far as I know, this requires OAuth2 support)

Note that I almost certainly will use protocols other than HTTP, and this service won't be RESTful.


text:
Q: Rails: return a string if no object found instead of sending the method I have a Notification model that is associated to a User model through "origin_user".
I am looking for a shortcut to this:
if notification.origin_user.present?
  notification.origin_user.name
else
  "a user"
end

Isn't there magic all-in-one function?

A: notification.origin_user.try(:name) || "a user"

But if youpromise a User, give a User. You could rely on the NullObject Design Pattern.


text:
Q: Vector smash protection is enabled PowerShell After issuing following command Invoke-WebRequest ekonomika.idnes.cz in PowerShell, its execution stops and I receive this message Vector smash protection is enabled. One of the cpu cores runs on 100%
A search on google did not reveal much more information - rather the opposite. Any ideas?

A: You are probably getting an IE prompt that looks like this:

To bypass this use the -UseBasicParsing switch:
Invoke-WebRequest ekonomika.idnes.cz -UseBasicParsing


text:
Q: What do I have to import to use the DataContractAttribute? As stated in the question. what do I have to import to use the DataContractAttribute?
as i have generated the file using the svcutil, it generated a file with that attribute and after adding it to my winform app, there seems to be an missing reference.
Using ????

anyone can help me with it?

A: You'll need to add a reference to the System.Runtime.Serialization assembly and then add the following using directive:
using System.Runtime.Serialization;


text:
Q: Loop through a selection , copying the selection to another sheet I'm trying to update a sheet with information from a filled in previous version.
It is a repeating block which moves down 13 rows eacht time. So trying to loop in combination with copying my selection, since there are only 11 values I need (the 1st and 13th contain information I do not want to overwrite)
The code I use is the following.
Sub Get_Data_From_File()
    Dim FileToOpen As Variant, i As Long, KolB As Long, KolG As Long
    Dim OpenBook As Workbook
    Dim m As Integer, n As Integer
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Select file to import", FileFilter:="Excel Files (*.xls*),*xls*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
            For i = 1 To 53
                m = -8 + i * 13
                n = 2 + i * 13
                With ActiveSheet
                .Blad2.Range("B" & m & ":G" & n).Select
*'                .Blad2.Range("B" & CStr(m) & ":G" & CStr(n)).Copy*
                ThisWorkbook.Worksheets("blad2").Range("B" & CStr(m) & ":G" & CStr(n)).PasteSpecial xlPasteValues
              End With
            Next i

        OpenBook.Close False

    End If
    Application.ScreenUpdating = True
End Sub

when I use this, I get a 483 error in the line ".Blad2.Range("B" & CStr(m) & ":G" & CStr(n)).Copy"
so I tried it with the " .Blad2.Range("B" & m & ":G" & n).Select" line
It does not seem to work. If you have any ideas, that would be appreciated.
thanks in advance


text:
Q: Evaluating min/max probability with Geometric random variables This is an exercise problem that I am solving from the book Probability and Random Processes for Electrical and Computer Engineers (Gubner, 2002) that I'm having trouble understanding. For anyone curious, the problem is Exercise 18 from Chapter 2.

Suppose that $X_1,\dots,X_n$ are independent, $\text{geometric}_1(p)$ random variables. Evaluate $P(\text{min}(X_1,\dots,X_n) \gt l)$ and $P(\text{max}(X_1,\dots,X_n) \le l)$.

The textbook solution is as follows:
$$
\begin{align}
P(\text{min}(X_1,\dots,X_n) \gt l) & = P\left( \bigcap_{k = 1}^n \{X_k \gt l\} \right) \\\
& = \prod_{k = 1}^n P(X_k \gt l) \\\
& = \prod_{k = 1}^n p^l \\\
& = p^{ln} \end{align}
$$
and
$$
\begin{align}
P(\text{max}(X_1,\dots,X_n) \le l) & = P\left( \bigcap_{k = 1}^n \{X_k \le l\} \right) \\\
& = \prod_{k = 1}^n P(X_k \le l) \\\
& = \prod_{k = 1}^n (1 - p)^l \\\
& = (1 - p^l)^n \end{align}
$$
I'm having trouble understanding pretty much the entire solution. If I were to summarize what's particularly puzzling me:

*

*How was the first line of each solution derived (i.e. $P(\text{min}(X_1, \dots, X_n \gt l) = P(\cap_{k = 1}^n \{X_k \gt l \}) $ and the corresponding equation for $\text{max}$)?

*The PMF for $\text{Geometric}_1(p)$ is given as $p_X(k) = (1 - p)p^{k - 1}$. How is $P(X_k \gt l) = p^l$? The same applies for the $\text{max}$ case as well.

A: 1) This is because the minimum of a set of numbers is greater than $l$ if and only if all the numbers are greater than $l$. So $\min(X_1,\ldots,X_n)>l$ if and only if $X_1 > l$ and $X_2 > l$ and ... and $X_n > l$. Note that the event "$X_1 > l$ and $X_2 > l$ and ... and $X_n > l$" is written as $\bigcap\limits_{k=1}^{n}\{ X_k > l\}$. Thus $$P(\min(X_1,\ldots,X_n) > l) = P\left(\bigcap\limits_{k=1}^{n}\{ X_k > l\}\right).$$
The $\max$ case is similar reasoning; it's because the maximum of a set of numbers is less than or equal to $l$ if and only if all the numbers are less than or equal to $l$.
Note that what I said above holds true regardless of the distribution of the $X_k$'s.
2) Note that if $X$ has PMF $(1-p)p^{k-1}$ for $k\ge 1$, then for any integer $l\ge 1$, we have
$\begin{align*}P(X \le l) &= \sum\limits_{k=1}^{l} P(X=k) \\ &= \sum\limits_{k=1}^{l}  (1-p)p^{k-1} \\ &= (1-p)\times \frac{1-p^{l}}{1-p} \quad(\text{using the }\textbf{geometric series formula})\\ &= 1-p^l.\end{align*}$
(And so $P(X > l) = 1-P(X\le l) = p^l$.)


text:
Q: Laravel 5.3 and Vue Webpack setup Hello I am getting JS errors in app.js. Basically it is not liking require('./bootstrap'); and gives the error:
all.js:50750 Uncaught ReferenceError: require is not defined

My app.js:
/**
 * First we will load all of this project's JavaScript dependencies which
 * include Vue and Vue Resource. This gives a great starting point for
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

my package.json:
{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "buble": "^0.13.2",
    "buble-loader": "^0.3.1",
    "css-loader": "^0.25.0",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-11",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.16.2",
    "style-loader": "^0.13.1",
    "vue": "^2.0.3",
    "vue-hot-reload-api": "^1.2.0",
    "vue-html-loader": "^1.2.3",
    "vue-loader": "^9.7.0",
    "vue-resource": "^1.0.3",
    "vue-style-loader": "^1.0.0",
    "webpack": "^1.13.2"
  }
}

Example.Vue:
    <template>

Example Component

                            I'm an example component!

    </template>

I also have a webpack.config.js:
'use strict'

const path  = require('path')

module.exports = {
    module: {
        loaders: [
            {
                test: /\.js$/,
                include: path.join(__dirname, 'resources/assets'),
                exclude: /node_modules/,
                loader: 'buble',
            },
            {
                test: /\.vue$/,
                loader: 'vue',
            },
            {
                test: /\.css$/,
                loader: 'style!css'
            },
        ]
    },
}

bootstrap.js file
window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');

/**
 * Vue is a modern JavaScript library for building interactive web interfaces
 * using reactive data binding and reusable components. Vue's API is clean
 * and simple, leaving you to focus on building your next great project.
 */

window.Vue = require('vue');
require('vue-resource');

/**
 * We'll register a HTTP interceptor to attach the "CSRF" header to each of
 * the outgoing requests issued by this application. The CSRF middleware
 * included with Laravel will automatically verify the header's value.
 */

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from "laravel-echo"

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: 'your-pusher-key'
// });

my gulpfile.js
const elixir = require('laravel-elixir');

require('laravel-elixir-webpack-official');

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */
var paths = {
    'cssstyles': 'resources/assets/css/',
    'jsscripts': 'resources/assets/js/',

    'adminlte': 'vendor/bower_components/AdminLTE/',
    'bootstrap': 'vendor/bower_components/bootstrap/',
    'chartjs': 'vendor/bower_components/Chart.js/dist/',
    'fastclick': 'vendor/bower_components/fastclick/',
    'fontawesome': 'vendor/bower_components/font-awesome/',
    'jquery': 'vendor/bower_components/jquery/',
    'slimscroll': 'vendor/bower_components/slimScroll/',
    'datatables': 'vendor/bower_components/datatables.net/',
    'moment': 'vendor/bower_components/moment/',
    'bootstrapgrowl': 'vendor/bower_components/bootstrap-growl/'
}

elixir.config.sourcemaps = false;

elixir(function(mix) {
    mix.sass('app.scss', paths.cssstyles)
        .styles([
            paths.bootstrap + 'dist/css/bootstrap.css',
            paths.fontawesome + 'css/font-awesome.css',
            paths.adminlte + 'plugins/datatables/dataTables.bootstrap.css',
            paths.adminlte + 'dist/css/AdminLTE.css',
            paths.adminlte + 'dist/css/skins/skin-blue.css',
            paths.adminlte + 'plugins/select2/select2.css',
            paths.cssstyles + 'dataTables.fontAwesome.css',
            paths.cssstyles + 'app.css'
        ], 'public/css/', './')

        .scripts([
            paths.jquery + "dist/jquery.js",
            paths.moment + 'moment.js',
            paths.bootstrap + "dist/js/bootstrap.js",
            paths.datatables + "js/jquery.dataTables.js",
            paths.fastclick + "lib/fastclick.js",
            paths.adminlte + "dist/js/app.js",
            paths.adminlte + 'plugins/daterangepicker/daterangepicker.js',
            paths.adminlte + 'plugins/select2/select2.js',
            paths.adminlte + 'plugins/datatables/dataTables.bootstrap.js',
            paths.slimscroll + "jquery.slimscroll.js",
            paths.chartjs + "Chart.js",
            paths.bootstrapgrowl + 'jquery.bootstrap-growl.js',
            paths.jsscripts + "app.js"
        ], 'public/js/', './')

    mix.webpack('app.js');

});

I have spent hours on this and the documentation on the web is not very clear as I am confused between browserify and webpack. I do want to state that I am not very front end savvy. Just want to have things in order so that can utilize Vue in future. Thank you for your assistance.

A: So dumb. I was not including the generated JS file. Thanks to everyone that took a stab at this.


text:
Q: I want to block a iam-test-user from production-ec2instance I want to block a iam-test-user from production-ec2instance with ec2 tag.
I think IAM policy have implicit deny.
So I added tag "Purpose/Test" to test-ec2instance.
And I applied a iam-policy-file below to iam-test-user.
{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "ec2:*",
        "Resource": "*",
        "Condition": {"StringEquals": {"ec2:ResourceTag/Purpose": "Test"}}
    }
] }

But iam-test-user can't see all ec2instance include test-ec2instance on aws-console.
Is the json file wrong?

A: Your policy is saying:

*

*Allow this entity to do anything (ec2:*) on EC2...

*If the resource has a tag of Purpose:Test
This should work when starting and stopping an instance with that tag.
Then you say: can't see all ec2instance include test-ec2instance on aws-console
The API call that returns a list of instances is DescribeInstances. This command is NOT related to a single instance, so it is unable to use tags. Therefore, the command will not function.
While you might think that you are assigning permissions so that they can only list Test instances, the command that lists instances does not look at the tags on the instances themselves. It just lists instances.
Here is an example:

*

*I only give you permission to talk to anyone who has a name of 'Keisuke'

*I then ask you to count how many people are standing in a room

The room does not have a name of Keisuke, so you cannot count the number of people in the room.
Similarly, it is not possible to limit the instances returned from a DescribeInstances command. You either give entities permissions to list the all, or list none.


text:
Q: Convention for multi-view iOS application I'm new to developing iOS applications, but I have a quick question about implementing a multi-view application.
I'm assuming to create an application with multiple views I must create my view controller classes, and instantiate all of them within my appDelegate class in order to switch back and forth between views?

A: Maybe.
With a UINavigationController you typically instantiate them in your current view controller, in response to some user action, then push the new controller onto the the UINavigationController stack.
If you're using a UITabBarController, you need to instantiate them before you put them in the tab bar, so you might do that in the app delegate in application:didFinishLaunchingWithOptions:.
It depends on how you plan to switch between them.

A: UINavigationController is your friend Casey..This tutorial will explain it..No need to create all viewControllers in appDelegate.


text:
Q: How has Stack Overflow implemented related tags functionality (Data Structure + Method)? I want to know how to implement related tags functionality on a site like Stack Overflow.
I have questions coming with a set of tags (maximum of 5) as input for training the system. I then have to find out related tags given a single/double/triple tag as input.
Example -

*

*A user lands on page First Landing Page.
Observation: User can see list of related tags along with the counts for the tag 1 - solr (in this case)

*The user clicks on one of the related tags, Second Page.
Observation: The user now sees questions related to both the tags and related tags to both two tags selected together as an entity.

I just need to know an efficient data structure and method to implement the same and am not looking for complete code here. I want to know the implementation part and not the way related tags are defined.
The duplicate suggested question discuss about how those related tags are calculated, not how they are implemented. When we talk about implementation, it means taking about data structures and methods. I know already that it's based on occurrence. Please note that difference.
Let me know if I am unclear in asking my question.


text:
Q: Por que o pdo não reconhece id? estou tendo um problema MUITO estranho.
Vejam essa mensagem:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'idUsuario' cannot be null' in /home/vigil982/public_html/php/enviaMsgLogra.php:46
  Stack trace:#0 /home/vigil982/public_html/php/enviaMsgLogra.php(46): PDOStatement->execute()
1 {main}

<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

header('Content-Type: text/html; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,X-Prototype-Version,X-Requested-With');

include_once("conPDO.php");

$pdo = conectar();

$data = file_get_contents("php://input");
$data = json_decode($data);
//print_r($data);

$msg = $data->mensagem;
$msg = utf8_decode($msg);
$idUsuario  = $data->idUsuario;
$idCep  = $data->idCep;
$nomeRemetente  = $data->nome;
$uf = $data->uf;
$cidade = $data->cidade;
$bairro = $data->bairro;
$logradouro = $data->logradouro;
$dia  = $data->dia;
$hora  = $data->hora;
$foto = '';

$cidade = utf8_decode($cidade);
$bairro = utf8_decode($bairro);
$logradouro = utf8_decode($logradouro);

$insereMsgLogra=$pdo->prepare("INSERT INTO avisosLogradouro (idAvisoLogradouro, idUsuario, estado, cidade, bairro, logradouro, msg, foto, data, hora) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insereMsgLogra->bindValue(1, NULL);
$insereMsgLogra->bindValue(2, $idUsuario);
$insereMsgLogra->bindValue(3, $uf);
$insereMsgLogra->bindValue(4, $cidade);
$insereMsgLogra->bindValue(5, $bairro);
$insereMsgLogra->bindValue(6, $logradouro);
$insereMsgLogra->bindValue(7, $msg);
$insereMsgLogra->bindValue(8, $foto);
$insereMsgLogra->bindValue(9, $dia);
$insereMsgLogra->bindValue(10, $hora);
$insereMsgLogra->execute();
//var_dump($idUsuario);
$idAvisoLogradouro = $pdo->lastInsertId();

$insereMsgBairro=$pdo->prepare("INSERT INTO avisosBairro (idAvisoBairro, idUsuario, estado, cidade, bairro, msg, foto, data, hora) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insereMsgBairro->bindValue(1, NULL);
$insereMsgBairro->bindValue(2, $idUsuario);
$insereMsgBairro->bindValue(3, $uf);
$insereMsgBairro->bindValue(4, $cidade);
$insereMsgBairro->bindValue(5, $bairro);
$insereMsgBairro->bindValue(6, $msg);
$insereMsgBairro->bindValue(7, $foto);
$insereMsgBairro->bindValue(8, $dia);
$insereMsgBairro->bindValue(9, $hora);
$insereMsgBairro->execute();
//var_dump($idUsuario);
$idAvisoBairro = $pdo->lastInsertId();

$insereMsgCidade=$pdo->prepare("INSERT INTO avisosCidade (idAvisoCidade, idUsuario, estado, cidade, msg, foto, data, hora) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$insereMsgCidade->bindValue(1, NULL);
$insereMsgCidade->bindValue(2, $idUsuario);
$insereMsgCidade->bindValue(3, $uf);
$insereMsgCidade->bindValue(4, $cidade);
$insereMsgCidade->bindValue(5, $msg);
$insereMsgCidade->bindValue(6, $foto);
$insereMsgCidade->bindValue(7, $dia);
$insereMsgCidade->bindValue(8, $hora);
$insereMsgCidade->execute(); // or die(print_r($pdo->errorInfo()));
//var_dump($idUsuario);
$idAvisoCidade = $pdo->lastInsertId();

$insereMsgEstado=$pdo->prepare("INSERT INTO avisosUF (idAvisoUf, idUsuario, estado, msg, foto, data, hora) VALUES (?, ?, ?, ?, ?, ?, ?)");
$insereMsgEstado->bindValue(1, NULL);
$insereMsgEstado->bindValue(2, $idUsuario);
$insereMsgEstado->bindValue(3, $uf);
$insereMsgEstado->bindValue(4, $msg);
$insereMsgEstado->bindValue(5, $foto);
$insereMsgEstado->bindValue(6, $dia);
$insereMsgEstado->bindValue(7, $hora);
$insereMsgEstado->execute();
//var_dump($idUsuario);
$idAvisoUf = $pdo->lastInsertId();

A: Para resolver o problema, você pode fazer o seguinte:
$insereMsgLogra->bindValue(2, (int) $idUsuario, PDO::PARAM_INT);

Isso fará um cast no seu parâmetro, forçando que seja sempre um valor inteiro.


text:
Q: Entering the same record twice, in Entity Framework I'm reviewing some EF code, and I'm wondering why it seems to be working.
The code is simple enough. We have a table that needs a query to determine the proper fields for its primary key. It's possible that between the time the query is run and the insert is committed that some other process has inserted a new record, so the insert fails with a primary key violation. (This would be better handled with an identity field in the primary key, but that's not a refactoring I can do, right now.) To deal with this, the original programmer used a loop:
MyRec myRec = new MyRec
{
    //.. set fields
};

bool isDone = false;
int retries = 0;
const int maxRetries = 8;
while (retries < maxRetries && !isDone)
{
    myRecseqno = getSeqno();

    try
    {
        myDbContext.myRecs.Add(myRec);
        myDbContext.SaveChanges();
        isDone = true;
    }
    catch
    {
        retries++;
    }
}

One thing I don't like is that it's catching every exception, instead of just a primary key violation. (Another thing I don't like is that there are four identical copies of this function in four different classes). But that's not my question. Assume I'll fix that.
What's bugging me is that myRec is being added to the collection multiple times, and I'd not expect that to work. A DbContext is a Unit of Work, which means that if the record was added to the collection on the first pass, it's still in the collection when it's added again, on the second loop.
Keep in mind, the primary key has changed, so I'd think that the collection would contain two records, after the second loop, the first with the original primary key and the second with the new.
Does EF use object identity to recognize when you're adding the same object to a collection, twice?

A: You may be advised to do the query and insert in a transaction, which would place a lock and prevent another process inserting. A stored procedure may give the best performance, or look at http://blogs.msdn.com/b/alexj/archive/2009/01/11/savechanges-false.aspx


text:
Q: How to calculate average value from gridded datasets in python Hello I have a gridded datasets in .nc format. I tried to read .nc file for different combination of latitude and longitude with the code given below, but i know this is not the ideal way to do that.
import netCDF4
from netCDF4 import Dataset
f= Dataset('data.nc')

data1 =  f.variables['asa'][:,3,23]
data2 =  f.variables['asa'][:,3,24]
data3 =  f.variables['asa'][:,3,25]
data4 =  f.variables['asa'][:,4,23]
data5 =  f.variables['asa'][:,4,24]
data6 =  f.variables['asa'][:,4,25]

and finally
data = np.vstack((data1,data2,data3,data4...))

Data = np.average(data, axis = 0)

Is there any simple ways to do that instead of reading every single grid and to calculate the average value??
yours help will be highly appreciated.

A: I don't know about nc formatting, but I would expect that you should be able to do
import netCDF4
from netCDF4 import Dataset

f= Dataset('data.nc')
Data = np.average(f.variables['asa'][:,3:5,23:26], axis = 0)


text:
Q: Button background color in ExtJS 6 does not change I know that there is many post on this subject, but even after looking at all and trying to use all the "cls" configs, the background color of my button does not change.
Here's my code:
var miscTools = Ext.create('Ext.panel.Panel', {
    title: 'Tools',
    id: 'toolsPanel',
    bodyPadding: 5,
    height: 200,
    border: false,
    collapsible: false,
    layout: 'anchor',
    defaults: {
        anchor: '100%'
    },
    items: [{
        xtype: 'button',
        id: 'colorToolButton',
        text: 'Auto color tool',
        cls: 'multiColor-btn',
        handler: colorWindow
    }]
})

CSS:
.multiColor-btn {
    background-color: yellow;
}

What am I doing wrong ?
ANSWERS
So the problem was from the gray theme of ExtJS. I needed to remove the background-image of the button in order to add a background color. Thanks to @Alexander for his answer.
Correct code:
.multiColor-btn {
    background-image: none !important;
    background-color: yellow !important;
}

Another option would have been to use a "afterRender" event to change the background color. However, it does just change the text background color. Thanks to @nenadg for this answer.
Ext.getCmp('colorToolButton').btnInnerEl.addCls('multiColor-btn')

A: Try this :
.multiColor-btn {
    background-color: yellow !important;
}

A: Instead of cls, try using userCls property for additional styles.
http://staging.sencha.com/extjs/6.0/6.0.1-modern/#!/api/Ext.Component-cfg-userCls


text:
Q: Kill process group not working I'm on Debian GNU/Linux.
The man page for "kill" says I can use negative PID value to kill process group, but when running on command line, it does not work:
$ /bin/kill -9 -21581
/bin/kill: invalid option -- '2'

Usage:
 kill [options] <pid> [...]
etc.

When using the bash built-in kill, it works fine.

A: Because its the first PID, you need to preceed it with "--" otherwise it'll be mistook for an option.
kill -9 -- -21581


text:
Q: Could not find profile: TwoOrgsChannel in Hyperledger Fabric I want to get genesis.block,but Could not find profile:  TwoOrgsOrdererGenesis.I can't get channel.tx as the same reason.
[myg@Ubuntu e2e_cli]$>../../build/bin/configtxgen -profile TwoOrgsOrdererGenesis -outputBlock ./channel-artifacts/genesis.block
2018-03-23 11:33:24.235 CST [common/tools/configtxgen] main -> INFO 001 Loading configuration
2018-03-23 11:33:24.335 CST [common/tools/configtxgen/localconfig] Load -> CRIT 002 Could not find profile:  TwoOrgsOrdererGenesis
2018-03-23 11:33:24.335 CST [common/tools/configtxgen] func1 -> CRIT 003 Could not find profile: TwoOrgsOrdererGenesis
panic: Could not find profile: TwoOrgsOrdererGenesis [recovered]
    panic: Could not find profile: TwoOrgsOrdererGenesis

goroutine 1 [running]:
github.com/hyperledger/fabric/vendor/github.com/op/go-logging.(*Logger).Panic(0xc42021a090, 0xc42026c770, 0x1, 0x1)
    /home/myg/gopath/src/github.com/hyperledger/fabric/vendor/github.com/op/go-logging/logger.go:188 +0xbd
main.main.func1()
    /home/myg/gopath/src/github.com/hyperledger/fabric/common/tools/configtxgen/main.go:242 +0x115
panic(0xc3db80, 0xc42026c760)
    /usr/local/go/src/runtime/panic.go:505 +0x229
github.com/hyperledger/fabric/vendor/github.com/op/go-logging.(*Logger).Panic(0xc4201b1ec0, 0xc420240560, 0x2, 0x2)
    /home/myg/gopath/src/github.com/hyperledger/fabric/vendor/github.com/op/go-logging/logger.go:188 +0xbd
github.com/hyperledger/fabric/common/tools/configtxgen/localconfig.Load(0x7ffee2bcf0c8, 0x15, 0x0)
    /home/myg/gopath/src/github.com/hyperledger/fabric/common/tools/configtxgen/localconfig/config.go:248 +0x7b4
main.main()
    /home/myg/gopath/src/github.com/hyperledger/fabric/common/tools/configtxgen/main.go:250 +0x4d2


text:
Q: Are all EJBs deployed as JAR? When looking at how Netbeans uses ant to build an Enterprise Application, packaged as an EAR file:
library-inclusion-in-manifest:
     [copy] Copying 1 file to /home/thufir/NetBeansProjects/netbeansEnterpriseApp/build/lib

-do-ear-dist:
    [mkdir] Created dir: /home/thufir/NetBeansProjects/netbeansEnterpriseApp/netbeansEnterpriseApp-ejb/dist
      [jar] Building jar: /home/thufir/NetBeansProjects/netbeansEnterpriseApp/netbeansEnterpriseApp-ejb/dist/netbeansEnterpriseApp-ejb.jar

-post-dist:

dist-ear:

pre-pre-compile:

pre-compile:

-do-compile-deps:
     [copy] Copying 1 file to /home/thufir/NetBeansProjects/netbeansEnterpriseApp/build

do-compile:
     [copy] Copying 1 file to /home/thufir/NetBeansProjects/netbeansEnterpriseApp/build/META-INF

post-compile:

compile:

pre-dist:

do-dist-without-manifest:

do-dist-with-manifest:
    [mkdir] Created dir: /home/thufir/NetBeansProjects/netbeansEnterpriseApp/dist
      [jar] Building jar: /home/thufir/NetBeansProjects/netbeansEnterpriseApp/dist/netbeansEnterpriseApp.ear

post-dist:

dist:

BUILD SUCCESSFUL
Total time: 1 second
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp$
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp$ tree
.
├── build
│   ├── lib
│   │   └── netbeansRemoteInterface.jar
│   ├── META-INF
│   │   └── MANIFEST.MF
│   └── netbeansEnterpriseApp-ejb.jar
├── build.xml
├── dist
│   └── netbeansEnterpriseApp.ear
├── nbproject
│   ├── ant-deploy.xml
│   ├── build-impl.xml
│   ├── genfiles.properties
│   ├── private
│   │   └── private.properties
│   ├── project.properties
│   └── project.xml
├── netbeansEnterpriseApp-ejb
│   ├── build
│   │   ├── classes
│   │   │   ├── ejb
│   │   │   │   └── NewSessionBean.class
│   │   │   ├── META-INF
│   │   │   │   └── MANIFEST.MF
│   │   │   └── netbeansRemoteInterface.jar
│   │   ├── empty
│   │   └── generated-sources
│   │       └── ap-source-output
│   ├── build.xml
│   ├── dist
│   │   └── netbeansEnterpriseApp-ejb.jar
│   ├── nbproject
│   │   ├── ant-deploy.xml
│   │   ├── build-impl.xml
│   │   ├── genfiles.properties
│   │   ├── private
│   │   │   └── private.properties
│   │   ├── project.properties
│   │   └── project.xml
│   └── src
│       ├── conf
│       │   └── MANIFEST.MF
│       └── java
│           └── ejb
│               └── NewSessionBean.java
└── src
    └── conf
        └── MANIFEST.MF

23 directories, 25 files
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp$
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp$ asadmin deploy dist/netbeansEnterpriseApp.ear
Application deployed with name netbeansEnterpriseApp.
Command deploy executed successfully.
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp$
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp$ asadmin list-applications
netbeansEnterpriseApp  <ear, ejb>
Command list-applications executed successfully.
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp$ cd dist/
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$ ls
netbeansEnterpriseApp.ear
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$ jar xf netbeansEnterpriseApp.ear
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$ ll
total 40
drwxr-xr-x 4 thufir thufir 4096 Nov 11 19:29 ./
drwxrwxr-x 7 thufir thufir 4096 Nov 11 19:28 ../
drwxr-xr-x 2 thufir thufir 4096 Nov 11 19:28 lib/
drwxr-xr-x 2 thufir thufir 4096 Nov 11 19:28 META-INF/
-rw-r--r-- 1 thufir thufir 2834 Nov 11 19:28 netbeansEnterpriseApp.ear
-rw-r--r-- 1 thufir thufir 1351 Nov 11 19:28 netbeansEnterpriseApp-ejb.jar
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$ ll lib/
total 20
drwxr-xr-x 2 thufir thufir 4096 Nov 11 19:28 ./
drwxr-xr-x 4 thufir thufir 4096 Nov 11 19:29 ../
-rw-r--r-- 1 thufir thufir  782 Nov 11 19:28 netbeansRemoteInterface.jar
thufir@dur:~/NetBeansProjects/netbeansEnterpriseApp/dist$

I notice that, when deployed to Glassfish, both EAR and EJB are listed.  On its own, an EJB is packaged as a JAR?  There's no such thing as an EJB packaged as an EAR?  (Rather, any EJB packaged in an EAR or WAR ultimately is deployed as a JAR -- to my understanding.)
Or, are there EJB which are not deployed as JAR files?

A: Yes, the EJBs in the WAR do not need to be packaged as Jar, if your applicationserver (as jboss7 and wildfly) supports this.
The ejb-classes can be found inside the WAR in WEB-INF/classes.
An example project used for tests you can find at ejb-cdi-unit-test-war. If you try and clone you will need maven to build the project.


text:
Q: Line integration in pauls notes calculus III
Why did he use $[0,2]$ as the limits of integration in the 3ed curve after substituting the value of $x = 1$ in $x$, shouldn't the limits be $[0,1]$ as in the $X$ axis,  so the last integration becomes $4$ ?
Please correct me if I am wrong .. Thanks


text:
Q: Installing Orchard 1.0 CMS I'v Installed Orchard 1.0 CMS , so I'v downloaded Orchard.Web.1.0.20.zip , then I copy all files from this folder and put them into my server by FTP, all files has been successfull sended.
When I go to my site I have Error, but I don't know how to solve them and why I have error?
I only copy files, IMHO it should be OK.
link to my page: http://konradkubacki.studentlive.pl/

A: Make sure your website is running in .NET 4 Integrated mode.
Try adding the
<customErrors mode="Off"/>

section to your system.web section in Web.config file to show more detailed information. Please post it here so I'd be able to provide more detailed solution.
Remember to turn showing the errors to the world off after that (mode="On"):)
[EDIT] The detailed error info you provided shows that there is a permission issue with accessing the Dependencies folder. Just grant the app user account (IUSR_machinename by default) permissions to access that folder - I answered a similar question on Orchard Codeplex site a while ago. But you have to have access to the server to do that.
You can also try creating that folder (App_Data/Dependencies) by hand after uploading Orchard, so appropriate permissions would be granted to the user under which your hosting account runs.
HTH


text:
Q: Azure New Portal web apps missing I have a number of web apps that I can see and on the old Azure management website, but these don't appear in the new portal, in Cloud Explorer in Visual Studio and the Azure App Service Support website.
Any help in getting this sorted out would be much appreciated.

A: just to validate, are you in the same subscription?
You can change your active subscription by clicking on the top-right corner.

If you are, please select the All resources option in the left pane menu.
If it's still not present can you tell us more about what is the "webApp" you don't see?


text:
Q: url links to SSRS reports I have a sql server which hosts three groups of reports. Rather than linking to the reports manager page which shows all three report groups I decided I would like to link directly to a report group.
Here's the URI which i'm passing (this is coming from a silverlight usercontrol with a button click event)
http://localhost/Reports/Pages/Folder.aspx?ItemPath=%2fConveyor+Reports&ViewMode=List
but instead it sends me to http://localhost/Reports/Pages/Folder.aspx
In that link ^ i'm trying to link into the "Conveyor Reports" group directly. But the end result is always redirecting me to Reports Manager homepage.

A: I modified my formatting to
http://localhost/Reports/Pages/Folder.aspx?ItemPath=/Conveyor%20Reports

and it worked.


text:
Q: Hibernate ignoring changes in schema.sql I'm developing an application with Spring Boot and hibernate, which connects to a postgres instance running in docker. When I first created my schema.sql, it looked like this:
CREATE TABLE groups(
    group_id varchar(255) PRIMARY KEY,
    group_desc varchar(255),
    group_name varchar(255)
);

The table created successfully, however I soon realized 255 is too short for my purposes and changed my schema to the following:
CREATE TABLE groups(
    group_id text PRIMARY KEY,
    group_desc text,
    group_name text
);

However, the database keeps reverting to the original data types. I've tried dropping the table, however when the Spring app runs and it gets created again as varchar(255) instead of text. How do I force hibernate to use the updated schema?
I've tried changing the spring.jpa.hibernate.ddl-auto property to create and update, and tried changing the fields to other datatypes, including other lengths of varchar. Nothing has worked so far. Even deleting schema.sql seemingly has no effect.
My application.properties looks like this:
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=<redacted>
spring.datasource.password=<redacted>
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

A: The Text datatype is not a Varchar but a CLOB.
Check your Groups class. I guess the name and desc attributes are String and the default related db type is then VARCHAR(255). Thus, if you generate your schema from your entity, String always become VARCHAR(255)
If you want to use Text, your field should be annotated with @Lob
public class Groups {
    @Lob
    @Column(name = "group_desc")
    private String desc

    @Lob
    @Column(name = "group_name")
    private String name
}

This being stated, I think you should change your java/db model because having a Lob/Text type as primary/foreign key frightens me a little (even if I never tried)
CREATE TABLE groups(
    group_id bigint PRIMARY KEY,
    group_code text NOT NULL UNIQUE,
    group_desc text,
    group_name text
);

public class Groups {
    @Id
    @Column(name = "group_id")
    private Long id;

    @Lob
    @Column(name = "group_code", nullable = false, unique = true)
    private String code;

    @Lob
    @Column(name = "group_desc")
    private String desc;

    @Lob
    @Column(name = "group_name")
    private String name;
}

NB : I usually don't generate the schema from entities so I instead use the code below to map a db text field to entity attribute :
    @Column(name = "group_desc", columnDefinition = "CLOB")
    private String desc;

But I am not sure if this is handled correctly to generate the schema


text:
Q: How to not include a certain column during query in SQL Server 2008 Thank you for the reply, but again im already using dynamic fields.
For example:
DECLARE @columns VARCHAR(8000)
SELECT @columns = COALESCE(@columns + ',[' + cast(QuestionName as varchar) + ']', '[' + cast(QuestionName as varchar)+ ']')
FROM Answer A
INNER JOIN Question Q ON A.QuestionID = Q.QuestionID
INNER JOIN Customer C ON A.CustomerID = C.CustomerID
GROUP BY Q.QuestionName

SET @columns = '[CustomerID],' + @columns

DECLARE @query VARCHAR(8000)
SET @query = 'Some PIVOT query without aggregation'

EXECUTE(@query)

But i want to arrange the fields in @columns..i want 1 field to be 1st:
@columns = [f1],[f2],[f3].

What i want is like this:
@columns = [f2],[f1],[f3] :

Because one of the fetch data..is constant in my report..
and should be place in the beginning or the first row to be displayed.


text:
Q: Issue filtering DT datatable with horizontal scroll in Rshiny In my Rshiny dashboard I want to display a wide table (>15 columns) in a DT DataTable having filters on top and horizontal scrolling on. When I now want to apply the filter all columns are suddenly visible in the area outside the width of the table.
Here's an example that shows the problem:
library(shiny)
library(DT)

runApp(shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("results", width = 300)
  ),
  server = function(input, output){
    output$results <- DT::renderDataTable(
      mtcars,
      filter = "top",
      options = list(scrollX = TRUE,
                     dom = 'Brtip')
    )
  }
))

Is this an unfixed problem in DT or is there a way how I could fix this in the given code example?


text:
Q: What does this Visual Studio (2013 professional) magnify glass icon mean?
In the bottom of my Visual Studio there is a little icon (see image)
It is a moving magnify glass (I think it's a magnify glass, I'm sure it's moving)
It's moving all the time (it's moving, in a circle shape, and the background 'block' shape is growing larger and smaller), but there is no hover text, nor can I click it...
I'm afraid of moving icons when I don't know what they do.....
Anyone know what it means/does?
EDIT:
when I click on F5, it's shown besides the VS build icon:

A: That's the predefined SBAI_Find icon in Visual Studio's Status Bar Animation Region. Any extension could be triggering it (or even Visual Studio itself). There's more information here: http://msdn.microsoft.com/es-es/library/microsoft.visualstudio.shell.interop.ivsstatusbar.animation(v=vs.100).aspx
There's no way to tell what is triggering it by your question only. To find the culprit, I'd try disabling all extensions and enabling them one-by-one.
Notice it shows when using the standard Find in Visual Studio (if you want a lengthy operation to check it, use Find In Files)

A: It simply means, it is trying to find and link all the files. You should not be too much bothered about it and it is not from any of the third party extension.

A: In Simple Words , It Is a Search Engine Build By VB.net To Find Content According To The User's Requirement Needed And The Section Selected
Note: Different Section Will Lead To Different Search Result


text:
Q: Ipod touch blink/flash white Hi my ipod touch (about 1.5 years old) recently started to blink/flash white when I use it. (Never completely white)
I tried restoring/updating the software, didn't work; tried pressing power+home button, also didn't work. Anything else I can try, or do I need to bring it in?

A: inverter for lcd-display is likely going (which is part of the logic-board).  Or the backlight (part of the lcd-assembly).  Bring it in.