text:
Q: What is the best file format to upload to MongoDB I am totally unfamiliar with MongoDB so pardon if my question is too simple.
I have 4 datasets and each dataset has files corresponding to samples, each sample has 3 files corresponding to three normalization method. The total number of samples in all 4 datasets is 20000 so the total files is 60000 (because of 3 normalization methods). Each file has about 2-5 columns and 60000 rows. I want to create a database which sort of has the following columns:
Dataset, Sample, Type, Normalization, ID, Value

Example: For a dataset Pnoc, I have a sample C021_0001_20140916 which is Tumor type and it has files corresponding to three normalization methods Kallisto, RSEM_Genes and RSEM_Isoforms. All of this info in encoded in the filename. The ID and value will be taken from target_id and tpm from within the file contents:
target_id   length  eff_length  est_counts  tpm
ENST00000619216.1   68  22.4958 3.07692 1.17482
ENST00000473358.1   712 527.104 0   0
ENST00000469289.1   535 350.229 0   0
ENST00000607096.1   138 16.1984 0   0
ENST00000417324.1   1187    1002.07 0.071357    0.000611642
ENST00000461467.1   590 405.167 0   0
ENST00000335137.3   918 733.078 0   0
ENST00000466430.5   2748    2563.07 233.847 0.783663
ENST00000495576.1   1319    1134.07 0   0

I am writing a script in python to go recursively through each file, create a JSON object which I will then upload to MongoDB in the script itself. The JSON object I am thinking looks something like this:
# 20000 Sample names, 3 Normalization methods and 60000 IDs in each file.
DatasetName1 {
    SampleName1 {
        Type {
            Normalization1 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            },
            Normalization2 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            },
            Normalization3 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            }
        }
    },
    SampleName2 {
        Type {
            Normalization1 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            },
            Normalization2 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            },
            Normalization3 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            }
        }
    },
    ...
    SampleName20000{
        Type {
            Normalization1 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            },
            Normalization2 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            },
            Normalization3 {
                { ID1: value, Expression: value },
                { ID2: value, Expression: value },
                ...
                { ID60000: value, Expression: value }
            }
        }
    }
}

However before I start writing the script to process so many files and convert to JSON, I wanted to know what really is the best format to upload to MongoDB - JSON/plaintext/csv or any other format?
Please let me know if I can provide any other information about my code.
Thanks!

A: For your requirement i'll do it in below way.
Create a CSV with below columns. Parse your files and dump data into the CSV. In any programming language CSV creation is very easy.
dt_set, sample, type, norm, id, value

After that import your CSV into MongoDB using MongoImport. This schema is easier one for your requirement. It is easier for aggregation, filtering etc. I feel your nested structure example is complex to do such things.


text:
Q: Calibrating a Cox PH model with R packages 'survival' and 'rms': time unit confusion I built a Cox Proportional Hazards model with the R package "rms" and am trying to cross-validate it. Splitting the data into training and test sets is what I'd like to do, but I'm new to survival analysis and can't find anything in the literature except rms::calibrate. I can't get it to work.
Here is the code:
# using the package 'survival', I make a survival object with
# follow-up time (2000 to 2020) and status (event=1, survival/censoring 0)
surv2 <- Surv(grid3@data$def_mean, grid3@data$status)
d <- datadist(grid3@data) # stores distribution summaries for potential variables??
options(datadist = "d") # seems to help cph() refer to variables
model <- cph(surv2 ~ cost_mean + elev_mean + popn_mean + cop99 + PAs_mean,
                 data = grid3@data, x = TRUE, y = TRUE, surv = TRUE, time.inc=1)
modrms <- rms::calibrate(model, B = 40, u = 1)

'time.inc' is time increments (1yr) - looking at model$surv.summary, I can see survival and 'no. at risk' figures for each of the 20 years. So that makes sense. But calling rms::calibrate the first message I get is Using Cox survival estimates at  1 Days...and looking at the calibration I get:
> summary(attr(modrms,"predicted"))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
      1       1       1       1       1       1

...so it looks like the model has been calibrated over a period of 1 day? And of course everyone survived (1=100%) ...the same thing happens using rms::calibrate(model, B = 40, u = 20).
I tried again starting with:
units(grid3@data$def_mean) <- "year"
surv3 <- Surv(grid3@data$def_mean, grid3@data$status)

...but that gives me an error!
Error in Ops.units(time, origin) :
  both operands of the expression should be "units" objects

I don't know what to try next. Wouldn't it be great if I could just build a model with the data from 2000-10, use that to make predictions for 2010-20, and look at predicted vs actual? But I'm stuck with calibration, and the documentation assumes more statistical expertise than mine (college stats plus efforts to improve my math).
Here is the data structure (not sure how I can make this reproducible):
> str(grid3@data)
'data.frame':   36918 obs. of  7 variables:
 $ def_mean  : num  20 20 20 20 20 20 20 20 20 20 ...
 $ status    : num  0 0 0 0 0 0 0 0 0 0 ...
 $ elev_mean : num  -0.664 -0.664 -0.664 -0.664 -0.664 ...
 $ popn_mean : num  -0.1658 0.0664 -0.1484 0.0601 -0.0381 ...
 $ cost_mean : num  1.53 1.48 1.43 1.66 1.6 ...
 $ PAs_mean  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ cop99     : Factor w/ 12 levels "10","20","30",..: 5 5 5 5 5 5 5 5 5 5 ...

> summary(grid3@data$def_mean)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   3.20   20.00   20.00   19.59   20.00   20.00

> table(grid3@data$status)

    0     1
34696  2222

A: The rms package can have a steep learning curve in some respects. You've already picked up on one thing that is sometimes missed: the importance of using datadist() to summarize the predictors, and then setting the datadist option (with the character name of the datadist object) so that summary functions have reasonable default choices for display.
With respect to the second error, I wonder if you maybe didn't re-run the datadist() command and reset the datadist option after you changed the time unit. The units() and label() functions in the rms-associated Hmisc package can be very useful, but if you don't re-run and reset datadist() after using them I suspect that things get confusing for the software downstream. If you specify a unit in one place, it will probably expect the same unit in another place.
Those commands don't do any transformations, however. The default assumption is that the time unit is "day," so that's what gets printed by default in the outputs. If you change the "units" to  "year," printouts will show "year" instead of "day" but the underlying calculations won't change.
So although calibrate() first claimed to be calculating at "1 Days" it wasn't really; that was just its default unit for printing. It still did the calibration at time = 1. Calibration at such an early time is probably not what you want.
I vaguely remember having some problems if the time.inc setting in the original cph() call didn't match the u setting in the calibrate() call. My usual practice is to know the time point at which I want to calibrate (e.g., 3-year survival for some types of cancer data) and use that for both those settings. Play a bit with a toy data set to see how to make that work for you.
Finally, calibrate() is best used with plot() to display the calibration curves (ideal, modeled, optimism-corrected by bootstrap). There might be a glitch if you try to print() the calibrate object. The values displayed on the standard plot are correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a spinner for each image loading in Ionic I am trying to load a list of images with spinner shown as each image is loaded.
This is what I have but don't see how to add a spinner as each image is loaded instead of seeing a blank screen as they load

            {{i.title }}

            {{i.location}}

A: You can easily do this with the || operator inside of an ng-src tag:
Controller:
$scope.loading = "<some-pic.gif>";

View:

*

*Change the src tag to ng-src, it is more Angular friendly

*Define a loading image/gif (previous uploaded) and store it in $scope variable

*Use || operator, if first option is undefined then the second (the gif) will be displayed

Fiddle: http://jsfiddle.net/xf3ezakc/

Also, you could use an $ionicLoading inside the controller to display a loading alert until all the images have loaded, I answered another question on how to do that here.
$scope.show = function() {
    $ionicLoading.show({
        template: 'Loading...'
    }).then(function(){
        console.log("The loading indicator is now displayed");
    });
};
$scope.hide = function(){
    $ionicLoading.hide().then(function(){
        console.log("The loading indicator is now hidden");
    });
};

// Assuming you have `$scope.data`, which it seems so
$scope.data = {};
$scope.show();
someDataCall().then(function(data) {
    // success
    $scope.hide();
}).catch(error) {
    // error
    $scope.hide();
});

I see that you also have a firebase reference in your code and if you are using $firebaseArray or $firebaseObject you could use $ionicLoading in combination with $loaded to detect the when the images have loaded (included in AngularFire API):
$scope.data.$loaded().then(function(data) {
    // success
    $scope.hide();
}).catch(function(error) {
    // error
    $scope.hide()
});

For the last 2, make sure to have injected $ionicLoading
References:
ng-src
$ionicLoading
AngularFire
ion-spinner (I have never used it)


text:
Q: String parsing functions in NSIS Is there any string parsing functions in NSIS other than StrCpy and StrLen?
Or a plugin that has methods like strstr, strcmp, find, contains etc.

A: StrFunc, included in the default install, contains several functions:
${StrCase}
${StrClb}
${StrIOToNSIS}
${StrLoc}
${StrNSISToIO}
${StrRep}
${StrStr}
${StrStrAdv}
${StrTok}
${StrTrimNewLines}
${StrSort}


text:
Q: Capturar todas as Sextas e Domingos e Quartas entre duas datas Estou tentando capturar todas as sextas-feiras, domingos e quartas feiras entre duas datas, usando o Moment.js. Eu não consegui entender porque não captura os dias:
-08/12/2021
-10/12/2021
já que cai na condição.
Eu estou tentando obter o seguinte:
2021-12-01 10:00:00
2021-12-01 16:00:00
2021-12-01 22:30:00
2021-12-03 10:00:00
2021-12-03 16:00:00
2021-12-03 22:30:00
2021-12-05 10:00:00
2021-12-05 16:00:00
2021-12-05 22:30:00
2021-12-08 10:00:00
2021-12-08 16:00:00
2021-12-08 22:30:00
2021-12-10 10:00:00
2021-12-10 16:00:00
2021-12-10 22:30:00

Segue a função:

const allDays = [5, 0, 3];

function formatToPush(dt_inicio, dt_final, dia, horas) {

let start = moment(dt_inicio);
let end = moment(dt_final);

let result = [];
let datas = [];
let current = start.clone();

if ((current.day(dia).isSameOrAfter(start)) || (current.day(dia).isSameOrAfter(end)) || (current.day(7 + dia).isSameOrBefore(end))) {
    result.push(current.clone());
}

result.map(m => {
    horas.map(h => {
        m.set({ hour: h.split(':')[0], minute: h.split(':')[1], second: 0, millisecond: 0 });
        datas.push(m.format('YYYY-MM-DD HH:mm:ss [GMT]ZZ'))
    })
});

return datas;
}

let final = [];

for(let i in allDays){
  final.push(...formatToPush('2021-12-01', '2021-12-10', allDays[i], ["10:00", "16:00", "22:30"]))
}

console.log(final)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

A: No seu código você fez um if em vez de um loop, então ele não necessariamente vai gerar tudo, caso as datas se espalhem por mais de uma semana.
Enfim, a ideia básica é primeiro verificar se a data inicial é um dos dias da semana que você quer. Se não for, primeiro você ajusta ela para a mais próxima. Por exemplo, no seu caso você quer domingo, quarta e sexta. Então se a data inicial for segunda ou terça, ajusta para a próxima quarta. Se for quinta, ajusta para a próxima sexta. Se for sábado, ajusta para o próximo domingo, e qualquer outro dia não precisa de ajuste.
Depois, precisamos saber qual desses dias da semana é o inicial, para saber quantos dias somar até o próximo. Do domingo para a quarta, são 3 dias, nos demais casos são 2 dias (inclusive de sexta para domingo).
Por fim, tendo isso, basta fazer um loop pelas datas, pulando a quantidade necessária até o próximo dia da semana, e para cada uma dessas datas, faço outro loop pelos horários. Ficaria assim:

// ajusta a data para o próximo dia da semana que está no array daysOfWeek
// retorna a data ajustada e o índice que corresponde ao dia da semana no array
function ajustaProximoDoW(data, daysOfWeek) {
    // verifica se o dia da semana está no array
    let index = daysOfWeek.findIndex(dow => data.day() === dow);
    if (index >= 0) { // se está, já retorna
        return [ data, index ];
    }
    // se não está, fazer o ajuste para o mais próximo
    let next = -1;
    for (let i = 0; i < daysOfWeek.length; i++) {
        const dow = daysOfWeek[i];
        if (data.day() > dow && data.day() < daysOfWeek[(i + 1) % daysOfWeek.length]) {
            next = daysOfWeek[(i + 1) % daysOfWeek.length];
            index = i;
            break;
        }
    }
    if (next === -1) {
        next = daysOfWeek[0];
        index = 0;
        if (data.day() > daysOfWeek[daysOfWeek.length - 1]) next += 7;
    }
    data.add(next - data.day(), 'days');
    return [ data, index ];
}

function gerarIntervalo(dt_inicio, dt_final, daysOfWeek, hours) {
    // ordena os dias da semana
    daysOfWeek.sort((a, b) => parseInt(a) - parseInt(b));
    // ajusta a data inicial
    let [ start, index ] = ajustaProximoDoW(moment(dt_inicio), daysOfWeek);
    let end = moment(dt_final);

    // diferenças a serem adicionadas para obter a próxima data
    let diffs = [];
    for (let i = 0; i < daysOfWeek.length; i++) {
        diffs[i] = ((daysOfWeek[(i + 1) % daysOfWeek.length] + 7) - daysOfWeek[i]) % 7;
    }

    let result = [];
    // compara início e fim, ignorando o horário
    while (end.isSameOrAfter(start, 'day')) {
        for (const h of hours) {
            const [hour, minute, second] = h.split(':').map(v => parseInt(v));
            start.set({ hour, minute, second });
            result.push(start.format('YYYY-MM-DD HH:mm:ss'));
        }
        start.add(diffs[index], 'days');
        index = (index + 1) % diffs.length;
    }
    return result;
}

let daysOfWeek = [0, 3, 5]; // domingo, quarta e sexta
let horarios = ["10:00", "16:00", "22:30"];
console.log(gerarIntervalo('2021-12-01', '2021-12-10', daysOfWeek, horarios));
<script src="https://momentjs.com/downloads/moment.min.js"></script>


text:
Q: firebase authentication (Access is denied) "generate release signed APK" I'm using Firebase Authentication email&pass for Sign in.  With database setting "Start in test mode" and change the rules for both read&write to "true". It really works perfectly via USB debugging. But when I generate for release signed APK, it shows error in build output with Message like this,

C:\Users\Public\MyAppName\app\firebase-database (Access is denied)

and also i've tried this firebase-authentication-not-working-in-signed-apk
and stil not worked for me.
any solution?
My code :
class LoginActivity : AppCompatActivity() {

lateinit var auth: FirebaseAuth

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_login)
    supportActionBar!!.hide()
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)

    auth = FirebaseAuth.getInstance()

    val curretuser = auth.currentUser
    if (curretuser != null) {
        startActivity(Intent(this@LoginActivity, ProfileActivity::class.java))
        finish()
    }

    login()
}

private fun login() {
    bt_loginbuttonLogin.setOnClickListener {

        if ( TextUtils.isEmpty(et_usernameinputLogin.text.toString())){
            et_usernameinputLogin.setError("Masukan User Name")
            return@setOnClickListener
        }
        else if ( TextUtils.isEmpty(et_passwordinputLogin.text.toString())){
            et_passwordinputLogin.setError("Masukan password")
            return@setOnClickListener
        }
        auth.signInWithEmailAndPassword(et_usernameinputLogin.text.toString(), et_passwordinputLogin.text.toString())
            .addOnCompleteListener {
                if (it.isSuccessful) {
                    Toast.makeText(this@LoginActivity, "login berhasil", Toast.LENGTH_LONG).show()
                    startActivity(Intent(this@LoginActivity, ProfileActivity::class.java))
                    finish()
                } else {
                    Toast.makeText(this@LoginActivity, "Email Atau Pasword Salah", Toast.LENGTH_LONG).show()
                }
            }
    }

    tv_registertextLogin.setOnClickListener{
        startActivity(Intent(this@LoginActivity, RegistrationActivity::class.java))
    }
}

A: solved with this video,
thanks internet.
this link
i was wrong to add SHA certificate fingerprints into my firebase console.
now i can generate release signed APK.


text:
Q: How to reach two layouts in one java class? I want to include two layouts in one java class. How can I make it? I am using android studio.
I want to use both layouts. And I want to use two buttons in different layouts from one java file. I am using setContentView but I am using a button from different activity too. So when I try my app, it crashes. I am using findviewbyid from different layout and app crashes. How can I block it?

A: If you have two separate layout files, you can use include to add those the layout you are inflating in that activity.
<include layout="@layout/layout1"/>
<include layout="@layout/layout2"/>

Add these inside the layout of that activity and you can then use the different layout and the buttons in them from the same activity.
Although without much clarity on your specific use case, the help we can give is limited.


text:
Q: Notify users when an edit is rejected Been seeing way too many "minimal" edits

@Schism - perhaps that's something that needs to be fixed? A
notification that "Your edit was rejected, please view the reasons why
and try and do better next time" would be good –  Robotnik

Would be extremely beneficial to let editors know what they are doing wrong if their edit is rejected, and would really help improve the quality of edits on the site.


text:
Q: Wallpaper won't stay I'm a new Lubuntu user (LXLE to be precise). I want to know why doesn't my wallpaper stay after a reboot? Any help is appreciated.

A: All you need to do is

*

*Copy file to your Home directory (partition of Ubuntu)

*add execute permission to that image you are using by

chmod 751 filename

It won't change when you restart!


text:
Q: build user chroot on first login I'm using ldap for remote user authentication and I basically need to either figure out how to:
a.  chroot a user on machine b from machine a via nfs,(which doesn't seem possible without mounting more directories than I'm comfortable with)
or -------
b.  After adding a user to the ldap db on machine a, force a script to be executed on machine b during the users login that will auto chroot the user before they are allowed to do anything upon their first login.

I'm thinking my second option is probably the best bet, and was thinking along the lines of using pam_exec.so to call the script.  However, I have a few concerns about this approach.  First, I'm not sure if the script that will be run will have root permissions which it will need to perform the chroot.  Second, I'm not sure if pam_exec happens early enough in the login process to be an effective option.  Lastly, I need to make sure that the code works in both pam.d/ssh and pam.d/su to consider it a valid solution.
Are my concerns valid or does it seem like this would be a good solution?  Or is there a better approach to this problem.

A: First of all, arguably, chroot might not be considered a security feature. There are opinions in the other direction, as well.
Arguably, what you need to implement is a reproducible, auditable method of limiting the ability of the user to perform actions other than the strictly allowed.
If you register your users in LDAP, surely you have already deployed the mechanisms to perform LDAP authentication on any machine connected to this LDAP, be it by means of sssd or using any other PAM module, it is not relevant to the rest of the solution, and is assumed to be already in place (in my case, I'm using freeIPA and sssd).
To implement this scenario, what I currently do is the following (be aware that this kind of restrictions requires that several conditions are met, otherwise the restriction can be easily circumvented):

*

*The users do not belong to the wheel group, the only one authorized to use su (enforced via PAM). Usually, a non-LDAP user (sysadm) exists to allow trusted administrators performing actions in cases of disaster recovery or LDAP unavailability.

*The users are given a properly secured rbash with a read-only PATH pointing to a private ~/bin, this ~/bin/ directory contains links to all allowed commands, for example:
$ ll ~/bin
total 0
lrwxrwxrwx. 1 root dawud 14 Sep 17 08:58 clear -> /usr/bin/clear*
lrwxrwxrwx. 1 root dawud  7 Sep 17 08:58 df -> /bin/df*
lrwxrwxrwx. 1 root dawud 10 Sep 17 08:58 egrep -> /bin/egrep*
lrwxrwxrwx. 1 root dawud  8 Sep 17 08:58 env -> /bin/env*
lrwxrwxrwx. 1 root dawud 10 Sep 17 08:58 fgrep -> /bin/fgrep*
lrwxrwxrwx. 1 root dawud  9 Sep 17 08:58 grep -> /bin/grep*
lrwxrwxrwx. 1 root dawud 10 Sep 17 08:58 rview -> /bin/rview*
lrwxrwxrwx. 1 root dawud 13 Sep 17 08:58 rvim -> /usr/bin/rvim*
lrwxrwxrwx. 1 root dawud 13 Sep 17 08:58 sudo -> /usr/bin/sudo*
lrwxrwxrwx. 1 root dawud 17 Sep 17 08:58 sudoedit -> /usr/bin/sudoedit*
lrwxrwxrwx. 1 root dawud 13 Sep 17 08:58 tail -> /usr/bin/tail*
lrwxrwxrwx. 1 root dawud 11 Sep 17 08:58 wc -> /usr/bin/wc*

*the users are given a restricted, read-only environment (think of stuff like LESSSECURE, TMOUT, HISTFILE variables). This is to avoid shell escapes from commands like less or vim.

*if MAC restrictions are in place (the specific GNU/Linux distribution you are using has SELinux enabled), the users are mapped to the SELinux user staff_u and given rights to execute commands as other user as required via sudo. The specific sudorules allowed need to be carefully reviewed to prevent the user from circumventing these limitations, and can also be deployed in your existing LDAP infrastructure (this is one of freeIPA features).

*the users' /home, /tmp and possibly /var/tmp are polyinstantiated via /etc/security/namespace.conf:
/tmp       /tmp/.inst/tmp.inst-$USER-     tmpdir:create   root
/var/tmp   /tmp/.inst/var-tmp.inst-$USER- tmpdir:create   root
$HOME      $HOME/$USER.inst/              tmpdir:create   root

Polyinstantiation of directories is not a new feature, it has been available for quite a long time now. As a reference, see this article from 2006. As a matter of fact, a lot of modules already use pam_namespace by default, but the default configuration at /etc/security/namespace.conf does not enable polyinstantiation.
Also, /etc/security/namespace.init should make all skeletal files read-only for the users and owned by root.
This way you can choose whether the users can execute any command on their own behalf (via a link in the private ~/bin directory, provisioned via /etc/skel, as explained above), on behalf of other user (via sudo) or none at all.


text:
Q: How to extract folder's name (a series number ID) in R? I have got a large number of folders containing CSV and htm files. Each folder has an unique folder name as ID. I am wondering would it be possible extract folder names?

A: For any directory path string, you can use:
fullpath = getwd()
directoryname = basename(fullpath)

For a whole range of directories:
manydirectories = list.dirs()
directorynames = basename(manydirectories)

You only need to omit the "." in directorynames to then get the folder names within that directory.


text:
Q: Aggregating Data with MAX & GROUP BY in VIEWS with a WHERE restriction Here is my Request.
Our Application generates a statement which invokes a view in a SQL-Server DB.
This statement selects DISTINCT or GROUP BY Data-fields from the view
passing a restricted subset of IDs.
Background:
I am using SQL-Server 2008 R2 running on Windows Server 2008 R2
With an example-table I will try to explain the problem.
Given this example table: [TabA]
ID [INT]    DATA [VARCHAR(8)]
---         ----
51           A1
50           A1
110          A5
100          A5

We then create the following view:
CREATE VIEW ViewOnTabA
AS
 SELECT
   MAX(ta.ID) As ID, ta.DATA
 FROM
   TabA ta
 GROUP BY ta.DATA
GO

With this statement, generated by our application,
we call the view passing some ID values:
SELECT
 ID, DATA
FROM ViewOnTabA
WHERE ID in (51,50,110,100)

The result is Ok
The Data fields are grouped and complete:
ID  DATA
--  ----
51  A1
110 A5

If instead of all IDs we pass only the smaller ID number: (50 instead of 51)
...
WHERE ID in (50,110,100)

The result is incomplete (ID 50 is missing):
ID  DATA
--  ----
110 A5

But we expected
ID  DATA
--  ----
50  A1
110 A5

It seems that in a VIEW the GROUP BY is executing before the WHERE condition.
As we cannot invoke stored procedures from our application,
we have to rely on calling a view.
Are there other possibilities to have a DISTINCT or GROUP BY order
of the DATA fields (in the example) within a VIEW.
The ID-fields must not necessarily be filtered with the MAX aggregate function.
But the Where restriction has to be applied on them.
P.S.
Executing this Select in a normal query including
the (WHERE ID in ...) restriction  it works fine:
 SELECT
   MAX(ta.ID) As ID, ta.DATA
 FROM
   TabA ta
 WHERE ID in (50,110,100)
 GROUP BY ta.DATA

output>>>>
ID  DATA
--  ----
50  A1
110 A5

For simulating this example
here are the create & insert statements:
create table TabA
(
ID  int ,
DATA varchar(8)
)
go

insert into TabA values (51,'A1')
insert into TabA values (50,'A1')
insert into TabA values (110,'A5')
insert into TabA values (100,'A5')

Any help would be greatly appreciated.
Regards,
Alberto

A: For this to work the way that you are expecting to, you would need to remove the group by from your view.  The reason why you are not seeing for e.g. the "50" in your results, is because it is already filtered out by the group by in the view.
You will either need to change your view (if nothing else is using it), or create a new view like this:
CREATE VIEW ViewOnTabA  /* or use a new name */
AS
 SELECT ta.ID, ta.DATA
 FROM TabA ta
GO

... and then run the select statement with the where clause on this view.
SELECT
   MAX(ta.ID) As ID, ta.DATA
 FROM
   ViewOnTabA ta  /* or use the new view's name */
 WHERE ta.ID in (50,110,100)
 GROUP BY ta.DATA


text:
Q: Navigation bar jumps in iPhone X when using Toolbar When going from one view to another, that uses a toolbar over the navigation bar, then the navigation bar jumps as seen in the image. Only happens in iPhone X

I have already added:
[self.tableView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];

But that did not help on this issue.
I am not using Storyboards

A: I've had a similar behaviour occur to me when the view controller I was trying to push was not checked for "Use Safe Area Layout Guides". My experiences seems to indicate Apple may change the position of the bottom/top layout guides at runtime if it detects the navigation stacks is using Safe Area layout guides; unfortunately it does produces a virtual artifact.
If you are not using storyboards, you can do it in code.  I recommend this Safe Area Layout Guide tutorial for more information on the topic.


text:
Q: Rails select_tag will not access belongs_to relation I am trying to do a
select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", "entity.name", "1")

but entity.name wont work throws an undefined method `entity.name'. "entity" belongs to another model. through an entity_id
class Employee < ActiveRecord::Base

  include UUIDHelper

  belongs_to :entity
  has_one :status
  has_many :restdays
  has_one :regular_work_period

  validates_presence_of :entity

end

require 'file_size_validator'
class Entity < ActiveRecord::Base

  include UUIDHelper

  has_one :access, autosave: true
  has_one :employee, autosave: true
  has_many :contact_detail, autosave: true
  has_many :file_set
  has_many :link_set

  mount_uploader :logo, AvatarUploader
  validates_presence_of :name
  validates :name, uniqueness: true
  validates_length_of :description, maximum: 256

  validates :logo,
        :file_size => {
            :maximum => 25.megabytes.to_i
        }
end

A: Either you add a method to your employee that you can call, like:
class Employee < ActiveRecord::Base
  ...

  def entity_name
    self.entity.name
  end
end

and then:
select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", "entity_name", "1")

or you can use a lambda instead of adding a method:
select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", lambda { |employee| employee.entity.name }, "1")

A: You could add this to your Employee model:
def entity_name
  self.entity.name
end

Or you could add a delegate like this to your Employee model:
delegate :name, :to => :entity, :prefix => true

Then you could do:
select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", "entity_name", "1")

A: The 'Entity' model refers to a table name 'entities' on the database (unless you overwrote the default for the table name). Use "entities.name" instead. This will work if you joined the result @employees = Employer.joins(:entity).


text:
Q: PHP convert MySQL datetime to Unix Timestamp I'm confused about timezone differences when converting a MySQL datetime to Unix timestamp. It appears to me that MySQL datetimes (2011-02-07 09:45:00) are in the server's local timezone. I want to convert this datetime into a Unix timestamp, which is always in the GMT timezone. To do this conversion, PHP passes the datetime into strtotime. The datetime string contains no timezone, so will strtotime assume the argument is local timezone or GMT?

A: The strtotime function will assume the datetime is in the server's local timezone.

A: Why not use MySQL's UNIX_TIMESTAMP() function?


text:
Q: Does NAT block UDP packets coming from a server connected using TCP? I'm trying to develop a game with using java server and game maker studio client. I've written some basic connection code and it works fine in my local network. But when I host the server and try to connect my client gets the ID assigned by server which sent through TCP but it does not receive any commands sent by UDP protocol.  How server can't establish connection over UDP while it can over TCP. I heard I need UDP hole punching. But once I'v written the server with game makers studio networking functions and UDP was able to establish connection with same configurations on the server. So they are using hole punching in their built-in functions ? If I need to implement hole punching instead should I use TCP only or I should learn hole punching for any cost ?

A: There are quite a few questions here so I'll try to break them apart piece by piece. First of all...

Does NAT block UDP packets coming from a server connected using TCP?

Yes. Just because the NAT has established a TCP connection between two machines does not mean it will automatically forward UDP packets as well.

How server can't establish connection over UDP while it can over TCP?

TCP is a connection oriented protocol while UDP is a connectionless protocol, so there is technically no such thing as a "UDP connection". When two computers communicate via UDP they simply exchange UDP packets back and forth and the "connection" is implied (or managed at a higher level), rather than spelled out by the UDP protocol itself.

I heard I need UDP hole punching... If I need to implement hole punching instead should I use TCP only or I should learn hole punching for any cost ?

UDP hole punching is one possibility but it is complicated and not 100% guaranteed that all NATs will be compatible. Instead, you could build your game using just TCP, then once it is working and deployed, experiment with more advanced communication channels like UDP hole punching or WebRTC Data Channels.


text:
Q: Delete and rename files using unlink() and rename() I have a folder, which contains thousands of images for my website products, looking like this:
D25200-1.jpg
D25200-2.jpg
D25200-3.jpg
D25201-1.jpg
D25201-2.jpg
D25201-3.jpg
D25201-4.jpg

Which means, that product D25200 has 3 photos and D25201 has 4 photos.
I want to delete some of the images, but keep the count from 1. For example, if I delete D25201-1.jpg and D25201-2, the rest of the images to get renamed as D25201-1.jpg and D25201-2.jpg.
This is the code I've created so far, but it only deletes the photos:
<?php
$codes = array(
    'D25201' => '1,2'
);

$dirs = array(
    dirname(__FILE__) . '/products/',
    dirname(__FILE__) . '/products/large/',
    dirname(__FILE__) . '/products/medium/',
    dirname(__FILE__) . '/products/small/'
);

foreach($codes as $code => $photos) {
    $photos = explode(',', $photos);

    foreach($photos as $photo) {
        foreach($dirs as $dir) {
            unlink($dir . $code . '-' . $photo . '.jpg');
        }
    }
}
?>

A: I havn't had time to test this but something like this should do it (Or atleast give you a hint at a possible direction the figure the rest out yourself):
$codes = array(
    'D25201' => '1,2'
);

$dirs = array(
    dirname(__FILE__) . '/products/',
    dirname(__FILE__) . '/products/large/',
    dirname(__FILE__) . '/products/medium/',
    dirname(__FILE__) . '/products/small/'
);

foreach($codes as $code => $photos) {
    $photos = explode(',', $photos);

    foreach($photos as $photo) {
        foreach($dirs as $dir) {
            if(unlink($dir . $code . '-' . $photo . '.jpg');){
              //if unlink is successfull... loop all images in current dir
                $files = scandir($dir);
                $c = 0;
                foreach($files as $file){
                   $c++;
                   //if the name of the image contains the productcode
                   if(strpos($file,$code) !== false){
                        //rename the file
                        rename ($file , $dir . $code . '-' . $c . '.jpg');
                   }
                }
            }
        }
    }
}

There is probably a better way, using less loops, but something like this should work.


text:
Q: Elasticsearch: Date Aggregation Most Recent I have query that works. It aggregates data based on Id and finds the MOST RECENT object based on the created field. The problem I have is that I would like to find the SECOND MOST RECENT instead of MOST RECENT. How would I go about this? I have been looking all through the docs and all I can find is range which doesn't help me to much. Thank you :)
{
    "query":{
      "match": {
         "name": "Robert"
      }
    },
    "aggs": {
        "previous": {
            "terms": {
                "field": "Id",
                "order": {"timeCreated": "desc"}
            },
            "aggs": {
                "timeCreated": {
                    "max": {"field": "created"}
                }

            }
        }
    }
}

A: Top_hits is what you are looking for. Use this:
{
"query":{
  "match": {
     "name": "A"
  }
},
"aggs": {
    "previous": {
        "terms": {
            "field": "Id"

        },
         "aggs": {
            "latestRecords": {
              "top_hits": {
                "sort": {
                  "created": {
                    "order": "desc"
                  }
                },
                "size" :2
              }
            }
          }
       }
     }
   }


text:
Q: Grails Spring Security Active Directory login failed when runnable jar in docker container I'm using a grails 4 runnable jar with spring Security.
Authentication is mapped to an Active Directory.
It works fine in dev mode and when run with java -jar on openjdk 11.0.2 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
The same in a docker container (on the same host) fails with the "wrong password" error (really not obvious in our beloved Active Directory): javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580 ]
Dockerfile is
FROM adoptopenjdk/openjdk11:latest
EXPOSE 8080

RUN mkdir /opt/app
COPY build/libs/*.jar /opt/app/app.jar

CMD ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/opt/app/app.jar"]

I'm guessing something is different somewhere in the system properties but which one...

A: I guess adding "-Dfile.encoding=UTF-8" just solved my problem.


text:
Q: Writing a Byte Array to a Range in Excel VBA without looping I am trying to dump an array to a worksheet directly without looping. This is possible for all data types, except a 'Byte' array. Why is this so?
I want to use Byte array, so as to save memory cost (data often exceeds the 2GB excel limit). While I have worked around this problem by dividing into chunks, I want to understand why a Byte array can't be dumped into a range directly.
edit 1:
The array value is either 0 or 1. And I want the output shown as it is.
Using a Boolean array gives it as TRUE or FALSE, which I don't prefer.
Any optimized(memory and speed) ways to do this?
Sub ArrayPasting()

    Dim byteArray(1 To 3) As Byte
    Dim intArray(1 To 3) As Integer

    For i = 1 To 3
        byteArray(i) = i
        intArray(i) = 2 * i
    Next i

    ActiveSheet.Range(Cells(1, 1), Cells(1, 3)).Value = intArray    'range populated with intArray
    ActiveSheet.Range(Cells(2, 1), Cells(2, 3)).Value = byteArray   'error

End Sub

A: You could use Application.transpose (in this case):
Sub ArrayPasting()

    Dim byteArray(1 To 3) As Byte
    Dim intArray(1 To 3) As Integer

    For i = 1 To 3
        byteArray(i) = i
        intArray(i) = 2 * i
    Next i

    ActiveSheet.Range(Cells(1, 1), Cells(1, 3)).Value = intArray    'range populated with intArray
    ActiveSheet.Range(Cells(2, 1), Cells(2, 3)).Value = Application.Transpose(Application.Transpose(byteArray))

End Sub

A: Say we have a REALLY big Boolean array that we want to:

*

*dump into cells

*convert to 1/0 (where TRUE is 1)
then something like:
Sub SayBoo()
    Dim Boo(1 To 2, 1 To 2) As Boolean
    Dim r As Range
    Set r = Range("A1:B2")

    Boo(1, 1) = True
    Boo(1, 2) = True
    Boo(2, 1) = False
    Boo(2, 2) = False
    r = Boo

    With r
        .Value = Evaluate("=IF(" & .Address & ",1,0)")
    End With

End Sub

will do it.

A: You cannot store binary array values direclty in Excel. You have to convert them to the format acceptable by Excel. Encode array values as base-64 string. Then you can store it in Excel cell.
Well, if you really need to store binary data in Excel (it's a little bit abusing of Excel. Excel wasn't created for binary data storage) you need to:

*

*Convert binary data to text (you are already doing it by base-64 encoding)

*Split text into smaller chunks and store each piece in separate cell. This way one image would be stored in several cells.


text:
Q: How to count just first paragraphs with explode() I have problem when Paragraph is in Blockquote, so I don't want to count those paragraphs. Basically, i want to exclude blockquote
$banerAfter[2] = "
nineth
"; //display after the second paragraph
$banerAfter[6] = "
nineth
"; //display after the sixth paragraph
$banerAfter[9] = "
nineth
"; //display after the nineth paragraph

$content = "
First paragraph

Don't count me

Second paragraph
";
$content = explode("
", $content);
$count = count($content);
for ($i = 0; $i < $count; $i++ ) {
  if ( array_key_exists($i, $banerAfter) ) {
    echo $banerAfter[$i];
  }
  echo $content[$i] . "
";
}

A: You can easy remove the
 tag and its content with preg_replace:
$content = "
First paragraph

Don't count me

Second paragraph
";
$content = preg_replace("/<blockquote.+?<\/blockquote>/i", "", $content);
$xpl = explode("
", $content);
echo $count = count(array_filter($xpl));

Result:
2

array_filter is needed to clean the array because explode maintain also the empty string after the last
 in your string.

A: You can remove the content between
 with a preg_replace.
Try this:
$content = "
First paragraph

Don't count me

Second paragraph
";
$content = preg_replace ("/
(.*?)<\/blockquote>/i", "", $content);
$content = explode("
", $content);
$count = count($content);
echo $count;

A: Also this is one way to do it
$content = "
First paragraph

Don't count me

Second paragraph
";
$p = array_values(array_filter(preg_split("/\<\/?\w+\>/", $content)));
echo strlen($p[0]);


text:
Q: Spatial Indexing and Bounding Box I have two tables each with a SHAPE Geom Column, and I'm working on getting the intersected area between every shape in the first table with the second table.
The second table has millions of rows, and hence my query takes a long time to execute.
I thought of creating an index on the SHAPE Column using:
create spatial index SPIX_Shape on LAND_V1(Shape) using geometry_auto_grid

I'm getting the following error message:

The CREATE SPATIAL INDEX statement is missing the required parameter 'BOUNDING_BOX'.
Validate the statement against the index-creation syntax.

I'm new to the spatial data world, so correct me if I'm wrong here.
Initially, I thought that bounding box should be automatically created by the DB Engine, checking each individual shape Geom and creating a bounding box for that when indexing. How do I manually specify a bounding box for my data?
And will that bounding box then affect the intersected area I calculate at the end? Will it differ depending on the GeomType [Polygon/MultiPolygon/GeometryCollection etc..]?
Here's my query:
select
                s1.*,
                s2.Shape.STIntersection(s1.Shape) as SHAPE
from   LAND_V1 s1
inner join LAND_V2 s2 -- biggerTable
ON s1.Shape.STIntersects(s2.Shape) = 1

How would I leverage spatial indexing here


text:
Q: Excel VBA Macro Formula Help Regarding not show formula in formula bar I want to use if condition formula to calculate the cube via vba macro button. I write code and its working is fine but code is show in formula bar and also working with formula come from vba macro and remain their, I want that this formula did not should be show in formula bar and the calculation should be done only via macro button when i press it. here is my code. Thanks
Sub CalCubMeter()

Worksheets("sheet1").Range("d3:d21").Formula = "=if(c3=C3,PRODUCT($c3^3),""-"")"

End Sub

A: Something along the lines of:
Public Sub CubeColumnC
    Dim wb as Workbook
    Dim ws as Worksheet
    Dim sourceRange as Range
    Dim sourceArr()
    Dim i as long

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1") 'change to as needed
    Set sourceRange = ws.Range("C3:C21")

    'Assign column c values to array
    sourceArr = Application.Transpose(sourceRange.Value)

    With ws
        For i = Lbound(sourceArr) To Ubound(sourceArr) 'Write back out to col D
            If .Cells(2+i, "C") = vbNullString Then   'if blank
                .Cells(2+i, "D") = "-"
            Else
                .Cells(2+i,"D")  = sourceArr(i)^3 'Calc the Cube value
            End If
       Next i
   End With
End Sub

I ignored your C3 = C3 as this is always True, amend as you see fit.
Edit: Application.WorksheetFunction.Power(sourceArr(i),3) changed to sourceArr(i)^3 for Cube value


text:
Q: Search partial match strings from multiple table in mysql query (very complex query) I have 3 tables - business, products and subproducts.
The table structure is http://sqlfiddle.com/#!9/f3342/1 here.
I need to pass in a string to search. It has to search all the three tables(all columns) and return id from the business table. bid is the business id (id) for products table and pid is the product id (id) for sub_products table.
Then I need to order the results in the order of table like  business,products then subproducts.
How can I do all this?
Thanks

A: Its easy if it doesn't have to be just one query
SELECT id
FROM business
WHERE Concat(name, '', category, '', s_desc, '' , f_desc, '', address1, '', views) like '%test%'

This will search for the specified columns in the business table that contains 'test' string. You can extend this query to include all the relevant columns as well as different tables you want to search. Just pass your search string from php into that query and it will return the id.
P.S. don't pass your input directly into your query (process and escape it first), as it will be open to sql injection.
I hope this helps.


text:
Q: Hartshorne IV Remark 4.10.9 a morphism to Jacobian variety As in the title, in Hartshorne's algebraic geometry chapter IV Remark 4.10.9, $X$ is a curve over $k$ and $J$ is the Jacobian variety of $X$ of $X$. There he defines a morphism $X^n \rightarrow J$ by "$(P_1, \cdots, P_n) \mapsto \mathcal{L}(P_1+\cdots+P_n - nP_0)$."
According to the definition of the Jacobian variety by the universal property, this is equivalent to give an invertible sheaf $\mathcal{M}$ on $X \times X^n$ such that for $(P_1, \cdots, P_n) \in X^n, \ \mathcal{M}_{(P_1, \cdots, P_n)} \simeq \mathcal{L}(P_1+\cdots+P_n - nP_0).$
But how does one know that there is such an invertible sheaf?

A: Define $p\colon X\times X^n\to X$ by
$$
p(x,y_1,\dots,y_n)=x
$$
and $q_{01},\dots,q_{0n}\colon X\times X^n\to X\times X$ by
$$
q_{0i}(x,y_1,\dots,y_n)=(x,y_i).
$$
Let $\Delta$ denote the diagonal divisor of $X\times X$.
Then $\mathcal{L}(\Delta)$ is a line bundle on $X\times X$ whose restriction to $X\times \{P\}$ is isomorphic to $\mathcal{L}(P)$.
Consider the line bundle
$$
\mathcal{M}:=q_{01}^*\mathcal{L}(\Delta)\otimes\dots\otimes q_{0n}^*\mathcal{L}(\Delta)\otimes p^*\mathcal{L}(P_0)^{\otimes -n}.
$$
on $X\times X^n$.
Then the restriction of $\mathcal{M}$ to $X\times \{(P_1,\dots,P_n)\}$ is isomorphic to $\mathcal{L}(P_1+\dots+P_n-nP_0)$.


text:
Q: How to add convenient buttons for new custom post statuses I add new post status via this code in functions:
function custom_post_status() {
    register_post_status( 'spam', array(
        'label' => _x( 'Spam', 'post' ),
        'public' => false,
        'exclude_from_search' => true,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop( 'SPAM (%s)', 'SPAM (%s)' ),
    ) );
}

function append_post_status_list() {
    global $post;
    $complete = '';
    $label = '';
    if( $post->post_type == 'post' ) {
        if( $post->post_status == 'spam' ) {
            $complete = ' selected="selected"';
            $label = 'SPAM';
        }

        echo '';
    }
}

add_action( 'init', 'custom_post_status' );
add_action( 'admin_footer-post.php', 'append_post_status_list' );

How to add:
 1. Convinient button in post editing page (like Update or Preview) in admin panel

*Add "Send to spam" option in post listing in admin panel

A: There is a work tool set that works nice for this kind of add on, called CMB2.  You can add all the fields and buttons you want as part of a metabox series.   Metaboxes are what make up the admin section section of wordpress.
https://wordpress.org/plugins/cmb2/
For example..a snippet:
 function custom_post_status() {
          register_post_status( 'spam', array(
         'label' => _x( 'Spam', 'post' ),
         'public' => false,
         'exclude_from_search' => true,
         'show_in_admin_all_list' => true,
         'show_in_admin_status_list' => true,
         'label_count' => _n_noop( 'SPAM (%s)',
 'SPAM (%s)' ),
     ) );
 }

 add_action( 'cmb2_admin_init', 'cmb2_sample_metaboxes' );
 /**
  * Define the metabox and field configurations.
  */
 function cmb2_sample_metaboxes() {

// Start with an underscore to hide fields from custom fields list
$prefix = '_yourprefix_';

/**
 * Initiate the metabox
 */
$cmb = new_cmb2_box( array(
    'id'            => 'test_metabox',
    'title'         => __( 'Test Metabox', 'cmb2' ),
    'object_types'  => 'spam', '  // <<<==== YOUR POST STATUS NAME
    'context'       => 'normal',
    'priority'      => 'high',
    'show_names'    => true, // Show field names on the left
    // 'cmb_styles' => false, // false to disable the CMB stylesheet
    // 'closed'     => true, // Keep the metabox closed by default
) );

// Regular text field
$cmb->add_field( array(
    'name'       => __( 'Test Text', 'cmb2' ),
    'desc'       => __( 'field description (optional)', 'cmb2' ),
    'id'         => $prefix . 'text',
    'type'       => 'text',
    'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
    // 'sanitization_cb' => 'my_custom_sanitization', // custom sanitization callback parameter
    // 'escape_cb'       => 'my_custom_escaping',  // custom escaping callback parameter
    // 'on_front'        => false, // Optionally designate a field to wp-admin only
    // 'repeatable'      => true,
) );

// URL text field
$cmb->add_field( array(
    'name' => __( 'Website URL', 'cmb2' ),
    'desc' => __( 'field description (optional)', 'cmb2' ),
    'id'   => $prefix . 'url',
    'type' => 'text_url',
    // 'protocols' => array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet'), // Array of allowed protocols
    // 'repeatable' => true,
) );

// Email text field
$cmb->add_field( array(
    'name' => __( 'Test Text Email', 'cmb2' ),
    'desc' => __( 'field description (optional)', 'cmb2' ),
    'id'   => $prefix . 'email',
    'type' => 'text_email',
    // 'repeatable' => true,
) );

// Add other metaboxes as needed

}
More can be seen here.
https://github.com/CMB2/CMB2/wiki/Basic-Usage#create-a-metabox


text:
Q: How work method injection in Dagger2 For example I have next code
public class Class {

   @Inject
   public void classMethod(SomeObject object) {
   //something
   }
}

Then I invoke classMethod method got SomeObject instance from graph. But how to run the method, because at the moment I dont have have method arg.

A: Haven't tried this myself, but my guess is that methods annotated with @Inject are designed to be called by Dagger only. Example:
class MyFragment extends Fragment {

  SomeObject someObject;

  @Override
  public void onCreate(Bundle saved) {
    ((InjectorActivity) getActivity()).component().inject(this);
  }

  @Inject
  public void injectSomeObject(SomeObject someObject) {
    this.someObject = someObject;
  }
}

Would be interested to know if it's indeed working like this.


text:
Q: Angular 2 json pipe shows content but not actual data

{{event | json}}

This works and shows all the correct data!

{{event.name}}

But this does not :/
I'm using Parse to fetch data and yes, there's a key with name, name.
export class EventsComponent {
  events: any[];

  ngOnInit() {
    this.fetchEvents();
  }

  fetchEvents() {
    let events = Parse.Object.extend('Event');
    let query = new Parse.Query(events);
    query.find({
      success: (results) => {
        this.events = results;
      },
      error: (error) => {
         console.log(error);
      }
   });
  }
}

A: Use the ?. safe-navigation (or Elvis) operator

{{event?.name}}

event.name breaks when Angular tries to resolve the binding and event is still null because you fetch in only in ngOnInit() which is quite a bit after Angulars first attempt to bind values.


text:
Q: why can't I change the value of a var named coma after and if statement I'd like to change the value of comma to true if a string contains a comma
xcode swfitui
struct ContentView: View {
        @State var dos = ""
        @State var coma : Bool = false

        var body: some View {
            Form {
            TextField("dosis", text: $dos)

                if dos.contains(",") == true {

                   coma = true
                }
            }
    }
    }

A: You cannot put that type code wherever you like in a View. The view expect to show other views, and your if is not returning a view. Try this approach where your if is in a modifier, or a function:
struct ContentView: View {
    @State var dos = ""
    @State var coma = false

    var body: some View {
        Form {
            TextField("dosis", text: $dos)
                .onChange(of: dos) { doz in
                    if doz.contains(",") {
                        coma = true
                    }
                    print("--> dos: \(dos)  coma: \(coma)")
                }
        }
    }
}

You can also use: .onSubmit {...}


text:
Q: How to break from middle of generator in dart? How can I break from dart generator based on some condition?
fn sync*(...){
  yield 1;
  yield 2;
  if(someCondition()) //cancel/break the generator
  yield 3;
  if(someCondition2()) //cancel/break the generator
  yield 4;
  if(someCondition4()) //cancel/break the generator
  yield 5;
}

A: Simply return from your generator when you want it to stop generating new values:
Iterable<int> fn(bool flag) sync* {
  yield 1;
  yield 2;
  if (flag) {
    return;
  }
  yield 3;
}

void main() {
  print(fn(true).toList()); // Prints: [1, 2]
  print(fn(false).toList()); // Prints: [1, 2, 3]
}


text:
Q: How to have multiple images in a sequence when a key is pressed - Processing I want to be able to have animate a sprite by using 3 different images when a key is pressed how would I do so, with an array as well as without one.

A: You can easily repurpose the Processing Animated Sprite example. You'll need one Animation instance and keyPressed() to animate the sprite (e.g. toggle frame updates)
Shameless plug: another option is using a library such as ImageSequencePlayer

A: If you want to avoid arrays and libraries this technique will work.  The frameRate() needs to turned down to 4 or 5 and then place a counter in the draw() which is reset to zero when it exceeds the number of images. As the counter value is passed to a display function it then displays the corresponding image. The images should be placed in a folder titled "data" in the sketch folder.
/*
 Must be GIF, JPEG, or PNG images
 */
PImage img0;
PImage img1;
PImage img2;
PImage img3;
PImage img4;

int counter = 0;

void setup() {
  size(400, 400);
  img0 = loadImage("frog0.png");
  img1 = loadImage("frog1.png");
  img2 = loadImage("frog2.png");
  img3 = loadImage("frog3.png");
  img4 = loadImage("frog4.png");
}

void display(int count) {
  switch(count) {
  case 0:
    image(img0, 0, 0, width, height);
    break;
  case 1:
    image(img1, 0, 0, width, height);
    break;
  case 2:
    image(img2, 0, 0, width, height);
    break;
  case 3:
    image(img3, 0, 0, width, height);
    break;
  case 4:
    image(img4, 0, 0, width, height);
    break;
  }
}

void draw() {
  frameRate(4);
  display(counter);
  counter++;
  if (counter > 4) {
    counter = 0;
  }
}


text:
Q: django model ForeignKey relation I have 3 models User, Lesson, Company
class User(models.Model):
    pass

class Company(models.Model):
    pass

class Lesson(models.Model):
    user = models.ForeignKey(User)
    company = models.ForeignKey(Company)

How can I add one lesson for two companies

A: If a Company has multiple Lessons and you also want a Lesson to have multiple Companys, you should use a ManyToManyField
class Lesson(models.Model):
    user = models.Foreignkey(User)
    companies = models.ManyToManyField(Company)

c1 = Company()
c1.save()
c2 = Company()
c2.save()

l1 = Lesson()
l1.companies.add(c1, c2)

A: You should put ForeignKey to Company model:
class Company(models.Model):
    lesson = models.Foreignkey(lesson)

Create a new company object, and add it to the lesson:
>>> c1 = Comapany(attr="blah", attr2="foo")
>>> l1.comapany_set.add(c1)

and you can add a list of company objects to lesson
>>> l1.comapany_set.add(*company_objs)

now you can access companies related to specific lesson with company_setattribut:
lesson.company_set.all()

also you can now assign one lesson to differen companies:
company1.lesson = lesson
company2.lesson = lesson

A: You can do this via shell: python manage.py shell
a = Company.objects.first()
b = Company.objects.last()
c = Lesson.objects.first()

a.lesson_set.add(c)
b.lesson_set.add(c)

You can also use: lessons instead of: lesson_set if you change models with: related_name
class Lesson(models.Model):
    company = models.ForeignKey(Company, related_name='lessons')

And from now you can use it like:
a.lessons.add(c)
b.lessons.add(c)


text:
Q: AngularJS resource : how to update I'm using express-resource on the server.
In my AngularJS controller:
    var User = $resource('/services/users/:userId', {userId:'@id'},
        { update: {method:'PUT'} }
    );
    $scope.save = function(user) {
        user.$update(function(u) { console.log("User " + u)});
    }

The PUT method should go to /services/users/2 but it's actually sent to /services/users
So I get a 404
BTW, the user ID field if UserID (not userId or id) but I don't understand how am I supposed to declare the URL.

A: Ok, after digging a bit I found
var User = $resource('/services/users/:id', {id:'@UserID'},
    { update: {method:'PUT'} }
);


text:
Q: TFS Error occurring in Visual Studio Online I am getting the following error in Visual Studio:
TF30063: You are not authorized to access (my server address here).
The TFS server is actually on Visual Studio Online and I've logged into it separately several times today so the server is definitely available and I was able to check-in stuff to my TFS server earlier today.
There are two things that I think may have contributed to this error but I don't know how to fix them.

*

*When asked for the Login, I used the wrong email address a few times and the login box popped up another two or three times before disappearing.

*I installed the HTML Agility Pack through Nuget, uninstalled it, then re-installed it.
I am not sure if either of these are causing the error but the result is that I can't check-in anything.
Any ideas about how to fix this?  I can re-install Visual Studio but I don't want to and to just face the same issue at the end.


text:
Q: php for is not working if i pass the values through variable i am parsing a XML data with simplexml_load_file() function and when i display the data using for loop its display correctly from the number i mention to the limit
<?php
for($i=10; $i<=20; $i++){
{
 $offer->name;
}
?>

but when i declare the values through variable it does not work.
<?php
$result_start = $_REQUEST['start'];
$result_limit = $_REQUEST['limit'];

for($i=$result_start; $i<=$result_limit; $i++){
{
 $offer->name;
}
?>

one more strange thing is happening here is that the loop is repeating 2 times more. like if i mention the loop from 10 to 20 so it is showing me the values from 10 to 22.

A: It seems to me the problem would most easily be solved by casting the user input to integers:
$result_start = (int) $_REQUEST['start'];
$result_limit = (int) $_REQUEST['limit'];


text:
Q: Clean way to make a php login script on a site with includes? Basically I have an index.php file with navigation in form of includes only.

*

*My script can check whether a user exists by checking a database.

*It can also log you in if the check was successful.
My problem is redirects! Do I really have to use
echo "<meta http-equiv=refresh content=\"1; URL=index.php\">";?
And I also have to make tons of if-statements to cover the entire possibilities of a users actions (have to take evil people into account).
Headers are already ruled out because I use includes and requires.
I'm on the brinck of switching to ASP.NET or something rediculous... This scripting is making me mad :P

A: Sounds like you either need to use an existing content management system or framework or learn to code in a modular drop-in fashion.  Coding it for modularity would mean that the included script can be left out and the page still function as usual.
I'll post an example in a bit.
Just looked at your code.  The index page is insecure.  Do not do it like that.  I could do something nasty like index.php?p=../../../whateverfile and try to include it from outside of /inc/.  You need some sort of protection against user input.  Something like an array specifying valid files to include to check against, or a db table containing valid files to include that it can check against.
edit
Also, never ever store the password in a cookie.  You should generate a unique key or something for the login and store it and check against it instead of the password.
Here's what you'd want to do:  Split the login file up into checking logic and presentation.  Once you do that it means that the checking logic can be included anywhere on the page, while the form itself can also be placed anywhere.
Here's a little example:
loginCheck.php
if(isset($_POST['login']))
{

     if(!$_POST['username'] || strlen($_POST['username']) <= 3 || strlen($_POST['username']) >= 20)  //Check user input for validity
     {
          $loginerror['username'] = "Username is required.  Must be between 3 and 20 characters long.";
     }
     if(!$_POST['password'])
     {
          $loginerror['password'] = "Password is required.";
     }

     if(count($loginerror) == 0)
     {
          $username = mysql_real_escape_string(trim($_POST['username'])); //Do whatever to the user input
          $password = mysql_reql_escape_string(trim($_POST['password']));

          $sql = mysql_query("SELECT `username`,`password`,`etc` FROM `users` WHERE `username` = '$username' AND `password` = '$password' LIMIT 1");  //Select both at the same time

          if(mysql_num_rows($sql) == 0)
          {
               $loginerror['login'] = "Username or Password incorrect or does not exist.";  //It's smart not to let people know which they got wrong.
          }
          else
          {
               $_SESSION['username'] = $username;
               $_SESSION['loggedin'] = true;
               $loginmessage = 'Welcome ' . $username. ', you are successfully logged in';
          }
      }
 }

loginForm.php
function dispError($name,&$errors)
{
     if(isset($errors[$name]))
     {
          return '' . $errors[$name] . '';
     }
     return '';
}

if(isset($loginmessage))
{
     echo $loginmessage;
}
elseif(isset($_SESSION['username']) && isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true)
{
     echo 'Welcome, ' . $_SESSION['username'];
}
else
{
     if(!isset($loginerror) || !is_array($loginerror))
     {
          $loginerror = array();  //Gotta make sure it exists for the next part if it hasn't been set.
     }
     echo dispError('login',$loginerror);
     echo '<form method="post" action="">';
     echo '<input name="username" placeholder="Username..." type="text" maxlength="15" />' . dispError('username',$loginerror) . '

';
     echo '<input name="password" placeholder="Password..." type="password" maxlength="20" />' . dispError('password',$loginerror) . '

';
     echo '<input name="login" type="submit" value="Login" style="width:100px;">';
     echo '</form>';
}

index.php
if(isset($_POST['login']))
{
     require_once("loginCheck.php");
}

//various other includes and requires

require_once("loginForm.php");

This way there's also no reason to redirect away from the login form/sign in page, as the checks can be easily included inline and both the form and the check can be included on any and all pages dynamically just by dropping it in where necessary.

A: When you validate the user/login set a session variable
$_SESSION['loggedin'] = true;

Then at the very top of each php file add the following code (You can put this code in a php file and use requires('thiscode.php')
<?php
session_start();

if(!loggedIn())
{
    header('Location: login.php');
    die();
}

function loggedIn()
{
    if($_SESSION['loggedin'])
        return true;
    else
        return false;
}
?>

A: You can probably still use the header() function, like this: <?php header("Location: login.php"); ?>
Make sure to add it before your include()s!
If not, post a snip-it of your code here, then I can analyse it.

A: Have you tried using ob_start();  // it makes you able to use headers anytime
make sure to put it on the first line and don't forget to add a ob_end_flush(); at the end
for more information : http://ca2.php.net/manual/en/function.ob-start.php

A:
I have an index.php file with navigation in form of includes only.

....

tons of if-statements

If you really must use a front controller architecture then try to at least make it data driven. You're simultaneously building a house of cards and a stick to beat yourself with.

My problem is redirects! Do I really have to use....

No. Only if the rest of your code is a mess and you want to implement a PRG pattern too. And even then it's not necessary.

Headers are already ruled out because I use includes and requires

Eh? That rather implies that your templating system is a mess.

I'm on the brinck of switching to ASP.NET or

It's not going to make you a better programmer.
You've made a lot of conflicting choices about the architecture of your application and now you're finding that these don't all fit together as easily as you had expected.
Go have a look at some of the excellent PHP CMS and frameworks available - and see how they tackle these problems.


text:
Q: Import Microstation geometry to ArcGIS 10 I have geometry alignments of land parcels defined in MicroStation InRoads V8i. Instead of using the dgn files I want to use the geometry files. I have ArcGIS 10 Desktop advanced license with Data Interoperability extension. InRoads will export to a LandXML file but ArcGIS is not able to read the files - "AdvanceToElement: unable to find xml element.
Does anyone know what process needs to happen in order to utilize these files?
Right now I am creating a separate dgn using the alignments and then bringing those into ArcMap but this is not feasible for the long-term and I want to automate the process of reading the geometry. I will not actually bring the geometry into ArcMap but overwrite current shapes with the Inroad geometry (geometry transfer).
An alternative would be to create shapefiles from the alignment files.
Does anyone know if this is possible?

A: You've tagged data-interoperability. So, if you have data interop installed, you should be able to import the LandXML files. It is listed amongst the supported formats.
If not, I know you can translate LandXML to any ESRI compatible format using FME. It is likely that you will need to do some processing to extract the features in FME or Data Interoperability.


text:
Q: how to expand a divider to the whole window width in flutter app? i have a list separated with dividers but the said dividers don't take the window's width. here is my code :
   Divider(
      color: Colors.black,
      height: 20,
      thickness: 0.5,
      indent: 20,
      endIndent: 0,
    ),

and the picture of the result

A: Change the indent property to 0;
Divider(
      color: Colors.black,
      height: 20,
      thickness: 0.5,
      indent: 0,
      endIndent: 0,
    ),

A: Even you can use Containers like this
Container(
        alignment: Alignment.center,
        width: 450,
        height: 1,
        color: Colors.black
    ),


text:
Q: Horizontal listview inside vertical listview (and scrolling multiple listviews together) I am creating an attendance app and currently am trying to implement a layout as follows for mass viewing of attendance data:
AAA | B | B | B | B | C
-----------------------
DDD | E | E | E | E | F
DDD | E | E | E | E | F

A, B and C are headers (A = Name, B = Date, C = %).  A and C should fixed and should not scroll in either direction.
D, E and F should scroll together vertically (D = name, E = checkbox, F = calculated %).
B and E should scroll together horizontally (B = date, E = checkbox).
Any thoughts on how this could be implemented?
I've search around on SO and through Google, and I haven't found a whole lot of direction on the issue.
I did find a horizontal list scroller library, and I think I can get that into my vertical list adapter, but even if that works out, that would leave me stuck with having the "B"/date header portion repeated on every line or not having it at all.
The only thing I can think of to do is to make the date header a separate horizontal scrolling listview and somehow make it scroll with the attendance data, but I have no idea on where to begin to try that.
Any pointers to tutorials, code or libraries would be appreciated.

A: This can be a tricky concept I would advise to use this structure
 <horizontal ScrolView>
  <scrollview>
  <table layout>

use table layout in place of the list view because list has it's own scroll and it causes trouble when placed in another scrolling widget


text:
Q: Namespace module inside class: instance variable scope I have a class like this. I have Commands defined as a module for internal name-spacing (since it responds to commands from the player and commands will be periodically added and removed). However, methods in Commands cannot see @environments. How do I fix this?
class Player
  attr_accessor :environment

  module Commands
    def self.look *args
      @environment.describe
    end

    def self.exit *args
      Kernel.exit(true)
    end

    def self.method_missing *args
      puts "What?"
    end
  end

  def respond arg
    cmd = arg.split(" ")
    Commands.send(cmd[0], cmd)
  end
end

A: @environment is an instance variable so it's accessed from an instance of Player. Adding self before a method makes it a class method (a static method in other languages) to make the code above work you could do:
class Player
  attr_accessor :environment

  def initialize
    self.extend Commands
  end

  module Commands
    def look *args
      puts @environment.describe
    end
  end

end

player = Player.new
Struct.new("Environment", :describe)
player.environment = Struct::Environment.new("foo")
puts player.look


text:
Q: Too many php session files created on one server We have a web application running multiple instances on different plesk servers. On one server we see quick generation of php session files under /var/lib/php/session directory. Which grows in 100 thousands in short period of time and clean-up of session files causes server load.
On other server we do not see such issue. What possible php (session) setting can cause creation hundreds of session files in seconds. it is looks like on each request to server cause creation of new session file. It does not look like php programatic issue because same application instance is running on other server not causing this issue.
Thank you for your suggestions.


text:
Q: Virtualbox stopped runnuing after new kernal install I am using Vbox on a Ubuntu host to run Arca Noae 503. Currently when starting the virtual machine of Arca Noae, I am getting an error message that the Vbox Linux driver (vboxdrv) is either not loaded or there is a permission problem with /dev/vboxdrv, the Vbox version is 6.0.4 r128413 (qt 5.9.5). The host is Ubuntu 18.04 on kernel 5.3.0-28 loaded on 01/17/20. The install of Vbox ran fine on 01/15/20.  The error message indicates to run /sbin/vboxconfig as root which I have however it fails with the message "vboxdrv.sh: failed: Look at /var/log/vbox-setup.log to find out what went wrong", however I am unable to find in the log what to do differently. The file "vboxdrv.sh" permissions are root and executable. The error message also notes that there are permission problems with /dev/vboxdrv, however I can not find vboxdrv.sh in that path.
Thanks for all of the suggestions. I added Virtualbox to the Debian sources list so that Vbox will update in the future when a new versions is released. I then installed version 6.1 and resolved all of the questions related to guest additions. The new install is working well and resolved all of the issues.

A: Update Virtualbox version (https://www.virtualbox.org/wiki/Downloads) or downgrade kernel version
https://www.virtualbox.org/wiki/Changelog-6.0

VirtualBox 6.0.14 (released October 15 2019): support Linux 5.3

A: Thanks for all of the suggestions. I added Virtualbox to the Debian sources list so that Vbox will update in the future when new versions are is a new relase. I then installed version 6.1 and resolved all of the questions related to guest additions. The new install is working well and resolved all of the issues.


text:
Q: Tools/Tips for integrating existing Java SWT projects into WindowBuilder? Having recently heard about Windowbuilder and its excellent graphical tools, I am looking atways to integrate it into a current SWT project.  I would prefer not to start from scratch, though the project has not entered into production, and theoretically has some wiggle room for integration/refactoring time.
The current project uses gridlayout, formlayout, absolutelayout and columnlayout, and uses multiple shells.  Currently UI code and button code have been abstracted into separate classes, so the UI template class can be used to instantiate multiple different shells in the same program.  It is in the process of being integrated with swt.paperclips.  The future of this app will include serial port communication, likely through serialio's SerialPort.
What are the best tools to use to integrate existing code into Windowbuilder using SWT and Eclipse?  Are there any caveats or gotchas that I need to watch out for?  Are there any tools that allow for creation of reusable UI templates, or am I expected to start from scratch with every layout?

A: The best answer I can give is to download WindowBuilder and try it out.
In my experience, I have found it very capable of parsing my sources and just working with my current SWT code, provided I am using typical SWT, JFace or RCP idioms and not reinventing the wheel.
Aside: I'm the author of PaperClips so I hope you're having a good experience with it.  :-) Be sure to send a note to our Google Groups forum if you have any questions or problems

A: Just found this in the WindowBuilder FAQ:
Can WindowBuilder Pro edit windows that have been created by hand?

Yes.
  Most GUI builders in the world will
  only read and write the code that they
  themselves create. WindowBuilder Pro
  is an exception to that rule. It can
  read and write not only the code it
  creates, but also a great deal of code
  written by hand(>90%). If you come
  across a case that does not work, send
  it to us for analysis. The more broken
  examples that we can "fix", the better
  WindowBuilder Pro will get in the long
  run (and the better chance you will
  have of salvaging your old code
  as-is). Note that dynamic GUI code can
  not be rendered or edited. The problem
  with dynamic code is that it generally
  relies on runtime calculations that
  have no meaning at runtime. Widgets
  created in a loop (where the loop
  parameters are passed in externally)
  are a good example. Widgets created in
  conditionals where the value of the
  conditional is not known until runtime
  are another example. Dynamic GUI code
  constructed from the results of
  complex database queries is yet
  another example.

Since some of my GUIs are dynamically generated, they don't currently import correctly.
I sent a message to one of the developers on the WindowBuilder project, and they indicated that to make UI templates that can be reused for future use, I can choose to implement factories.  In my project, this will require some refactoring, but since there still is more coding to do, I might still save myself time in the long run.


text:
Q: Why method is not running in JavaScript? I just runnung method getNewMessagesLong() in longPolling way:
function getNewMessagesLong() {
    pollingFishingStarts();
    $request = $.ajax({
        type: 'POST',
        url: "listenMessageLong",
        data: lastIncomingMessageLongJson,
        dataType: 'json',
        success: function(data) {
            console.log('Long Fishing ends...');
            pollingFishingEnds();
            }, complete: getNewMessagesLong})
}

but line with pollingFishingEnds() is not running//
and line with console.log() is runnig ok

A: The url you have is listenMessageLong. This doesn't seem correct. If the url is not correct, then the ajax will never succeed and thus the success method will never fire.


text:
Q: Resharper warning code heuristically unreachable I am having below code and wondering why else part is unreachable as per resharper.
private bool SomeMEthod(some parameter)
{
    bool status = false;
    var someCollection = _entity.CustomerPaymentStatus.Where(record => record.CustomerPaymentId == paymentId && record.CurrentRecord == true);
    if (someCollection != null)
    {
        var receivedPayment = someCollection.FirstOrDefault();
        /*some code to save data into DB*/
        status = true;
    }
    else
    {
        //Some code here to log failure scenario

        //here Resharper giving me warning
        //code is heuristically unreachable
    }
    return status;
}

I have checked couple of post but not clear like Code is heuristically unreachable
Any Thought please.

A: .Where() never returns null, but always returns an IEnumerable<T> (or IQueryable<T>. The enumerable might have 0 items, but it's still a non-null enumerable.

A: The Linq Where query will return an empty IEnumerable if no matching records are found, so it is highly unlikly that someCollection will ever be null - although ReSharper does not seem to be completly sure about it.
Also see MSDN Where

A: Assuming _entity is a DbContext, then Where always returns an IQueryable object.
 IQueryable<T> someCollection = _entity.CustomerPaymentStatus.Where(...);

That IQueryable object is never null (otherwise you wouldn't be able to query it).
Testing that object for null doe not execute the query. So
 if (someCollection != null)

is the same as
 if (true)


text:
Q: getting Failed to load resource: the server responded with a status of 415 Extjs and SpringMVC I'm using Extjs4 and SpringMVC in a web application.
I have a view called detail.js which contains a textfiled. (Of course that i have a store, model js (which concerns extjs) and a java model, o DAO, DTO and Service layers ...)
My problem is in my Js controller : i have a button to which i listen to a click event, when it's clicked, the controller launch the following methode :
saveCampagne:function(){
        var form = this.getDetail().getForm(); //here i get my form
        var me = this; //me contains the current controller
        if (form.isValid()) { //test if there is no errors in my form
            form.submit({
                url: 'saveCampagne.aspx',//the action mapped in my java class
                jsonSubmit: true,
                controller: me,
                success: function(form, action) {
                    alert("suuuuuuuceeeeessssss");

                },
                failure: function(form, action) {
                    alert("failure");

                }
            });
        }
    }

In the springMVC side, i have the following method :
@RequestMapping("/saveCampagne")
    @ResponseBody
    public Map<String, Object> handleSaveCampagne(@RequestBody final CampagneDto campagne,final HttpServletRequest request){

        LOGGER.debug("========= Save campagne called ");
        campagneService.insertCampagne(campagne);//calling service layer which calls DAO layer
        return buildJsonResponse(campagne);
    }

But my problem is that when i click on the button, i have the following error and i don't know from where it comes :(
getting Failed to load resource: the server responded with a status of 415  (Type de Support Non Support�)
the sentense between () means some think like "Unsupported media type"
Any help ?
Thanks in advance.

A: Problem solved :)
It was in my DTO. In my DTO a hade a collection, but my Json send a string.
So there is no explicit conversion from string to collection.
What i did is that i redifined my setter, so it will take a string as a parameter and not a collection, then inside the setter code, i set a list of DTO elements that i've created basing on the string reseived.


text:
Q: Deleting comments from a post: NoReverseMatch while trying to delete comment of a post I am quite new to django and web development and trying to delete the comment from posts, and has provided a class based view, but I am getting this error while running the code.
Reverse for 'delete_comment' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<slug>[^/]+)/(?P<comment_id>[0-9]+)/delete/$']

I have provided the comment section below and you can find the delete section towards the last.
comment-section.html
            {{ comments.count }} Comment{{ comments|pluralize }}
        {% for comment in comments %}

{{ comment.user.first_name|capfirst }} {{ comment.user.last_name|capfirst }}

{{ comment.timestamp }}

{{ comment.content }}

 Reply

        {% if request.user == comment.user %}
        Delete
        {% endif %}

views.py
class DeleteCommentView(BSModalDeleteView, LoginRequiredMixin, UserPassesTestMixin):
    model = Comment
    template_name = 'posts/comment_delete.html'
    success_message = 'Deleted'

    def get_success_url(self):
       return reverse_lazy('posts:detail_post')

    def test_func(self, comment_id):
       comment = self.get_object(self.comment_id)
       if self.request.user == comment.user:
         return True
       return False

urls.py
    path('<slug>/<int:comment_id>/delete/', DeleteCommentView.as_view(), name='delete_comment'),

Please do let me know how can I let users delete their comments from the post. It was easier to delete the whole post.
Thanks in advance!

A: It looks like your URL takes two arguments, slug and comment_id, but you are only passing in comment_id when you use the {% url %} tag.
It's not altogether obvious what the slug is since you don't show the model, but assuming it's the post slug, you could perhaps fix this with:
{% url 'posts:delete_comment' comment.post.slug comment.id %}

Probably the better solution however is to have your URL not take the slug at all since the ID is enough to identify it. We can't see the code for BSModalDeleteView but I'm guessing it is only expecting an ID, in which case you might need a new URL just for deleting comments such as:
path(
   "/comments/<int:pk>/delete/",
   DeleteCommentView.as_view(),
   name="delete_comment",
)


text:
Q: launchd uses UDP port 69. Why? Why and what for launchd listens on TFTP port 69?
How to prevent?
$ sudo lsof -nP -i:69
COMMAND PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
launchd   1 root   23u  IPv6 0x55f5dbd8d897c847      0t0  UDP *:69
launchd   1 root   57u  IPv4 0x55f5dbd8d897e687      0t0  UDP *:69
launchd   1 root   59u  IPv6 0x55f5dbd8d897c847      0t0  UDP *:69
launchd   1 root   60u  IPv4 0x55f5dbd8d897e687      0t0  UDP *:69

I think this is a root problem why tftpd cannot listen on port 69 – port is already in use – and exits with status 1.


text:
Q: When to use fit_transform and transform? For stuff like LabelEncoder and the SimpleImputer from scikit-learn why do we use fit_transform for the X_train DataFrame and why do we use transform for the X_valid DataFrame?
eg
for col in object_cols:
    label_X_train[col] = label_encoder.fit_transform(X_train[col])
    label_X_valid[col] = label_encoder.transform(X_valid[col])

What is the difference between the two in terms of how they work?

A: If you want to use the an imputer to fill some missing values in your training data using the median first you need to calculate what that median value is, this is what happens when you call fit().
Now you have the median value but you haven't altered your dataset, to do that you need to change (or transform) your dataset. This is what happens when you call transform(). Often you want to calculate a median value and use that median value to replace NaNs or some other non value, fit_transform() does both of the aforementioned steps in one go for convenience.
When you call fit() your imputer object saves the values that were fit, when you call transform on your test data, this value is use for imputation.
Going in back to your example. You use sklearn.preprocessing.LabelEncoder to convert strings to integers. You call fit() and then transform (or fit_transform()) on your training data to change strings to integers. Now you have your test data and you need to use the same approach to change the strings in your test data to integers, so you use the already fitted LabelEncoder object and only need to call transform() as the object has already been fit (or parameterized) on your training data.

A: label_encoder.fit make the label encoder ready and it has no output. Then you can use by label_encoder.transform(X). However, label_encoder.fit_transform make the encoder ready and then generates the output. In the other words:
label_X_train[col] = label_encoder.fit_transform(X_train[col])

is the same as
label_encoder.fit(X_train[col])
label_X_train[col] = label_encoder.transform(X_train[col])

For the validation dataset, you don't want to fit the label encoder again (because it is already fitted and it is ready), so you just use transform.


text:
Q: List most prevalent values with their corresponding sum I want to get top N most prevalent values of a field in a CSV file
with their sum in another field. How may I do that with awk?
Suppose my file is:
v1,45
v3,20
v2,500
v3,100
v2,200
v1,55
v3,50
v1,10

and I need N=2 most occurring field 1 values with their sum of corresponding field2 values
in this case output would be:
v1,110
v3,170

A:  awk -F, '{a[$1]+=$2;c[$1]++}END{for(k in c)print c[k], k","a[k]}' file|sort -nr|awk 'NR<3&&$0=$2'

it could be solved in one awk, but this is more straightforward. :)
if you want to change your N, just modify the last awk cmd NR<3...

A: In Gnu awk there is an asort function, so you could do
gawk -f a.awk file

where a.awk is:
BEGIN { FS=OFS="," }
{
    a[$1]++
    b[$1]+=$2
}

END {
    for (i in a)
        a[i]=a[i]"\t"i
    n=asort(a)
    for (i=1; i<=n; i++) {
        split(a[i],c,"\t")
        ind[i]=c[2]
    }
    for (i=n; i>n-2; i--)
        print ind[i],b[ind[i]]
}

Output:
v3,170
v1,110


text:
Q: C1083: Cannot open include file: 'GL/gl.h': No such file or directory I was using QtCreator for some time to play with OpenGL, and everything was ok. But finally i needed to attach a debugger to QtCreator, so i have installed windows 7 SDK. From this time i get error:
C:\Qt\5.4\msvc2012_opengl\include\QtGui\qopengl.h:122: error: C1083: Cannot open include file: 'GL/gl.h': No such file or directory

It is a problem only on my office computer, when I work at home everything compiles. So the problem is maybe with compiler?

A: This happened to me today...
For some reason the QT installer defaults to the MSVC 2012 32Bit OpenGL kit instead of the correct (in my case) MSVC 2013 64bBit OpenGL kit.
So I would check if there is a mismatch between the installed kits and your OS and/or MSVC version.
In my case opening the MaintenanceTool.exe (in the Qt dir) selecting Package Manager then uninstalling the "bad" kit and selecting the "good" one solved the issue.
Edit: in the package manager it refers to Prebuilt components, but they show up in Qt Creator as kits...


text:
Q: Ruby: Split string at character, counting from the right side Short version -- How do I do Python rsplit() in ruby?
Longer version -- If I want to split a string into two parts (name, suffix) at the first '.' character, this does the job nicely:
name, suffix = name.split('.', 2)

But if I want to split at the last (rightmost) '.' character, I haven't been able to come up with anything more elegant than this:
idx = name.rindex('.')
name, suffix = name[0..idx-1], name[idx+1..-1] if idx

Note that the original name string may not have a dot at all, in which case name should be untouched and suffix should be nil; it may also have more than one dot, in which case only the bit after the final one should be the suffix.

A: Put on the thinking cap for a while and came up with this regexp:
"what.to.do.now".split(/\.([^.]*)$/)
=> ["what.to.do", "now"]

Or in human terms "split at dot, not followed by another dot, at end of string".  Works nicely also with dotless strings and sequences of dots:
"whattodonow".split(/\.([^.]*)$/)
=> ["whattodonow"]
"what.to.do...now".split(/\.([^.]*)$/)
=> ["what.to.do..", "now"]

A: String#rpartition does just that:
name, match, suffix = name.rpartition('.')

It was introduced in Ruby 1.8.7, so if running an earlier version you can use require 'backports/1.8.7/string/rpartition' for that to work.

A: Here's what I'd actually do:
/(.*)\.(.*)/.match("what.to.do")[1..2]
=> ["what.to", "do"]

or perhaps more conventionally,
s = "what.to.do"

s.match(/(.*)\.(.*)/)[1..2]
=> ["what.to", "do"]

A: If you want the literal version of rsplit, you can do this (this is partly a joke, but actually works well):
"what.to.do".reverse.split('.', 2).map(&:reverse).reverse
=> ["what.to", "do"]

A: if this="what.to.do"  you can do this:
this.split(%r{(.+)\.})

and you'll get back
["", "what.to", "do"]

A: You can also add rsplit to the String class by adding this at the top of your file.
class String
  def rsplit(pattern=nil, limit=nil)
    array = self.split(pattern)
    left = array[0...-limit].join(pattern)
    right_spits = array[-limit..]
    return [left] + right_spits
  end
end

It doesn't quite work like split.
e.g.
$ pry
[1] pry(main)> s = "test.test.test"
=> "test.test.test"
[2] pry(main)> s.split('.', 1)
=> ["test.test.test"]
[3] pry(main)> s.split('.', 2)
=> ["test", "test.test"]
[4] pry(main)> s.split('.', 3)
=> ["test", "test", "test"]

vs.
[6] pry(main)> s
=> "test.test.test"
[7] pry(main)> s.rsplit('.', 1)
=> ["test.test", "test"]
[8] pry(main)> s.rsplit('.', 2)
=> ["test", "test", "test"]

But I can't quite work out how to short split it.


text:
Q: IBOutlet is nil in IBDesignable class I have a custom view class that is supposed to just contain a label. I have an extension in each target that will provide the text that should be displayed in the view, this way I don't have recreate each controller just to have a different label and background color in it.
My custom code is:
@IBDesignable
class HomeAccentView: UIView {

    @IBOutlet weak var nameLabel: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)

        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        setup()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        setup()
    }

    private func setup() {
        backgroundColor = UIColor.main

        nameLabel.text = String.headerText
        nameLabel.textColor = UIColor.white
    }
}

I have my nib's file owner as HomeAccentView and the label is connected as an outlet on the storyboard.
But whenever I try to set the text of the label it's always nil. What am I missing or doing wrong?

A: You did not set class for view. You set only file owner, which means that you told that HomeAccessView is responsible for loading the view, but your code is not showing this. Is there any motive behind this? Otherwise, remove class from file owner and set it for view.


text:
Q: Graph : detect cycle in a cycle You are given an undirected  graph .
It is known that graph will contain few cycles . Give some pointers to detect if we have a cycle which has a smaller cycle with in it .  If yes print out the bigger cycle nodes and smaller cycle nodes
Here 1,2,9,8,6,5,1  has internalls  cycle of 5 3 4 6 5
Assume we have few functions already defined for us . You can leverage them to build over these .
   class graph
{
    private:int n;
        int **a;
        int *reach;
        int *pos;
    public:graph(int k=10);
        void create();
        void dfs();
        void dfs(int v,int label);
        int begin(int v);
        int nextvert(int v);
};

A: Create a list of cycles and hash of nodes with no of nodes
so cycle A ... contains 4 nodes and hashed Q,W,E,R
cycle B ... contains 5 nodes and hashed W,E,R,A,S
now search for cycles with common nodes ... if you find then you have some cycles with common edges


text:
Q: USB ports get disabled by hub due to EMI? I am seeing the following message in the Linux kernel log:
usb usb1-port5: disabled by hub (EMI?), re-enabling...

After that USB devices are disconnected. In some cases they reconnect immediately, in other cases they don't. In the latter cases, I also see:
usb usb1-port5: Cannot enable. Maybe the USB cable is bad?

What causes these issues and how to avoid the bad effects?
In this particular case, a wireless USB stick is connected directly to a USB port. The issue does not correlate to a particular time of day. Using a different USB port makes no difference. Using a different wireless USB stick makes no difference. Using a different mainboard makes a difference. Disconnecting other USB devices makes no difference.
Even though presenting details here, answer can and should try to cover more settings to be useful to others.

A: I don't understand why. Physically moving the wireless USB stick from the mainboard by connecting it to an external USB hub connected with a 2 meter cable made the disconnect problems go away.


text:
Q: How to enable different voices (and languages) for TextToSpeech I'm trying to create a simple TextToSpeech app that speaks portuguese (pt_BR).
The default Locale Android reference does not include pt_BR, so I created it:
public Locale pt_BR = new Locale("pt", "BR");
...

public void onInit(int initStatus) {
    tts.setLanguage(pt_BR);
}

and it works, but with a very "robotic" voice, not smooth at all. Is it possible to download (or even buy) different voices for specific languages? (not an app, but the voice itself, so that I can include the voice as a TextToSpeech in my app Project).
Thanks!

A: Yes. there are few good TTS engines available whihc you can use. They have free versions as well as paid versions which have added features.
Nuance Engine is good. It has both TTS and VRS (Voice recognization system). Also you can check iSpeech.
But i felt Nuance is better. both have free versions. you can easily integrate and check.