text:
Q: lapply() showed two different results when using with leveneTest() I have this dataframe list containing different dataframes.
df_list <- list(
  `1.3.A` =
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L

    ),
  `2.2.A` =
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L,
       "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L
    ),
  `1.1.B` =
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L
    )
)

What I was trying to do was to test for homogeneity of variance among groups (Person in this case). But after several trials of piping lapply() with leveneTest() my codes showed two different results.
This particular code worked and gave me the result I was looking for.
ht <- function(df){
  leveneTest(df$Height ~ df$Person)
}

final_ht <- lapply(df_list, ht)

However, for this code
wood <- lapply(df_list, function(i) ~leveneTest(y = Height, group = Person, data = i))

would give a result showing <environment: 0x55869b4289b8>
I have no idea why the function in wood didn't return or run the leveneTest.
What is happening  with lapply() in both codes?
Can somebody enlighten me on what lapply() is doing on both cases?
Also, in the code ht it  returns a  warning, is this ok?
In leveneTest.default(y = y, group = group, ...) :
group coerced to factor. Error in cat("1: In leveneTest.default(y = y,
group = group, ...) : group coerced to factor.",  :
  argument 2 (type 'list') cannot be handled by 'cat'

Would very much appreciate any help.

A: Remove the tilde, as in
wood <- lapply(df_list, function(i) leveneTest(y = Height, group = Person, data = i))

If you were using purrr (or some other rlang-derived set of functions), then you might use it as something like:
purrr::map(df_list, ~ leveneTest(y = Height, group = Person, data = .x))
# or
purrr::map(df_list, ~ leveneTest(y = Height, group = Person, data = .))

In base R, the tilde returns a formula/expression that stores with it the environment of the calling expression, which is why you see <environment:...>. In base R, it is often used to define relationships between response and model variables, such as lm(mpg ~ disp + cyl, data=mtcars); it can also be used to define marginal variables, as in xtabs(~ cyl + vs, data = mtcars). In neither of those situations is the actual calling environment (stored with the ~) used, but it's still there.
In purrr, it can be used to more tersely define anonymous functions. The following are, for the most part, equivalent:
lapply(df_list, function(dat) leveneTest(y = Height, group = Person, data = dat))
purrr::map(df_list, function(dat) leveneTest(y = Height, group = Person, data = dat))
purrr::map(df_list, ~ leveneTest(y = Height, group = Person, data = .))
purrr::map(df_list, ~ leveneTest(y = Height, group = Person, data = .x))
# new to R-4.1
lapply(df_list, \(dat) leveneTest(y = Height, group = Person, data = dat))


text:
Q: change to colour of polygon plot and add legend Follow up question from Assign colours to values and plot horizontal bars in R
with all the data values, how can i change to following code such that the colour coded on hmin2 bar switches. the left side of the line should be blue and the right side should be red.
FullRange = range(dataframe123, na.rm=TRUE)

BoxRanges = lapply(dataframe123, range, na.rm=TRUE)

plot(NULL, xlim=FullRange, ylim=c(0,3),  yaxt="n", xlab="Value", ylab="")
abline(v=19.293)
axis(2, at=(0:2)+0.4, labels=c("hmin1", "hmin2","hmin3"),
lty=0, las=2)

for(i in 1:3) {
polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293),
    c(i-1,i-0.2,i-0.2,i-1), col="red")
polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]),
    c(i-1,i-0.2,i-0.2,i-1), col="blue")
}

In addition, how do i add a legend to the plot indicating the what the colours represent?
Red represents a negative change in parameters and the blue represents a positive change in parameters.

Been stuck for hours. Any help will be appreciated thank you.

A: One option could be add polygon for hmin2 outside the loop. In order to add the legend, you should increase the plot area (xlim and ylim), so the legend will be visible.
plot(NULL, xlim=c(FullRange[1]-1, FullRange[2] +1), ylim=c(-1,4),  yaxt="n", xlab="Value", ylab="")
abline(v=19.293)
axis(2, at=(0:2)+0.4, labels=c("hmin1", "hmin2","hmin3"),
     lty=0, las=2)

for(i in c(1,3)) {
  polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293),
          c(i-1,i-0.2,i-0.2,i-1), col="red")
  polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]),
          c(i-1,i-0.2,i-0.2,i-1), col="blue")
}
i = 2
polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293),
        c(i-1,i-0.2,i-0.2,i-1), col="blue")
polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]),
        c(i-1,i-0.2,i-0.2,i-1), col="red")

legend(x = 20, y = 4.5, legend = "negative changes",
     border = NULL, fill = "red",
     bty = "n",
     bg = "n")
legend(x = 20, y = 4, legend = "positive changes",
       border = NULL, fill = "blue",
       bty = "n",
       bg = "n")

Edit
If you want to add a title to your plot you must use main inside plot. To add a label to your line, you can use text:
plot(NULL, xlim=c(FullRange[1]-1, FullRange[2] +1), ylim=c(-1,4),  yaxt="n", xlab="Value", ylab="", main = "Range of H min values with parameter changes")
abline(v=19.293)
axis(2, at=(0:2)+0.4, labels=c("hmin1", "hmin2","hmin3"),
     lty=0, las=2)

for(i in c(1,3)) {
  polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293),
          c(i-1,i-0.2,i-0.2,i-1), col="red")
  polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]),
          c(i-1,i-0.2,i-0.2,i-1), col="blue")
}
i = 2
polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293),
        c(i-1,i-0.2,i-0.2,i-1), col="blue")
polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]),
        c(i-1,i-0.2,i-0.2,i-1), col="red")

legend(x = 20, y = 4.5, legend = "negative changes",
       border = NULL, fill = "red",
       bty = "n",
       bg = "n")
legend(x = 20, y = 4, legend = "positive changes",
       border = NULL, fill = "blue",
       bty = "n",
       bg = "n")
text(x = 17.5, y = -0.9, labels ="19.293", col = "black", cex = 0.9)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How is the Falcon 9 aerodynamically stable while ascending? How is the Falcon 9 aerodynamically stable while ascending? The rocket doesn't look like it should be able to fly straight. With the large, largely empty fairing at the top and the heavy engines at the bottom and no fins, it looks like it would want to flip around. Is it simply really well controlled by computers to not stray from the prograde vector, or are the engines really light, or what?

A: It isn't.
Stabilisation is achieved by gyros which command the rocket nozzles to swivel so a sideways component of thrust can be used to balance the rocket. This has been true since the days of the A-4, which used moveable graphite fins sticking into the rocket exhaust to stabilise the device.
Before, rockets used much larger fins and a long ramp for stabilisation, and the rocket had to gain enough speed for the fins to become effective. Only by adding artificial stabilisation did bigger rockets become possible.


text:
Q: Error when configuring firebase with environment variables I am trying to configure my Firebase project using environmental variables, and am having problems. I'm sure some of you guys/gals will be able to help me so I will get straight into the code
.firebase.js
import Rebase from 're-base';
import firebase from 'firebase';

const config = {
    apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGEBUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID
 };

const app = firebase.initializeApp(config);
const base = Rebase.createClass(app.database());
const facebookProvider = new firebase.auth.FacebookAuthProvider();

export { app,base,facebookProvider };

.server.js
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3001;
const app = express();
const router = require('./routes');
const mongoose = require('mongoose');

require('dotenv').config();

// Define middleware here
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

app.use(router);

mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/cryptoTracker")

app.listen(PORT, () => {
  console.log(` ==> Server now on port ${PORT}!`);
});

Error
@firebase/database: FIREBASE FATAL ERROR: Can't determine Firebase Database URL.  Be sure to include databaseURL option when calling firebase.initializeApp().
Furthermore
I am confused because I do have a databaseURL parameter and that environment variable IS defined in my .env file. I am not posting my .env file on here for obvious reasons but I assure you that all the variables I am calling are located inside of it.


text:
Q: using IOS camera, got  I'm using UIImagePickerController to let my user take a photo or choose a photo from the photoAblum.
Problem is that,
it seems OK to go to the photoAlbum,
but about 8 out of 10 times I go to the camera,
the gdb throws this warnig (or even an error?):
wait_fences: failed to receive reply: 10004003

here is my code to initialize a UIImagePickerController
- (IBAction)fromCameraButtonTapped {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:imagePicker animated:YES];
        return;
    }
}

the method that go the the photo ablum is almost the same as this one, except the sourceType.
What's more, it is also ok when I choose a photo back from the album,
but it often throws the same warning when I choose a new-token photo from the camera.
And once my app even crashed with a following memory warning after this strange warning.
So I thinks it is neccessary to get it over.
Anybody know what I should do?
THanks a lot!

A: I've solved this,
my app crashes because after a memory warning,
I set some of my very important properties in viewDidUnload, so after I touch some button or do some action, it crashes,
but I still got that strange warning.
Anyway My app works fine in the view.


text:
Q: Buying someone a Steam game without a Steam account I deleted my Steam account with with 1k games on it recently because I wanted to combat my video game addiction.
I want to gift a game (specifically Artifact) to a friend, he has a Steam account and I don't. Is there a way to buy him a key or something like that so I can send him the game without having Steam?

A: Instead of creating a temporary account or giving a gift card, you can use an authorized reseller site like the humblebundle.com or greenmangaming.com to purchase a Steam key that your friend can redeem. Often these kind of sites have the added benefit of allowing you or your friend to select either a Steam or GOG key (or just download a DRM-free installer directly for some games).
Note that in my experience, some people have trouble understanding how to redeem these keys, but if your friend is familiar with Steam or GOG, they should be able to figure it out. These sites do a pretty good job of explaining how to redeem keys.
("Artifact" is a Valve game and therefore will probably only ever be available on Steam, but for others looking for a way to do this with other games, I think this is the better option.)
IMPORTANT: Make sure that you only buy keys from a legitimate authorized reseller! There are illegitimate sites, such as G2A, that sell illegally (or questionably at best) acquired keys. These keys have a high chance of getting revoked, so it is very important to check to make sure the site's legitimate.

A: There are two ways that come to mind. 1 is to give him a gift card (as Frank mentioned in his comment), the other is to make a new account and gift it to him through it, and then delete that account (which is probably more complicated since I believe you will have to re-friend him through that new account)


text:
Q: Why do I get "Permission denied" when redirecting the output of sudo echo "xyz" to a file? Why do I get
-bash: test: Permission denied

when I run
sudo echo "xyz" > test

The directory permissions are:
drwxr-xr-x 3 root root 4096 2014-08-05 16:26

I have no problem creating a file in the directory using sudo.  But why can't I sudo echo into it?

A: This happens because you're only running the echo command as root. The output redirection is handled by your (non-root) shell. To avoid this, don't use the shell's redirect and use an actual command to handle the writing: tee. What you want to do can be done as so:
echo "xyz" | sudo tee test > /dev/null

(if you don't redirect the output, tee will output xyz to stdout, too)


text:
Q: SQL Concatenate and group I need a TSQL version of group_concat
Simmilar to the example found here:
Policy   Destination   ID
-------------------------
PolA     DestA         1
PolA     DestA         2
PolB     DestB         3
PolB     DestB         4
PolC     DestC         5
PolC     DestC         6
PolC     DestD         7

The output should look like this:
PolA   DestA   1,2
PolB   DestB   3,4
PolC   DestC   5,6
PolC   DestD   7

The grouping is on the uniqueness of both the first 2 columns, and then a concatenated output on the third.
I found this link but it only take into account 2 columns
Any help would be appreciated.

A: In MSSQL Synax:
SELECT Policy, Destination, STRING_AGG ( [ID], ',' ) IDs
FROM Table

A: You can try this :
SELECT G.Policy, G.Destination,
    stuff(
    (select cast(',' as varchar(max)) + U.ID
    from yourtable U
    WHERE U.Policy = G.Policy and U.Destination = G.Destination
    order by U.Policy
    for xml path('')
    ), 1, 1, '') AS IDs
FROM yourtable G group BY G.Policy, G.Destination

A: I just create the PolA example table for you, just replace the CTE as your table, try below:
WITH ABC
as
(
select   'PolA' as Policy,'DestA' as Destination,'1' as ID
UNION ALL
select 'PolA','DestA','2'
)

SELECT Policy, Destination,
 STUFF((SELECT ',' + A.ID FROM ABC as A WHERE A.Policy = B.Policy FOR XML PATH('')),1,1,'') as ID
FROM ABC as B
GROUP BY B.policy, B.Destination


text:
Q: not recieving Parse Push Notification I'm having a problem receiving Parse Push Notification using devices lower than android lollipop. Parse push notification works perfectly with devices with OS Lollipop but with versions lower than lollipop it does not work I hope some help me thanks in advance.
Manifest File
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:protectionLevel="signature"
    android:name="com.synborate.app.synborate.permission.C2D_MESSAGE" />
<uses-permission android:name="com.synborate.app.synborate.permission.C2D_MESSAGE" />

<application
    android:name=".SynborateApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="stateHidden|adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <activity
        android:name=".authentication.AuthenticatorActivity"
        android:label="@string/app_name" />

    <service android:name=".authentication.SynborateAuthenticatorService" >
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator" />
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/authenticator" />
    </service>

    <meta-data
        android:name="AA_DB_NAME"
        android:value="Synborate.db" />
    <meta-data
        android:name="AA_DB_VERSION"
        android:value="5" />

    <service android:name="com.parse.PushService" />

    <receiver android:name="com.parse.ParseBroadcastReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.USER_PRESENT" />
            <action android:name="act" />
        </intent-filter>
    </receiver>

    <receiver android:name="com.synborate.app.synborate.utils.CustomPushReciever"
        android:exported="false">
        <intent-filter>
            <action android:name="act" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.USER_PRESENT" />
            <action android:name="com.parse.push.intent.RECEIVE" />
            <action android:name="com.parse.push.intent.DELETE" />
            <action android:name="com.parse.push.intent.OPEN" />
        </intent-filter>
    </receiver>

    <receiver android:name="com.parse.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <!--
              IMPORTANT: Change "com.parse.starter" to match your app's package name.
            -->
            <action android:name="act" />
            <category android:name="com.synborate.app.synborate" />
        </intent-filter>
    </receiver>

</application>


text:
Q: Creating a new list from the means of a list of a function I've defined a function called CalcspeedAngle
def CalcspeedAngle(k):
    xpos = [1,2,3,4,5,6,7,8,9]
    ypos = [10,11,12,13,14,15,16,17,18]
    turnrates = [entry/3.099 for entry in xpos][::k]
    vts = [entry/3.099 for entry in ypos][::k]
    return(turnrates,vts)

then I write
turnrates, vts = CalcspeedAngle(k)

My question is: How can I create two new lists (m1list and m2list) that contain the averages of the turnrates and vts with k = 1,2,3,4,5,6,7,8,9,10,15,20? In other words, how can I create:
m1list = [mean(flattened(turnrates(k=1))), mean(flattened(turnrates(k=2))), ...]
m2list = [mean(flattened(vts(k=1))), mean(vts(turnrates(k=2))), ...]

Any help would be greatly appreciated.

A: One way to simplify your code is to perform one iteration over range(10), unpack your 2 lists of lists, calculate the mean for each, and append them to your result lists:
def lists_of_means():
    m1list = []
    m2list = []

    for i in range(10):
        turnrates, vts = CalcspeedAngle(i)
        m1list.append(np.mean(turnrates))
        m2list.append(np.mean(vts))

    return m1list, m2list


text:
Q: Propriedades estáticas e liberação de memória Estou com algumas dúvidas em relação a liberação dos recursos para casos onde meus modificadores são estáticos.
Meu projeto é de teste unitário e estou usando Selenium pela primeira vez.
public class LoginTest : Base
{
        [ClassInitialize]
        public static void Iniciar(TestContext context) { }

        [TestMethod]
        public void Logar()
        {
            var loginPage = new LoginPage(driverGC);
            loginPage.Navegar("http://localhost:3533/Authorize/LogOn").Logar("usuario@dominio.com.br", "123456");
            Assert.IsTrue(loginPage.VerificarMenuLateral());
        }

        ...
}

public abstract class Base
{
        protected static IWebDriver driverGC = new ChromeDriver(@"C:\chromedriver_win32");
}

A propriedade é estática para que todos os testes ocorram com referência ao que já se foi obtido e para não haver novas instâncias do navegador a cada método executado. É uma prática não recomendável?
Acontece que tenho várias classes para teste. Todas herdando de base. Li em vários lugares que objetos, métodos e classes estáticas não são liberadas da memória no processo normal do GC.
Isso quer dizer que para cada primeiro método de teste executado em cada classe, terei uma carga na memória da propriedade driverGC que nunca será liberada?
Ou, sendo a propriedade de uma classe que não é estática, ela será removida junto a liberação da classe?
Ou, ainda, esta propriedade virá para a próxima classe com os valores obtidos na execução da classe anterior?
Implementei dentro de cada classe de teste um método:
[ClassCleanup]
public static void Finalizar()
{
    driverGC.Close();
    driverGC.Dispose();
}

Isso acarretará em liberação de memória após execução?
Vomo faço pra acompanhar todos os objetos carregados em memória em tempo de execução e suas respectivas liberações? Tem como?

A: O objeto na variável estática não será liberado porque a memória é estática, não faria sentido liberar isso. Mas o objeto que for referenciado na variável estática pode ser liberado sim, desde que não existam outras referências para ele. Se tiver, não tem porque liberar também.
Então precisa se perguntar se o objeto deve continuar existindo ou não. Se não deve, basta anulá-lo (null) na variável estática.
Esse método Finalizar() parece uma bela gambiarra. Você pode garantir que em todas situações esse método será chamado? Ele é necessário?
O Close() provavelmente deveria estar dentro do Dispose(). Esse Dispose() é necessário? Ele faz o que? O que eu vi no código parece que não existe este método. Se existisse, provavelmente teria que ser chamado em algum lugar, mas não parece que tenha um lugar para fazer isso. E provavelmente deveria usar using.
O Iniciar() também não parece fazer algum sentido.
Membros estáticos não são herdados, então essa classe Base sequer parece fazer sentido.

Isso quer dizer que para cada primeiro método de teste executado em cada classe, terei uma carga na memória da propriedade driverGC que nunca será liberada?

Não só existirá um em toda aplicação. Se o seu valor não for explicitamente mudado só existirá um objeto referenciado por ele. Mesmo que mude para um novo objeto, o anterior será descartado tão logo seja possível se não tiver novas referências para ele. Nada precisa ser feito.

Ou, sendo a propriedade de uma classe que não é estática, ela será removida junto a liberação da classe?

O que importa é a propriedade ser estática. A única coisa que uma classe estática faz é não permitir que existam membros não estáticos, além de, claro não permitir herdar, o que não faria sentido.

Ou, ainda, esta propriedade virá para a próxima classe com os valores obtidos na execução da classe anterior?

Não entendi o que é isto, mas com toda explicação já dada acho que dá para concluir o que quer saber.

Isso acarretará em liberação de memória após execução?

Não, leia mais abaixo. E observe o que já escrevi em cima.

Ah, e como faço pra acompanhar todos os objetos carregados em memória em tempo de execução e suas respectivas liberações? Tem como?

Alguma coisa pode ser pelo próprio debugger do Visual Studio ou outro IDE. Outras só com um profiler.
Leituras complementares:

*

*Membros estáticos são coletados pelo GC quando não são mais necessários?

*Método Dispose()

*Devo sempre utilizar Dispose()?

*Quais tipos de recursos são liberados em uma declaração "using"?

*Quando é recomendável que uma classe implemente IDisposable?

*O que significa '~' na frente do construtor de uma classe C#

*Quando devo usar GC.SuppressFinalize()?


text:
Q: how to retrieve data from a form in the controller of an api rest in symfony I am registering a doctor in my api through my symfony controller. And for that I created a form for the doctor, and then I have to persist these data in my database. And that's where I can not get the data from the form, that's what I tried on my postman, but it returns me a 500 error saying:

Child \"username\" does not exist.

I'm trying to recover my form data through this query:

$user->setUsername($form['username']);

Controller
  /**
 * @Route("/api/inscription/medecin")
 * @Rest\View(statusCode=Response::HTTP_CREATED)
 * @Method("POST")
 */
   public function postDocAction(Request $request){

     $medecin = new Medecin();
    $user = new User();
    $user->setSalt('');
    $form = $this->createForm('Doctix\MedecinBundle\Form\MedecinType', $medecin);

    $form->submit($request->request->all()); // Validation des données

    if ($form->isValid()){
     $encoder = $this->get('security.password_encoder');
     $encoded = $encoder->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($encoded);
        $user->setUsername($form['username']);
        $user->setRoles(array('ROLE_MEDECIN'));

        $user->setNom($form['nom']);
        $user->setPrenom($form['prenom']);
        $user->setNumTel($form['numTel']);
        $user->setAdresse($form['adresse']);

        $medecin->setUser($user);
        $medecin->setSexe($form['sexe']);
        $medecin->setQuartier($form['quartier']);
        $medecin->setNumOrdre($form['numordre']);
        $medecin->setSpecialite($form['specialite']);
        $medecin->setClinique($form['clinique']);

        $em = $this->getDoctrine()->getManager();
        $em->persist($medecin);
        $em->flush();
  }
   }

Form
   class MedecinType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('user',UserType::class)
        ->add('sexe',  TextType::class)
        ->add('specialite',SpecialiteType::class)
        ->add('clinique',CliniqueType::class)
        ->add('quartier',  TextType::class)
        ->add('numordre',  TextType::class)
    ;
}

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Doctix\MedecinBundle\Entity\Medecin',
        'csrf_protection' => false
    ));
}
}

Test in Postman

A: After you do $form->handleRequest($request);,
$form->getData() holds the submitted values.
But, the original $medecin variable has also been updated. So non need to set all the fields again.
https://symfony.com/doc/current/forms.html#handling-form-submissions

A: short answer :
According to the json, user seems to be an object so to access username, you should probably write:

$form["user"]["username"];
  You should apply the same logic to all elements inside user.

complete answer :
There are multiple incoherences in your code. The advantage of passing the object into the createForm() method, is that the object will automaticaly be updated once the form is submited and valid. This avoid you to go throught all the setters later as you are doing now.
So if you want the user object to be correcly updated into the medecin's object, you should set the user before creating the form :
<?php
 /**
 * @Route("/api/inscription/medecin")
 * @Rest\View(statusCode=Response::HTTP_CREATED)
 * @Method("POST")
 */
 public function postDocAction(Request $request){

    $medecin = new Medecin();
    $user = new User();
    $user->setSalt('');
    $user->setRoles(['ROLE_MEDECIN']);
    $medecin->setUser($user);

    $form = $this->createForm('Doctix\MedecinBundle\Form\MedecinType', $medecin);
    $form->submit($request->request->all()); // Validation des données

    if ($form->isValid()) {
     $encoder = $this->get('security.password_encoder');
     $encoded = $encoder->encodePassword($user, $user->getPlainPassword());
     $user->setPassword($encoded);

     $em = $this->getDoctrine()->getManager();

     $em->persist($user); // Safety, as i don't know how you configured your entities
     $em->persist($medecin);
     $em->flush();
   }
 }


text:
Q: Small functions vs. keeping dependent functionality in same function I have a class that sets up an array of nodes and connects them to each other in a graph-like structure. Is it best to:

*

*Keep the functionality to initialize and connect the nodes in one function

*Have the initialization and connection functionality in two different functions (and have a dependent order on which the functions must be called -- though keep in mind these functions are private.)

Method 1:
(Bad in that one function is doing two things, BUT it keeps dependent functionality grouped together -- the nodes should never be connected without being initialized first.)
init() {
    setupNodes()
}

private func setupNodes() {
    // 1. Create array of nodes
    // 2. Go through array, connecting each node to its neighbors
    //    according to some predefined constants
}

Method 2:
(Better in the sense that it is self-documenting, BUT connectNodes() should never be called before setupNodes(), so anyone working with the class internals needs to know about this order.)
init() {
    setupNodes()
}

private func setupNodes() {
    createNodes()
    connectNodes()
}

private func createNodes() {
    // 1. Create array of nodes
}

private func connectNodes() {
    // 2. Go through array, connecting each node to its neighbors
    //    according to some predefined constants
}

Excited to hear any thoughts.

A: You may also find (depending on how complex each of these tasks are) that this is a good seam for splitting out another class.
(Not sure if Swift works this way but pseudo-code:)
class YourClass {
    init(generator: NodesGenerator) {
        self.nodes = connectNodes(generator.make())
    }
    private func connectNodes() {

    }
}

class NodesGenerator {
    public func make() {
        // Return some nodes from storage or make new ones
    }
}

This separates the responsibilities of creating and modifying nodes to separate classes:NodeGenerator only cares about creating/retrieving nodes, while YourClass only cares about connecting the nodes it is given.

A: The problem you're dealing with is called temporal coupling
You're right to be concerned about how understandable this code is:
private func setupNodes() {
    createNodes();
    connectNodes();
}

I can guess what's going on there but tell me if this makes what else is going on a little clearer:
private func setupNodes() {
    self.nodes = connectNodes( createNodes() );
}

This has the added benefit of being less coupled to modifying instance variables but to me being readable is number one.
This makes connectNodes()'s dependency on nodes explicit.

A: In addition to this being the exact purpose of private methods, Swift gives you the ability to use inner functions.
Inner methods are perfect for functions that have only a single call site, but feel like they don't justify being separate private functions.
For example, it's very common to have a public recursive "entry" function, which checks preconditions, sets up some parameters, and delegates to a private recursive function which does the work.
Here's an example of how that might look in this case:
init() {
    self.nodes = setupNodes()

    func setupNodes() {
        var nodes = createNodes()
        connect(Nodes: nodes)
    }

    private func createNodes() -> [Node]{
        // 1. Create array of nodes
    }

    func connect(Nodes: [Node]) {
        // 2. Go through array, connecting each node to its neighbors
        //    according to some predefined constants
    }
}

Pay attention to how I use return values and parameters to pass around data, rather than mutating a shared state. This makes the data flow much more obvious at first glance, without needing to jump into the implementation.

A: Separate functions, for two reasons:
1. Private functions are private for exactly this situation.
Your init function is public, and it's interface, behavior, and return value is what you need to worry about protecting and changing. The result that you expect out of that method is going to be the same no matter what implementation you use.
Since the rest of the functionality is hidden behind that private keyword, it can be implemented however you like... so you might as well make it nice and modular, even if one bit depends on the other being called first.
2. Connecting nodes to each other might not be a private function
What if at some point you want to add other nodes to the array? Do you destroy the setup that you have now, and re-initialize it completely? Or do you add nodes to the existing array and then run connectNodes again?
Possibly connectNodes can have a sane response if the array of nodes hasn't been created yet (throw an exception? return an empty set? you have to decide what makes sense for your situation).

A: Every function you declare carries with it the burden of adding documentation and making it generalized so that it is usable by other parts of the program. It also carries the burden of understanding how other functions in the file may be using it for someone reading the code.
If however it isn't used by other parts of your program, I wouldn't expose it as a separate function.
If your language supports it, you can still have one-function-does-one-thing by using nested functions
function setupNodes ()  {
  function createNodes ()  {...}
  function connectNodes ()  {...}
  createNodes()
  connectNodes()
}

The place of declaration matters very much, and in the above example it is clear without needing any further clues that the inner functions are meant to be used only within the body of the outer function.
Even if you are declaring them as private functions, I assume that they are still visible to the whole file. So you would need to declare them close to the declaration of the main function, and add some documentation which clarifies that they are to be used only by the outer function.
I don't think that you have to strictly do one or the other. The best thing to do varies on a case by case basis.
Breaking it up into multiple functions certainly adds an overhead of understanding why there are 3 functions and how they all work with each other, but if the logic is complex then this added overhead may be much less than the simplicity introduced by breaking up the complex logic into simpler parts.


text:
Q: ClassPathResource cannot access my spring properties file (using Spring web MVC) The actual location of the file is in "D:\eclipse\projects\issu\src\main\webapp\WEB-INF\spring\spring.properties"
I tried:
Resource resource = new ClassPathResource("/src/main/webapp/WEB-INF/spring/spring.properties");

Resource resource = new ClassPathResource("/WEB-INF/spring/spring.properties");

Resource resource = new ClassPathResource("classpath:/WEB-INF/spring/spring.properties");

I also have added "/src/main/webapp" folder to my build path.
ClassPathResource cannot find it. Any ideas? thanks! :)
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>ISSU</display-name>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

my spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.myapps.issu" />

    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <tx:annotation-driven />

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="/WEB-INF/spring/spring.properties" />
    </bean>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.databaseurl}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="${hibernate.config}" />
        <property name="packagesToScan" value="com.myapps.issu" />
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
    </bean>
    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions" value="/WEB-INF/tiles.xml" />
    </bean>

    <bean id="issuDao" class="com.myapps.issu.dao.IssuDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="issuService" class="com.myapps.issu.services.IssuServiceImpl">
        <property name="issuDao" ref="issuDao" />
    </bean>
</beans>

A: Have you tried this one
Resource resource = new ClassPathResource("src/main/webapp/WEB-INF/spring/spring.properties");

A: Added the build path up to /src/main/webapp (via project properties) and use this code: Resource resource = new ClassPathResource("/WEB-INF/spring/spring.properties");

A: Add src\main\webapp\ folder in your classpath(using project properties) and use this...
Resource resource = new ClassPathResource("WEB-INF/spring/spring.properties");
Remember not to use "/" at the start of path.


text:
Q: FancyBox PHP form submit issue Okay, so I've been having a problem for the past four days, and a couple hours ago, I think I may have solved part of it (fancybox example #5, on their site, seems to be something that I want), however, I cannot get any part of it to work.
    <?  if($_GET['page'] != "startTime"){ ?>

    <link rel="stylesheet" type="text/css" href="/./fancybox/jquery.fancybox-1.3.1.css" media="screen" />

<? } ?>
<? if($_GET['page'] == "ajax"){
var_dump($_POST); } ?>
<? if($_GET['page'] == "startTime"){?>

   <form id="startTimeForm" method=post>

Please, enter data

    Enter Year
    <input class="czas" id="sec" name="year" type="text" size="5" maxlength="5" value="00" />

<input class="czas" type="submit" name="newTime" value="Set Start Time" />

   </form>

I also had used a javascript function, below, and I'd eventually like that to work in the code above, but I cannot get the above to work properly. It just does nothing. Firebug also reports no errors.

So, any help would be appreciated. Please tell me what I'm doing wrong.

A: The demonstration here worked to solve the problem. It created another problem, but that is for another question. I believe that was your demo, JFK, so thank you.

A: $.ajax({
        type    : "POST",
        cache   : false,
        url     : "downTime.php?page=ajax",
        data    : $(this).serializeArray(),
        success : function(data) {

Instead of:
            $.fancybox(data);

Try
            $("#fancyboxdiv").fancybox(data);

        }
    });

Where fancyboxdiv is the name of your element that hosts the fancybox.
You will change the other functions to
$("#fancyboxdiv").fancybox().close()

etc..
Most JQuery UI components require a element to work off of as its parent and it will usually modify that element adding/removing elements to it and changing CSS to give appearance that is needed


text:
Q: Recursive breadth first traversal in Bash I'm trying to discover why my traversal isn't working.  I believe I've isolated the problem to the point in code where it says "directory contains" and then what was passed to the function.  The function gets passed an array containing all of the new file paths to echo but for some reason it is only receiving the first one.  Am I passing the array incorrectly or could it be something else?
#!/bin/bash

traverse(){
  directory=$1
  for x in ${directory[@]}; do
    echo "directory contains: " ${directory[@]}
    temp=(`ls $x`)
    new_temp=( )
    for y in ${temp[@]}; do
      echo $x/$y
      new_temp=(${new_temp[@]} $x/$y)
    done
  done

  ((depth--))

  if [ $depth -gt 0 ]; then
    traverse $new_temp
  fi
}

A: You cannot pass arrays as arguments. You can only pass strings. You'll have to expand
the array to a list of its contents first. I've taken the liberty of making depth
local to your function, rather than what I assume is a global variable.
traverse(){
  local depth=$1
  shift
  # Create a new array consisting of all the arguments.
  # Get into the habit of quoting anything that
  # might contain a space
  for x in "$@"; do
    echo "directory contains: $@"
    new_temp=()
    for y in "$x"/*; do
      echo "$x/$y"
      new_temp+=( "$x/$y" )
    done
  done

  (( depth-- ))
  if (( depth > 0 )); then
    traverse $depth "${new_temp[@]}"
  fi
}

$ dir=( a b c d )
$ init_depth=3
$ traverse $init_depth "${dir[@]}"


text:
Q: TWA - Struggling w/ Offline Screen implementation This is my first Android project using Java and XML. (Which has been a process)
I'm having problems extending my LauncherActivity to display an Offline-Screen
I have been following Offline-First Trusted Web Activities
When this didn't work I followed some other Stackoverflows Taking users to offline activity |  No internet Layout
I noticed the key elements for this to work.

*

*adding user network perms to Mani fest.

*calling the new offline activity extend the Launcher Activity | Java file.

*registering offline activity in the Mani fest.

*Error handling | Java file

*adding helpers ConnectivityManager / rendering Layout activity | Java file & XML
when I run the build - I still get the Dinosaur.
I used the code demo from - Chrome Dev as referenced above and followed up by using code from
Offline First Demo


text:
Q: Mapping use Automapper How to map List of anonymous to List of T using AutoMapper?
For example:
class Test{
  public string a1{get;set]}
  public string a2{get;set;}
}

//....Entity Framework 4.3.1
var t=from z in db select {z.a1,z.a2};

var tmp=AutoMapper.Mapper.DynamicMap<List<Test>>(t);

But tmp always is empty
How to fix it?

A: You will need to call t.ToList() to execute the query first
var tmp=AutoMapper.Mapper.DynamicMap<List<Test>>(t.ToList());

A: how about you change
var t=from z in db select new Test
                          {
                             a1 = z.a1,
                             a2 = z.a2
                           }

EDIT
to allow mapping to dynamic types , you can refer to existing post


text:
Q: Woocommerce attribute as symbol not text I don't seem to be able to find any information on whether this is possible. Instead of a piece of text as an attribute I would like to display a tick symbol.
i.e. My attribute is called Vegetarian the value is "yes". Instead of displaying the word "yes" I would like to display a tick symbol.
Does anyone know where I could make an edit to achieve this?

A: Ok, I've found the file that needs to be edited to achieve this. You need to make a copy and save it to your template in /single-product/product-attributes.php
After the foreach loop paste:
<?php global $product;
      $vegetarian = $product->get_attribute( 'vegetarian' ); ?>

<?php if($vegetarian){
            echo '
Vegetarian
';
      }?>

Then make sure that the Vegetarian attribute is not "Visible on the product page" by unchecking that box in the product options in admin. Now it will appear with a tick at the end of the attribute list.
i.e.
Attribute: attribute value
Attribute: attribute value
Vegetarian:


text:
Q: It is possible to define url for each Group - OpenAPI Java I have to open an endpoint for external use by a client, and I have to create documentation for it, but when creating the group in openApi, I can't find a way to restrict the client so that it doesn't see the internal endpoints.

The client should only see the "API" group, is there any way to do this? or is it not possible?


text:
Q: Why i am getting InnoDB deadlock error? "Deadlock found when trying to get lock" I have the InnoDB table in MySQL.
I got the error
"Deadlock found when trying to get lock; try restarting transaction"
The query is a simple DELETE query. There is no transaction.
The query is like
"DELETE FROM mylogs WHERE userid=178487 AND logdate<'2021-03-12 15:13:32'"
What can be the reason i got this error? Maybe there were some other SELECT or INSERT or DELETE queries parallel, but i do not know. No more errors.
What can be the reason of this error and how i can prevent?
There is the index structure .

There i the info about the last deadlock

There is the result of "show create table logs;"


text:
Q: Remote execution with on a Single node with Multiple GPU I am looking into documentation for running hydra on a single node remotely. I am looking for methods where I can run a code present in my local machine and to run it on a GCP instance.
Any pointers?

A: It sounds like you are looking for a Hydra Launcher that supports GCP.
For now, Hydra does not support this. We do have a Ray Launcher that launches to AWS and could be further extended to launching on GCP. Feel free to subscribe this issue.


text:
Q: Stuck, need help Program crashes whenever it tries to access the SharedPreferences Program runs until it tries to access the SharedPreferences in my updateUserSettings() method. I have spent the last 2 hours searching the internet with no explanations. Please help!
I have the line that messes everything up Commented at the bottom of my onCreate();
Here is FuelEconomyCalculatorActivity.java
    package com.example.fuelcalculator;

    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.TextView;
    import android.widget.Toast;

    public class FuelEconomyCalculatorActivity extends ActionBarActivity implements
            OnClickListener {

        private EditText fuelEditText;
        private EditText distanceEditText;
        private TextView mpgTextView;
        private TextView litresTextView;
        private Button calculateButton;
        private Button clearButton;
        private RadioButton gallonsRadio;
        private RadioButton litresRadio;
        private RadioButton milesRadio;
        private RadioButton kmRadio;
        private String mpg = " ";
        private String kp100 = " ";
        private boolean metricChecked;
        private boolean imperialChecked;
        private boolean usGallonChecked;
        private boolean ukGallonChecked;

        private static final int RESULT_SETTINGS = 1;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_fuel_economy_calculator);
            fuelEditText = (EditText) findViewById(R.id.fuelEditText);
            distanceEditText = (EditText) findViewById(R.id.distanceEditText);
            mpgTextView = (TextView) findViewById(R.id.mpgTextView);
            litresTextView = (TextView) findViewById(R.id.litresTextView);
            calculateButton = (Button) findViewById(R.id.calculateButton);
            clearButton = (Button) findViewById(R.id.clearButton);
            gallonsRadio = (RadioButton) findViewById(R.id.gallonsRadio);
            litresRadio = (RadioButton) findViewById(R.id.litresRadio);
            milesRadio = (RadioButton) findViewById(R.id.milesRadio);
            kmRadio = (RadioButton) findViewById(R.id.kmRadio);
            calculateButton.setOnClickListener(this);
            clearButton.setOnClickListener(this);

            if (savedInstanceState != null) {
                mpg = savedInstanceState.getString("mpg");
                kp100 = savedInstanceState.getString("kp100");
                initializeViews();
            }
        //  updateUserSettings();
        }

        protected void onSaveInstanceState(Bundle savedInstanceState) {
            super.onSaveInstanceState(savedInstanceState);
            savedInstanceState.putString("mpg", (String) mpgTextView.getText());
            savedInstanceState.putString("kp100", (String) litresTextView.getText());
            litresRadio.setChecked(true);
            kmRadio.setChecked(true);
        }

        private void initializeViews() {
            mpgTextView.setText(mpg);
            litresTextView.setText(kp100);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.fuel_economy_calculator, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            switch (item.getItemId()) {
            case R.id.action_settings: {
                Intent intent = new Intent(FuelEconomyCalculatorActivity.this,
                        FuelEconomySettingsActivity.class);
                startActivityForResult(intent, RESULT_SETTINGS);
                return true;
            }

            case R.id.action_about: {
                Intent intent = new Intent(getApplicationContext(),   FuelEconomyAboutPageActivity.class);
                startActivity(intent);
                return true;
            }

            default:
                return super.onOptionsItemSelected(item);
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            switch (requestCode) {
            case RESULT_SETTINGS:
                updateUserSettings();
                break;

            }

        }

        private void updateUserSettings() {
            SharedPreferences sharedPrefs = PreferenceManager
                    .getDefaultSharedPreferences(this);

            if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
            {
                metricChecked = true;
                imperialChecked = false;
            }
            else if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("imperial"))
            {
                imperialChecked = true;
                metricChecked = false;
            }
            if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("uk"))
            {
                ukGallonChecked = true;
                usGallonChecked = false;
            }
            else if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("us"))
            {
                usGallonChecked = true;
                ukGallonChecked = false;
            }

            if(metricChecked)
            {
                litresRadio.setChecked(true);
                kmRadio.setChecked(true);
            }
            else if(imperialChecked)
            {
                milesRadio.setChecked(true);
                gallonsRadio.setChecked(true);
            }
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.calculateButton) {
                float mpg = 0;
                float kmLitres = 0;
                // it doesn't matter which you use here, as long
                // as you use a fuel and a distance method
                if (ukGallonChecked && !usGallonChecked) {
                    if (getKM() > 0 && getLitres() > 0) {
                        mpg = getMiles() / getGallons();
                        kmLitres = getLitres() / (getKM() / 100);
                        mpgTextView.setText(String.format("%.2f", mpg));
                        litresTextView.setText(String.format("%.2f", kmLitres));
                    }
                } else if (usGallonChecked && !ukGallonChecked) {
                    if (getKM() > 0 && getLitres() > 0) {
                        mpg = getMiles() / getGallonsUS();
                        kmLitres = getLitresUS() / (getKM() / 100);
                        mpgTextView.setText(String.format("%.2f", mpg));
                        litresTextView.setText(String.format("%.2f", kmLitres));
                    }
                }
            } else if (v.getId() == R.id.clearButton) {
                resetValues();
            }

        }

        public float CheckValues(EditText input) {
            float value = 0;
            try {
                value = Float.parseFloat(input.getText().toString());
                if (value < 1) {
                    Toast toast = Toast.makeText(this,
                            "Please enter a number that is larger than 0",
                            Toast.LENGTH_SHORT);
                    toast.show();
                }
            } catch (Exception ex) {
                Toast toast = Toast.makeText(this, "Please enter a number",
                        Toast.LENGTH_SHORT);
                toast.show();
            }
            return value;
        }

        public void resetValues() {
            mpg = " ";
            kp100 = " ";
            fuelEditText.setText("");
            distanceEditText.setText("");
            mpgTextView.setText("");
            litresTextView.setText("");
        }

        public float getKM() {
            float distance = CheckValues(distanceEditText);
            if (milesRadio.isChecked()) {
                distance = (float) (distance * 1.60934);
            }
            return distance;
        }

        public float getMiles() {
            float distance = CheckValues(distanceEditText);
            if (kmRadio.isChecked()) {
                distance = (float) (distance * 0.62137);
            }
            return distance;
        }

        public float getLitres() {
            float fuel = CheckValues(fuelEditText);
            if (gallonsRadio.isChecked()) {
                fuel = (float) (fuel * 4.54609);
            }
            return fuel;
        }

        public float getLitresUS() {
            float fuel = CheckValues(fuelEditText);
            if (gallonsRadio.isChecked()) {
                fuel = (float) (fuel * 3.785411784);
            }
            return fuel;
        }

        public float getGallons() {
            float fuel = CheckValues(fuelEditText);
            if (litresRadio.isChecked()) {
                fuel = (float) (fuel * 0.219969);
            }
            return fuel;
        }

        public float getGallonsUS() {
            float fuel = CheckValues(fuelEditText);
            if (litresRadio.isChecked()) {
                fuel = (float) (fuel * 0.264172);
            }
            return fuel;
        }
    }

And here is my FuelEconomySettingsActivity.java
package com.example.fuelcalculator;

import android.app.Activity;
import android.os.Bundle;

public class FuelEconomySettingsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getFragmentManager().beginTransaction().replace(android.R.id.content,
                new FuelEconomySettingsFragment()).commit();

    }

}

Here is my LogCat
07-18 14:35:37.014: E/AndroidRuntime(3084): FATAL EXCEPTION: main
07-18 14:35:37.014: E/AndroidRuntime(3084): Process: com.example.fuelcalculator, PID: 3084
07-18 14:35:37.014: E/AndroidRuntime(3084): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fuelcalculator/com.example.fuelcalculator.FuelEconomyCalculatorActivity}: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.access$900(ActivityThread.java:161)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.os.Looper.loop(Looper.java:157)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.main(ActivityThread.java:5356)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at java.lang.reflect.Method.invokeNative(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at java.lang.reflect.Method.invoke(Method.java:515)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at dalvik.system.NativeStart.main(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): Caused by: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.example.fuelcalculator.FuelEconomyCalculatorActivity.updateUserSettings(FuelEconomyCalculatorActivity.java:128)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.example.fuelcalculator.FuelEconomyCalculatorActivity.onCreate(FuelEconomyCalculatorActivity.java:63)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.Activity.performCreate(Activity.java:5426)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
07-18 14:35:37.014: E/AndroidRuntime(3084):     ... 11 more

I am new to Android so I am not very good at debugging so could someone please assist me with my predicament?
The activity is already included in my Manifest so I know that is not the issue.
Any help is much obliged.

A: You are getting a NullPointerException because you are getting null as the default value for SharedPreference.getString()
Since it is getString() get an empty string as the default value...
So try this..
if(sharedPrefs.getString("measuringUnits", "").equalsIgnoreCase("metric"))

instead of
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))


text:
Q: Request for Input for PHP Script in Linux I'm currently running a DNS server with a MySQL Backend, and I'm creating scripts to insert data into the MySQL tables.
My question is: Is it possible to have the script run, then request input in the shell to then be put into the script to then be run in a query against the MySQL Server?
For example I have a query to be ran:
INSERT INTO table (domain, type, ttl) VALUES ('$domain', 'TXT', 120);

I want to change the $domain variable on each run of the script and do not want to keep editing the script file.
Thanks for any responses


text:
Q: How to get the auto-generated primary key after insertion in stored procedure? My SQL Server table:
[dbo].[Rep] (
[rep_ID]        INT          IDENTITY (300, 1) NOT NULL,
[Restaurant_ID] INT          NULL,
[Fname]         VARCHAR (50) NOT NULL,
[Lname]         VARCHAR (50) NOT NULL,
CONSTRAINT [PK_Rep_ID] PRIMARY KEY CLUSTERED ([rep_ID] ASC),
CONSTRAINT [FK_Restaurant_ID] FOREIGN KEY ([Restaurant_ID]) REFERENCES [dbo].[Restaurants] ([ID])

);
I want to create a stored procedure that return the auto generated key for the inserted record.
My current stored procedure:
CREATE PROCEDURE [dbo].[createRepAcc]
    @first varchar(50),
    @last varchar(50)
AS
    INSERT INTO Rep([Fname], [Lname])
    OUTPUT inserted.rep_ID
    VALUES (@first, @last);

It's able to insert into the table but only return 1 instead of the primary key generated.
What am I doing wrong?

A: You can use scope_identity() to get the last generated id. For your case here is a detailed worksheet
/* creating a simple table with identity column */
CREATE TABLE dbo.a(identity_column INT IDENTITY(300,1), x CHAR(1));

/* Procedure that inserts values and returns generated output*/
CREATE PROCEDURE [dbo].[ap]
    @x char(1),
    @id int output
AS
    INSERT INTO a(x) VALUES (@x);
    select @id = SCOPE_IDENTITY();

/* This is how the procedure could be called */
declare @ident int -- declare a variable to receive output
execute dbo.ap @x='b', @id=@ident output -- execute or call the procedure
select @ident -- select or print the genereated id


text:
Q: Split the Paragraph using "." in node I wanted to split the paragraph in node using full stop but again there are some exceptions that I need to check before splitting it. For Ex I wanted to split the following paragraph using "." but it should not affect the statements which contain website name or email Id or statements that are in parenthesis ().
 My Country is best country in the world.My country name is India. This country belongs to several states.each state has different users which are using website named www.google.com or www.facebook.com. My state named Maharashtra uses email Id starting with dummy@gmail.com.

Can anybody please help me on that ?

A: Try this RegExp
var newContent = content.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|");


text:
Q: Getting pop-up error "Netscape.cfg/AutoConfig failed" when trying to drive firefox via selenium Grid using Watir-Webdriver Get Error:
Netscape.cfg/AutoConfig failed. Please contact your system administrator.
 Error:  defaultPref failed: [Exception... "Component returned failure code:  0x8000ffff (NS_ERROR_UNEXPECTED) [nsIPrefBranch.setBoolPref]"  nsresult:  "0x8000ffff (NS_ERROR_UNEXPECTED)"  location: "JS frame :: prefcalls.js  ::  defaultPref :: line 58"  data: no]

Netscape.cfg/AutoConfig failed. Error:  defaultPref failed: [Exception... "Component returned failure code:  0x8000ffff (NS_ERROR_UNEXPECTED)

I have the following setup:
Selenium Grid on CentOs 6.4
Slave Node = CentOs 6.4
Trying to run Firefox remotely via Watir-WebDriver
require "rubygems"
require "test/unit"
#require "selenium"
require "watir-webdriver"

caps = Selenium::WebDriver::Remote::Capabilities.firefox
#caps.version = "24"
caps[:name] = "Firefox 24  , port 5555"

default_profile = Selenium::WebDriver::Firefox::Profile.from_name "default"
default_profile.native_events = true
driver = Selenium::WebDriver.for(:firefox, :profile => default_profile)

    @browser = Watir::Browser.new(
    :remote,
    :url => "http://vm-auto.his.vm:4444/wd/hub",
    :desired_capabilities => caps)

    @browser.goto "google.com"
    @browser.text_field(:name => "q").set "3M"
    @browser.button.click
    @browser.div(:id => "resultStats").wait_until_present
    @browser.screenshot.save ("GoogleSearch_FF24.png")
    @browser.close

Firefox version is Mozilla Firefox 24.7.0
there is a reference to this error in https://bugzilla.mozilla.org/show_bug.cgi?id=717438
the resolution being suggested as:
In my case commenting out this pref in mozilla.cfg stops generating this message.
But I do not know origin of this pref.

//stops the request to send performance data from displaying
//pref("toolkit.telemetry.prompted", true);

But, i could not find mozilla.cfg on the filesystem where firefox is installed

A: That error definitely seems to be related to a problem in the mozilla config file BUT in my case the file was not mozilla.cfg but mozilla-lock.cfg (located at C:\Program Files (x86)\Mozilla Firefox\).
The filename is dictated by the lockset.js file at C:\Program Files (x86)\Mozilla Firefox\defaults\pref\.  The line is pref("general.config.filename", "mozilla-lock.cfg")
My issue with the config file was the following lines:
lockpref("security.tls.version.min", "1");
lockpref("security.tls.version.max", "3");

The values should be without quotes:
lockpref("security.tls.version.min", 1);
lockpref("security.tls.version.max", 3);

As addendum, it's entirely possible you don't have a config file at all and the problem exists with a manual configuration in the about:config. Open up the about:config page, and sort by 'status' to look for 'locked', 'user set' or any other non 'default' items.

A: I had the same issue with Firefox 24 ESR. Mozilla.cfg was in the same directory as the Firefox executable.
In my case this was under "%localappdata%\Microsoft\AppV\Client\Integration[Unique-Code]\Root".
I commented out 'pref("toolkit.telemetry.prompted", true);' and the error message didn't appear anymore.


text:
Q: Kali Linux bluetooth bluez shows only device's MAC address but not name? I am using Kali Linux 2020.2, bluez installed for Bluetooth. When I search devices I only see the MAC address, but not the name of the devices. I found this GitHub issue, but it was closed without a solution:
https://github.com/blueman-project/blueman/issues/944

Here is the image
Does anyone know how to fix this?

A: You could try this:
https://superuser.com/questions/778660/changing-bluetooth-device-name
I've not tested it myself. Please, let us know if it worked for you.


text:
Q: how to switch java version on Mac OS 10.8.4 I need to switch the Java version on my Mac OS X 10.8.4 but am not sure how, the version I have right now is 1.6.0_51 but i want to switch to 1.6.0_45:

$java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-11M4509)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode)

/usr/libexec/java_home -v 1.6.0_43
Unable to find any JVMs matching version "1.6.0_43".
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

I assume there is no such a version as 1.6.0_43 on my mac? how can install it and then switch to it? thanks!

A: As the description says on this website: "...it's really a pain to switch between this Java version by shell..." so this person made a tool to do the switching. Since I don't know your reasoning (if you really have to do it via the command line) it may not be overly useful but a quick google search revealed this downloadable tool from their website.

A: To see which versions you have installed use:
/usr/libexec/java_home -V

For example shows this for me:
15:04 $ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    10.0.1, x86_64: "Java SE 10.0.1"    /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
    1.7.0_80, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home

Then simply in your ~/.bashrc or ~/.bash_profile:
$ export JAVA_HOME=$(/usr/libexec/java_home -v 1.7.0_80)

As for getting version 1.6 (or nearly any prev version) I think that as of this date (Nov 2018) you will be out of luck.  I can get to https://jdk.java.net/8/ but any earlier version is a 404 (11 is the latest).  I'm sure you could search a bit more though as I understand it, once they (Oracle) have discontinued a version, they no longer maintain it since it could be a security risk.
Once you have DL a Mac .dmg, I'm sure it installs in the correct location and will be visible with java_home.
There is information at https://stackoverflow.com/a/47699905/1019307 that discusses using homebrew to install Java and it mentions Java6 (the post is dated Dec 2017).

A: *

*Install an other Java version, that you need.

*I had to switch between 1.6_XX and 1.7_XX so wrote a litte script for that. It does its job pretty good. You have to replace some stuff but maybe it helps you:
#!/bin/bash
#v1.0.3
#by Sapphire

# /!\ Configuration /!\
# vim ~/.bash_profile :
# alias changej="sudo ~/Documents/changeJavaVers.sh"
# sudo visudo -f /etc/sudoers :
# #Custom privilege
# user ALL=NOPASSWD: /Users/username/Documents/changeJavaVers.sh
# change java dir's at (1) and (2)

echo -e "\n***********************************************************"
echo "*                EASY JAVA VERSION CHANGER                *"
echo "***********************************************************"

echo "Enter java version (6, 7, ..) or 'set' for settings"
echo -n "Version: "
read vers
if [ "$vers" == "set" ]
then
    echo "settings not implemented yet"
    #TODO open settings
    #set java home path, add java versions
    #current home: echo $JAVA_HOME
elif (($vers == 6))
then
    #(1)
    ln -fhsv /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/ /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
    export JAVA_HOME=`/usr/libexec/java_home -v 1.6+ -d32`
    echo -e "\n-----------------------------------------------------------"
    echo "                       JAVA VERSION"
    echo "-----------------------------------------------------------"
    java -version
    echo -e "\n-----------------------------------------------------------"
    echo "                        JAVA HOME"
    echo "-----------------------------------------------------------"
    echo $JAVA_HOME
    echo "***********************************************************"
elif (($vers == 7))
then
    #(2)
    ln -fhsv /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/ /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
    export JAVA_HOME=`/usr/libexec/java_home`
    echo -e "\n-----------------------------------------------------------"
    echo "                       JAVA VERSION"
    echo "-----------------------------------------------------------"
    java -version
    echo -e "\n-----------------------------------------------------------"
    echo "                        JAVA HOME"
    echo "-----------------------------------------------------------"
    echo $JAVA_HOME
    echo -e "\n***********************************************************"

else
    echo -e "\ninvalid input - available java versions: 6, 7"
fi

EDIT
Got a newer version here. Works for me on OSX 10.9.3
#!/bin/bash
#v1.1.0
#last change: 12 June 2014
#by Sapphire

# /!\ Configuration /!\
# vim ~/.bash_profile :
# alias changej="sudo ~/Documents/changeJavaVers.sh"
# sudo visudo -f /etc/sudoers :
# #Custom privilege
# user ALL=NOPASSWD: /Users/username/Documents/changeJavaVers.sh
# change java directories (1), (2)

echo -e "\n***********************************************************"
echo "*                EASY JAVA VERSION CHANGER          v1.1.0 *"
echo "***********************************************************"

echo "Enter java version (6, 721, 745, 760) or 'set' for settings"
echo -n "Version: "
read vers
if [ "$vers" == "set" ]
then
    echo "settings not implemented yet"
    #TODO open settings
    #set java home path, add java versions
    #current home: echo $JAVA_HOME
elif (($vers == 6))
then
    #(1)
    ln -fhsv /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/ /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
elif (($vers == 721))
then
    #(1)
    ln -fhsv /Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/ /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
elif (($vers == 745))
then
    #(1)
    ln -fhsv /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/ /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
elif (($vers == 760))
then
    #(1)
    ln -fhsv /Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/ /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
else
    echo -e "\ninvalid input - available java versions: (6, 721, 745, 760)"
    exit
fi
#(2)
export JAVA_HOME='/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home'
echo -e "\n-----------------------------------------------------------"
echo "                       JAVA VERSION"
echo "-----------------------------------------------------------"
java -version
echo -e "\n-----------------------------------------------------------"
echo "                        JAVA HOME"
echo "-----------------------------------------------------------"
echo $JAVA_HOME
echo -e "\n***********************************************************"
exit

A: There is no need to download a whole new version. What you really want is this:
-target version
Generate class files that target a specified version of the VM. Class files will run on the specified target and on later versions, but not on earlier versions of the VM. Valid targets are 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), and 1.7 (also 7).
The default for -target depends on the value of -source:

If -source is not specified, the value of -target is 1.7
If -source is 1.2, the value of -target is 1.4
If -source is 1.3, the value of -target is 1.4
If -source is 1.5, the value of -target is 1.7
If -source is 1.6, the value of -target is 1.7
For all other values of -source, the value of -target is the value of -source.

from this source. -target and -source allow to control the target JVM and source code level. As the source says the value of target will default to the value you give source but you can control both if you want.
If this option can't provide a specific enough version for you, though I can't imagine why you would need such an exact version, then you'll just have to bite the bullet and download the right version yourself


text:
Q: Boost preprocessor library I'm having some trouble expanding to the base value
# include <boost/preprocessor/cat.hpp>

#define REL_ITERATION_1 1
#define REL_FRAME_ITERATION(i) BOOST_PP_CAT(REL_ITERATION_, i)
#define REL_ITERATION_PARAMS_2 REL_FRAME_ITERATION(1)
#define REL_FRAME1(i)           BOOST_PP_CAT(REL_ITERATION_PARAMS_, i)
#define REL_FRAME2(i)           REL_ITERATION_PARAMS_##i
REL_FRAME1(2)
REL_FRAME2(2)

Here's the output.
BOOST_PP_CAT(REL_ITERATION_, 1)
1

Does anyone have any idea why the first call is not the same as the second? I thought I had a handle on using the preprocessor, but I just don't get this. :(

A: Never mind.  I missed the part in the documentation where it says if it expands to a BOOST_PP_CAT() macro, it won't expand it.
Doh!


text:
Q: How to render my external html file inside the div element in MVC? I have tried @Html.Raw(Model) but it renders only the plain html. The css styles are not embedded in view.
How to render a Html file inside the div with the css styles?
Thanks in advance!

A: Try something like that, but not sure whether it's included the css.
@Html.Raw(File.ReadAllText(Server.MapPath("~/Index.html")))

Suggest you to create the partial view and call it in your view page.
@Html.Partial("~/Views/Shared/_Index")


text:
Q: Mathematica's GatherBy function using Pandas groupby I'm designing a function similar to the GatherBy in Mathematica. I thought it could be easily done by dressing up groupby function in Pandas. This function will group the list by certain given characteristic function.
Setup
time1 = pd.date_range(start=datetime.datetime(2015, 1, 30), end=datetime.datetime(2015, 2, 5))
datedat = np.array([time1, 0.1 * numpy.arange(7), 0.2 * numpy.arange(7)]).T

print(datedat)
array([[Timestamp('2015-01-30 00:00:00', freq='D'), 0.0, 0.0],
   [Timestamp('2015-01-31 00:00:00', freq='D'), 0.1, 0.2],
   [Timestamp('2015-02-01 00:00:00', freq='D'), 0.2, 0.4],
   [Timestamp('2015-02-02 00:00:00', freq='D'), 0.3,
    0.6],
   [Timestamp('2015-02-03 00:00:00', freq='D'), 0.4, 0.8],
   [Timestamp('2015-02-04 00:00:00', freq='D'), 0.5, 1.0],
   [Timestamp('2015-02-05 00:00:00', freq='D'), 0.6,
    1.2]], dtype=object)

Suppose I want to group it by year and month —— you see there are data for January and February. So I design a characteristic function:
gatherf = lambda x: ((x[0].year)*1000+x[0].month)

For every time-data records, this gatherf would calculate a value for groupby to distinguish time.
Objective
my final object is to develop a function gather_by, by which
gather_by(datedat, gatherf)

Should generate this:
array([[[Timestamp('2015-01-30 00:00:00', freq='D'), 0.0, 0.0],
   [Timestamp('2015-01-31 00:00:00', freq='D'), 0.1, 0.2]],

   [[Timestamp('2015-02-01 00:00:00', freq='D'), 0.2, 0.4],
   [Timestamp('2015-02-02 00:00:00', freq='D'), 0.3,
    0.6],
   [Timestamp('2015-02-03 00:00:00', freq='D'), 0.4, 0.8],
   [Timestamp('2015-02-04 00:00:00', freq='D'), 0.5, 1.0],
   [Timestamp('2015-02-05 00:00:00', freq='D'), 0.6,
    1.2]]], dtype=object)

My Effort
In general cases, the datedat might have more column than 3. I couldn't group them one by one. So I tried:
datedatF2 =pandas.DataFrame({'dat':datedat,'gather_key':numpy.array(list(map(gatherf, datedat)))})

with
groupedall=datedatF2['dat'].groupby(datedatF2['gather_key'])

but this leads to Data must be 1-dimensional error. what should I do?

A: Inputs -
datedat
array([[Timestamp('2015-01-30 00:00:00', freq='D'), 0.0, 0.0],
       [Timestamp('2015-01-31 00:00:00', freq='D'), 0.1, 0.2],
       [Timestamp('2015-02-01 00:00:00', freq='D'), 0.2, 0.4],
       [Timestamp('2015-02-02 00:00:00', freq='D'), 0.3, 0.6],
       [Timestamp('2015-02-03 00:00:00', freq='D'), 0.4, 0.8],
       [Timestamp('2015-02-04 00:00:00', freq='D'), 0.5, 1.0],
       [Timestamp('2015-02-05 00:00:00', freq='D'), 0.6, 1.2]], dtype=object)

gatherf
lambda x: ((x[0].year) * 1000 + x [0].month)

One very reliable method of grouping building on your current approach, would be passing a custom list/key to groupby (the grouping predicate need not belong to the dataframe!) -
key = list(map(gatherf, datedat))

r = []
for _, g in pd.DataFrame(datedat).groupby(key):
    r.append(g.values.tolist())

Alternatively, as a list comprehension -
r = [g.values.tolist() for _, g in pd.DataFrame(datedat).groupby(key)]

np.array(r)

[[[Timestamp('2015-01-30 00:00:00', freq='D'), 0.0, 0.0],
  [Timestamp('2015-01-31 00:00:00', freq='D'), 0.1, 0.2]],
 [[Timestamp('2015-02-01 00:00:00', freq='D'), 0.2, 0.4],
  [Timestamp('2015-02-02 00:00:00', freq='D'), 0.3, 0.6],
  [Timestamp('2015-02-03 00:00:00', freq='D'), 0.4, 0.8],
  [Timestamp('2015-02-04 00:00:00', freq='D'), 0.5, 1.0],
  [Timestamp('2015-02-05 00:00:00', freq='D'), 0.6, 1.2]]]

This should also work for any number of columns, provided gatherf is appropriately written to match.

A: I think you can use groupby by mapped function gatherf:
datedatF2 = pd.DataFrame(datedat)

gatherf = lambda x: x[0].year*1000 + x[0].month

out = [x.values.tolist() for i, x in datedatF2.groupby(list(map(gatherf, datedat)))]
print (out)

[[[Timestamp('2015-01-30 00:00:00', freq='D'), 0.0, 0.0],
  [Timestamp('2015-01-31 00:00:00', freq='D'), 0.1, 0.2]],

[[Timestamp('2015-02-01 00:00:00', freq='D'), 0.2, 0.4],
  [Timestamp('2015-02-02 00:00:00', freq='D'), 0.3, 0.6],
  [Timestamp('2015-02-03 00:00:00', freq='D'), 0.4, 0.8],
  [Timestamp('2015-02-04 00:00:00', freq='D'), 0.5, 1.0],
  [Timestamp('2015-02-05 00:00:00', freq='D'), 0.6, 1.2]]]

First solution with Series:
datedatF2 = pd.DataFrame(datedat)
dates = pd.to_datetime(datedatF2.iloc[:, 0])

s = dates.dt.year*1000 + dates.dt.month
print (s)
0    2015001
1    2015001
2    2015002
3    2015002
4    2015002
5    2015002
6    2015002
Name: dat0, dtype: int64

out = [x.values.tolist() for i, x in datedatF2.groupby(s)]

EDIT:
Second approach si faster:
N = 100000
df = pd.DataFrame({1:pd.date_range('2015-01-01', periods=N, freq='15H'),
                   2:np.random.randint(100, size=N),
                   3:np.random.randint(100, size=N)})
datedat = df.values

In [75]: %%timeit
    ...: datedatF2 = pd.DataFrame(datedat)
    ...: dates = pd.to_datetime(datedatF2.iloc[:, 0])
    ...: s = dates.dt.year*1000 + dates.dt.month
    ...: out = [x.values.tolist() for i, x in datedatF2.groupby(s)]
    ...:
1 loop, best of 3: 249 ms per loop

In [76]: %%timeit
    ...: datedatF2 = pd.DataFrame(datedat)
    ...: gatherf = lambda x: x[0].year*1000 + x[0].month
    ...: out = [x.values.tolist() for i, x in datedatF2.groupby(list(map(gatherf, datedat)))]
    ...:
1 loop, best of 3: 359 ms per loop

Caveat:
Performance depend on the data - size of DataFrame and number of values groups. But generally second solution is faster as first.


text:
Q: GridFS does not play well with AfNetworking or remote downloading of images I have an app that used GridFS to store the images of a document (references). I am trying to use AfNetworking to download the images when a UITableViewCell is shown. However AFNetworking does not have a method that deals with image data that is stored in binary form i.e. it asks for a physical URL on the server. Please see (https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking) under image downloads. I trealy need to use AFNetworking methods for caching etc.
Any tips?

A: GridFS is a filesystem. If you want to serve images over HTTP, which is something AFNetworking can handle, you'll need to set that up to a web server.
Apache and Nginx appear to both have modules to server GridFS, so that'd be a good place to start.


text:
Q: What happens when you dynamic_cast between derived classes with the same base class? I am trying to figure out what happens when you dynamic_cast from one derived class to another derived class. Why does the below code raise a segmentation fault? Note that I am not trying to use this code for anything. I merely want to understand what is happening.
It's also worth noting that the same code works using static_cast. I can't seem to find any documentation that goes into the finer details of what is happening here. Can somebody explain?
struct base
{
    virtual void printing(){cout<<"base printing"<<endl;};
};
struct derived_1 :public base
{
    virtual void printing(){cout<<"derived_1 printing"<<endl;};
};
struct derived_2 :public base
{
    virtual void printing(){cout<<"derived_2 printing"<<endl;};
};

int main()
{
    base * b = new derived_2();
    derived_1 *d_1 = dynamic_cast<derived_1*>(b);

    // calling printing raises segmentation fault
    d_1->printing();
}

A: The cast to derived_1 will fail, because derived_2 is a base object but not a derived_1 object. Therefore, you cannot "side cast" to the desired pointer type.
Not that whenever dynamic_cast fails, it will return a nullptr (except for reference types). This eventually leads to the segmentation fault in your code (in general, I would suggest you always add a if (d_1 != nullptr) before using a dynamically casted object).
Update:
By the way, this is actually a good example for the necessity of dynamic_cast. Even though you could be tempted to use static_cast in your example and it would compile, you will be dealing with undefined behavior. Using static_cast will compile without hickups, but you would actually be working with a broken type. Assume derived_1::printing() accesses some variable derived_1::a, which does not exist in derived_2. By statically side-casting a derived_2 object (which doesn't have a) to a derived_1 object d_1, you would falsely assume d_1 to contain some valid a, which is not the case.
Example:
// ...
struct derived_1 :public base
{
    const int a = 123;
    void printing() override {cout<<"derived_1 printing " << endl;}
    void foo() { cout << "Foo using constant = " << a << endl; }
};

// ...
int main()
{
    base * b = new derived_2();
    derived_1 *d_1 = static_cast<derived_1*>(b);
    d_1->printing(); // Will call derived_2::printing(), which is not what you expect!
    d_1->foo();      // Won't show a = 123 but some nonesense (mostly 0),
                     // because a is not defined in derived_2.
}


text:
Q: How can I make Outlook 2007 auto BCC messages to a specific email with specific words in subject using VBA?
Possible Duplicate:
Outlook VBA to BCC emails sent not working in Outlook 2007

So far I have this code from outlookcode.com which I can get to work sending all emails I send to the BCC email. I am not a developer, so I don't have a lot of context to go about editing this myself, or even approaching researching this. If anyone knows how to make this check for words in the subject, or check if the subject equals a certain string, I'd really appreciate it.
Private Sub Application_ItemSend(ByVal Item As Object, _
                                 Cancel As Boolean)
    Dim objRecip As Recipient
    Dim strMsg As String
    Dim res As Integer
    Dim strBcc As String
    On Error Resume Next

    ' #### USER OPTIONS ####
    ' address for Bcc -- must be SMTP address or resolvable
    ' to a name in the address book
    strBcc = "someone@somewhere.dom"

    Set objRecip = Item.Recipients.Add(strBcc)
    objRecip.Type = olBCC
    If Not objRecip.Resolve Then
        strMsg = "Could not resolve the Bcc recipient. " & _
                 "Do you want still to send the message?"
        res = MsgBox(strMsg, vbYesNo + vbDefaultButton1, _
                "Could Not Resolve Bcc Recipient")
        If res = vbNo Then
            Cancel = True
        End If
    End If

    Set objRecip = Nothing
End Sub

A: If you don't want to get involved with VB, you could do this with the rules wizard as follows:

*

*Create one rule and make it your last rule. This rule should be applied when your name is in the To or Cc fields. And it should stop processing subsequent rules:
 Step 1: Select conditions: Where my name is in the To or Cc box.
 Step 2: Select actions: Stop processing more rules.

*Create another rule and add it to the bottom of rule create at step 1 above. Make it as follows:
 Step 1: Select conditions: Where my name is not in the To box.
 Step 2: do whatever you want with you BCC message here.

So, the thing with the procedure above is that if you reached the rule created on step 2 is because you received a message where your name is not in the To or Cc fields, i.e. you are in the Bcc field.
You just need those two rules because there is no such condition as "Where my name is NOT in the To or Cc box". But we can manage to do the same with the above workaround.


text:
Q: Spring Security OAuth2 Could not obtain access token I have a spring security oauth client which is authenticating against a custom auth0 provider.
For getting the UserAuthorizationUri, i need to make a post request to a rest endpoint which is a wrapper on top of auth0.
So i have extended OAuth2ClientContextFilter and used a custom redirect strategy.Now the application is redirecting to the auth provider and after login ,access token is failing with CSRF error
  2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request '/login' matched by universal pattern '/**'
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login?code=F9WkgL_98BFFZkef&state=27ef0714353cf5d119ab088609e3a701950302ae8238c3210f0909590ffaa38b37c087274a73ebc24ae2cbb7de055ce94ebffdff5f7a00a74c80fdd0a9c046ee63596996b408b444151839c8d01eef820ecd77fc9316525b22ed4e7a078e008e44297604bb90be6d3e809b90659b1a384706f712243c9a7d8538817851d0ea2c2a5ba65c580e4b844e14af773498adbae6cf6b882fa2d487d43621a146e78a0b670030e1632295f132b36b4e6259080a478ba789aa4bb2902e7c6d25178e8964184250 at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login?code=F9WkgL_98BFFZkef&state=27ef0714353cf5d119ab088609e3a701950302ae8238c3210f0909590ffaa38b37c087274a73ebc24ae2cbb7de055ce94ebffdff5f7a00a74c80fdd0a9c046ee63596996b408b444151839c8d01eef820ecd77fc9316525b22ed4e7a078e008e44297604bb90be6d3e809b90659b1a384706f712243c9a7d8538817851d0ea2c2a5ba65c580e4b844e14af773498adbae6cf6b882fa2d487d43621a146e78a0b670030e1632295f132b36b4e6259080a478ba789aa4bb2902e7c6d25178e8964184250 at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@58543bda. A new one will be created.
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login?code=F9WkgL_98BFFZkef&state=27ef0714353cf5d119ab088609e3a701950302ae8238c3210f0909590ffaa38b37c087274a73ebc24ae2cbb7de055ce94ebffdff5f7a00a74c80fdd0a9c046ee63596996b408b444151839c8d01eef820ecd77fc9316525b22ed4e7a078e008e44297604bb90be6d3e809b90659b1a384706f712243c9a7d8538817851d0ea2c2a5ba65c580e4b844e14af773498adbae6cf6b882fa2d487d43621a146e78a0b670030e1632295f132b36b4e6259080a478ba789aa4bb2902e7c6d25178e8964184250 at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@af35197
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login?code=F9WkgL_98BFFZkef&state=27ef0714353cf5d119ab088609e3a701950302ae8238c3210f0909590ffaa38b37c087274a73ebc24ae2cbb7de055ce94ebffdff5f7a00a74c80fdd0a9c046ee63596996b408b444151839c8d01eef820ecd77fc9316525b22ed4e7a078e008e44297604bb90be6d3e809b90659b1a384706f712243c9a7d8538817851d0ea2c2a5ba65c580e4b844e14af773498adbae6cf6b882fa2d487d43621a146e78a0b670030e1632295f132b36b4e6259080a478ba789aa4bb2902e7c6d25178e8964184250 at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login?code=F9WkgL_98BFFZkef&state=27ef0714353cf5d119ab088609e3a701950302ae8238c3210f0909590ffaa38b37c087274a73ebc24ae2cbb7de055ce94ebffdff5f7a00a74c80fdd0a9c046ee63596996b408b444151839c8d01eef820ecd77fc9316525b22ed4e7a078e008e44297604bb90be6d3e809b90659b1a384706f712243c9a7d8538817851d0ea2c2a5ba65c580e4b844e14af773498adbae6cf6b882fa2d487d43621a146e78a0b670030e1632295f132b36b4e6259080a478ba789aa4bb2902e7c6d25178e8964184250 at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /login' doesn't match 'POST /logout
2018-01-18 12:01:21.465 DEBUG 28785 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login?code=F9WkgL_98BFFZkef&state=27ef0714353cf5d119ab088609e3a701950302ae8238c3210f0909590ffaa38b37c087274a73ebc24ae2cbb7de055ce94ebffdff5f7a00a74c80fdd0a9c046ee63596996b408b444151839c8d01eef820ecd77fc9316525b22ed4e7a078e008e44297604bb90be6d3e809b90659b1a384706f712243c9a7d8538817851d0ea2c2a5ba65c580e4b844e14af773498adbae6cf6b882fa2d487d43621a146e78a0b670030e1632295f132b36b4e6259080a478ba789aa4bb2902e7c6d25178e8964184250 at position 6 of 12 in additional filter chain; firing Filter: 'OAuth2ClientAuthenticationProcessingFilter'
2018-01-18 12:01:21.466 DEBUG 28785 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/login'
2018-01-18 12:01:21.466 DEBUG 28785 --- [nio-8080-exec-3] uth2ClientAuthenticationProcessingFilter : Request is to process authentication
2018-01-18 12:01:21.467 DEBUG 28785 --- [nio-8080-exec-3] uth2ClientAuthenticationProcessingFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Could not obtain access token

        Caused by: org.springframework.security.oauth2.common.exceptions.InvalidRequestException: Possible CSRF detected - state parameter was required but no state could be found
            at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.getParametersForTokenRequest(AuthorizationCodeAccessTokenProvider.java:255) ~[spring-security-oauth2-2.0.14.RELEASE.jar:na]
            at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:209) ~[spring-security-oauth2-2.0.14.RELEASE.jar:na]

App config
security:
  oauth2:
    client:
      clientId: xxx
      clientSecret: xxxx
      userAuthorizationUri: https://x.amazonaws.com/v1/login
      accessTokenUri: https://x.amazonaws.com/v1/getToken
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
      additional-information:
        env: test
    resource:
      userInfoUri: https://x.amazonaws.com/v1/userInfo?env=test

Application.java
@SpringBootApplication
@EnableOAuth2Sso
public class NauthtestApplication extends SpringBootServletInitializer {

    @Bean
    public NAuth2ClientContextFilter oauth2ClientContextFilter() {
        NAuth2ClientContextFilter filter = new NAuth2ClientContextFilter();
        return filter;
    }

    public static void main(String[] args) {
        SpringApplication.run(NauthtestApplication.class, args);
    }
}

Custom Filter
public class NAuth2ClientContextFilter extends OAuth2ClientContextFilter implements Filter, InitializingBean {

Custom Redirect Strategy
public class NAuthRedirectStrategy  implements RedirectStrategy {

    private String clientId="xxx";

    @Override
    public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {

        System.out.println("Reached the custom redirect strategy");

        NAuthLoginRequest loginRequest = new NAuthLoginRequest();
        loginRequest.setClientId(clientId);
        loginRequest.setEnv("test");
        loginRequest.setClaims(Arrays.asList("user","groups"));
        loginRequest.setCallbackUrl("http://localhost:8080/login");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
        ObjectMapper mapper = new ObjectMapper();
        HttpEntity<String> loginRestRequest = new HttpEntity<String>(mapper.writeValueAsString(loginRequest), headers);

        ResponseEntity<String> loginResponse = restTemplate.exchange(url, HttpMethod.POST,loginRestRequest, String.class);
        System.out.println("Login Response redirect url is " + loginResponse.getBody());
        String redirectUrl = loginResponse.getBody().substring(1,loginResponse.getBody().length()-1);;
        response.sendRedirect(redirectUrl);

    }


text:
Q: How can I add a variable to this bash command? ssh $server_gd_bare -t "cd  ~/public_html; git pull -q ~/root.git master"

I want to add these two varialbes to the command line above but ..
working_repo = ~/public_html

root_repo = ~/root.git master

Note that I am sshing into my remote server.
Thanks

A: Just define the variables and use them in the substitution for the respective parts of the code as below:
server_gd_bare="some-server"
working_repo="~/public_html"
root_repo="~/root.git master"

ssh $server_gd_bare -t "cd  $working_repo; git pull -q $root_repo"