text:
Q: Fatal error in dictionary - Index out of range / Swift I have a txt text file. The text file contains the text attached to each date.
Example:

30.10.2022 : Hello Stack Overflow.

31.10.2022 : Hello programmers.

01.11.2022 : We are the best.

02.11.2022 : Swift, is the best programming language.

etc…
I need to bind each sentence to date and show only the sentence that corresponds to today's date.
Example:

If today is 30.10.2022 - show in textView only the result: Hello Stack Overflow. And the same for every day... If the date changes from 30.10.2022 to 31.10.2022, we will see the result in textView - Hello programmers!

I tried to split my text from file text to dictionary and got an error - Swift/ContiguousArrayBuffer.swift:575: Fatal error: Index out of range.
I want to note that yesterday everything was working, but today it is not working, despite the fact that I did not change the code. Got confused. I can't understand what I missed.
Code with error...

import Foundation

class NameDaysModel {

private var dataArray: [String] = []

func loadDictionary() -> Dictionary<String, String> {

    let pathToFile = Bundle.main.path(forResource: "NameDays", ofType: "txt")

    if let path = pathToFile {
        let countriesString = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
        dataArray = countriesString.components(separatedBy: "\n")
    }

    var dictionary = [String: String]()
    for line in dataArray {
        let components = line.components(separatedBy: " : ")
        dictionary[components[0]] = components[1] // = Thread 1: Fatal error: Index out of range
    }

    return dictionary
}

private func getDate() -> String {

    let date = NSDate()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd.MM.yyyy"
    let str = dateFormatter.string(from: date as Date)
    return str
}

func getNameDay() -> String {
    let date = getDate()
    let nameDays = loadDictionary()
    return nameDays["\(date)"] ?? ""
}
}

A: Based on the error you're getting, it sounds like some of the lines in your text file don't contain the string " : ". In that case your components array from the line let components = line.components(separatedBy: " : ") would only contain 1 element: The entire line of text.
You need to either make sure your data always contains a " : " in every line or add checking code that makes sure each value of components contains at least 2 elements before attempting to index into components[1].


text:
Q: cva.glmnet() lambda value does not give correct number of non-zero predictors in glmnet() I have an issue with specifying the lambda value based on cva.glmnet().

The lowest "binomial deviance" was attained in my data with alpha = 1 and lambda = 0.04126. It said that there were 43 predictors that were non-zero.

After this, I used glmnet() to create a list of the non-zero predictors, but I only got 27 of them.

I have the predictors set as factors with 3 levels. I made sure that they were input as factors in cva.glmnet() using do.call(), and I used that same data through do.call() in glmnet().
Does anyone know why using this value of lambda is not getting me the "correct" number of predictors? Is the data not being passed as a data.frame in either of the functions? Are some factor levels being counted as multiple predictors?
Any help is appreciated. Thank you!

A: I was able to figure this out.
cva.glmnet() does create dummy variables automatically, it seems. However, glmnet() does not.
So, I needed to use the acm.disjonctif() function from the ade4 package to create dummy variables for my predictors to put into the glmnet() function. This gave me 43 non-zero predictors, matching cva.glmnet().

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I specify disk size for new machine instance for Azure? I want to create a new NC6 instance (for my GPU and ML works). Few days ago I created my first instance for the NC6 instance, it was 150 GB standard SSD one, it was too much for me, so I tried to change the disk to low price one, but I noticed you cannot shrink or swap/change the disk to reduced size one or HDD one. So, I ended up deleting the instance and now trying to create a new one, but here, seems there is no way to change disk size, it seems you can change "OS disk type" to SSD to HDD, but no disk size e.g. 150 GB to 32 GB. So, How do I specify disk size for new machine instance for Azure? Thanks.

A: Unfortunately you cannot change or specify your instance's disk size on Azure. The disk size for the OS disk is depends on the VM image.
https://docs.microsoft.com/en-US/troubleshoot/azure/virtual-machines/default-size-images-changed-30-gb


text:
Q: very simple java cms can any one suggest me a very very simple java cms.I have seen cms like opencms but they are very dificult to understand.
I want a light weighted cms with very minimum features

A: ZCMS is your Answer. It´s a simple and lightning-fast Java CMS less than 2Mb.
http://code.google.com/p/zencherry-cms/downloads/list
Also have a look on Liferay. Basically its a portal but a very good for CMS also.

A: Check List of content management systems

A: Have a look at JeaseCMS. It's very easy to install, to use and to customize:
http://www.jease.org/


text: Q: What would be the combined dielectric constant of two dielectrics in series? Let's say we have two parallel conductor plates. In the middle, there is not one but two layers of dielectrics made of different materials. If we know the relative permittivity of each dielectric, how could we couple it to get a single dielectric constant?


text:
Q: parameter pendingDynamicLinkData specified as non-null is null private fun getReferralId() {
    Firebase.dynamicLinks
        .getDynamicLink(intent)
        .addOnSuccessListener(this) { pendingDynamicLinkData ->
            pendingDynamicLinkData?.link?.getQueryParameter(
                DEEP_LINK_QUERY_PARAM_REFERRAL_ID
            )?.let { refId ->
                viewModel.saveReferralId(refId)
            }
        }
}

java.lang.NullPointerException: Parameter specified as non-null is
null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter,
parameter pendingDynamicLinkData
at app.package.activity.MainActivity.getReferralId$lambda-2(Unknown
Source:7)
at app.package.activity.MainActivity.$r8$lambda$ANLS0uCuXrQe7RFQ5b0C-RFsBKE(Unknown
Source:0)
at app.package.activity.MainActivity$$ExternalSyntheticLambda3.onSuccess(Unknown
Source:4)

version:
implementation platform("com.google.firebase:firebase-bom:28.3.1")
implementation "com.google.firebase:firebase-dynamic-links-ktx"

What is wrong here?
UPDATE
It happens when I update version of play-services-auth libs
implementation "com.google.android.gms:play-services-auth:19.2.0"
implementation "com.google.android.gms:play-services-auth-api-phone:17.5.1"

to newest version
implementation "com.google.android.gms:play-services-auth:20.0.0"
implementation "com.google.android.gms:play-services-auth-api-phone:18.0.0"

How is that even related?

A: it's a bug in the library due to a play services update. To fix it, you should explicitly declare that the pendingDynamicLinkData is nullable.
Like this:
private fun getReferralId() {
    Firebase.dynamicLinks
        .getDynamicLink(intent)
        .addOnSuccessListener(this) { pendingDynamicLinkData: PendingDynamicLinkData? ->
            pendingDynamicLinkData?.link?.getQueryParameter(
                DEEP_LINK_QUERY_PARAM_REFERRAL_ID
            )?.let { refId ->
                viewModel.saveReferralId(refId)
            }
        }
 }

A: Complement to @brwngrldev's answer.
Update
The problem was fixed in a recent version of play services library (https://developers.google.com/android/guides/releases#january_05_2022)
Check what dependencies you have in your project, and update them to the version listed in "Artifacts released on maven.google.com".
For example, in the case of the question's issue, the following dependencies need to be updated:
implementation "com.google.android.gms:play-services-auth:20.0.1"
implementation "com.google.android.gms:play-services-auth-api-phone:18.0.1"

OLD ANSWER
The bug was fixed in play-services-base version (https://developers.google.com/android/guides/releases#december_16_2021)
If you do not wish to explicitly set the field to nullable, you can update the  play-services library by adding these two lines to your app's build.gradle.
implementation 'com.google.android.gms:play-services-base:18.0.1'
implementation 'com.google.android.gms:play-services-tasks:18.0.1'

Credits: https://github.com/firebase/firebase-android-sdk/issues/2992#issuecomment-1001847825


text:
Q: Store settings of qt application using QSettings Hello I have created an application using qt and I managed to save some of its settings using QSettings.
void DoneIt::writeSettings()
{
    QSettings settings("mycompany", "RightDoneIt");
    settings.beginGroup("DoneIt");
    settings.setValue("size", size());
    settings.setValue("pos", pos());
    settings.endGroup();
}

void DoneIt::readSettings()
{
    QSettings settings("mycompany", "RightDoneIt");
    settings.beginGroup("DoneIT");
    resize(settings.value("size", QSize(400, 400)).toSize());
    move(settings.value("pos", QPoint(200, 200)).toPoint());
    settings.endGroup();
}

That works fine with the window position and size.
I have add some widgets in my application using the designer of qt and I would like to save their state too.
One of my widgets is a radio button and I call it radioButtonbnw
How can I save its state (checked or unchecked) ?
What are the best practises ?

A: *

*Put them to QButtonGroup.

*Use QButtonGroup::setId to set Id for each radio button in this group.

*Save the Id of the checked button get by QButtonGroup::checkedId.

*Get the pointer of this button using QButtonGroup::button(id) when restore, and call QAbstractButton::setChecked.

BTW: if you want to saves the current state of mainwindow's toolbars and dockwidgets, use QMainWindow::saveState.

A: Here an example widget with three QRadioButton
settingspane.h
#ifndef SETTINGSPANE_H
#define SETTINGSPANE_H

#include <QWidget>
#include <QSettings>

class SettingsPane
      : public QWidget
{
    Q_OBJECT

    QSettings *settings;

public:
    explicit SettingsPane(QWidget *parent = nullptr);

public slots:
    void handle_rb_buttonReleased(int id);
};

#endif // SETTINGSPANE_H

settingspane.cpp
#include "settingspane.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QRadioButton>
#include <QButtonGroup>

SettingsPane::SettingsPane(QWidget *parent)
   : QWidget(parent)
{
    settings = new QSettings();

    auto mlayout = new QVBoxLayout();
    setLayout(mlayout);

    // create some buttons
    auto rb_frst = new QRadioButton("first");
    auto rb_scnd = new QRadioButton("second");
    auto rb_thrd = new QRadioButton("third");
    // container to organize groups of buttons (no visual)
    auto buttonGroup = new QButtonGroup();
    buttonGroup->addButton(rb_frst,0);
    buttonGroup->addButton(rb_scnd,1);
    buttonGroup->addButton(rb_thrd,2);
    // layout buttons for visual representation
    auto rb_layout = new QHBoxLayout();
    rb_layout->addWidget(rb_frst);
    rb_layout->addWidget(rb_scnd);
    rb_layout->addWidget(rb_thrd);
    mlayout->addLayout(rb_layout);

    // use Functor-Based Connection due to overloaded buttonReleased
    connect( buttonGroup,
             SIGNAL(buttonReleased(int)),
             this,
             SLOT(handle_rb_buttonReleased(int)));

    // restore button from settings
    int id = settings->value("buttonGroup").toInt();
    buttonGroup->button(id)->setChecked(true);
}

void
SettingsPane::handle_rb_buttonReleased(int id)
{
    // save new status to the settings
    settings->setValue("buttonGroup", id);
}

Using this in a MainWindow
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow
      : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
};

#endif // MAINWINDOW_H

mainwindow.cpp
#include "mainwindow.h"
#include "settingspane.h"

#include <QTabWidget>

MainWindow::MainWindow(QWidget *parent)
   : QMainWindow(parent)
{
    auto cwidget = new QTabWidget();
    setCentralWidget(cwidget);

    auto settingsPane = new SettingsPane();
    cwidget->addTab(settingsPane,"Settings");
}

main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

results in:


text:
Q: Is it possible to find a cross-domain iframe's new URL after a redirect? I'm trying to post to the login form of an application on another subdomain of my site. It's a third party app that I don't have source access to.
I know that you can't access most features of a cross-domain iframe because of same origin policy. All I need to access, however, is the URL that's been redirected to (via JavaScript) within the iframe. It has a session token that I want to pass through.
That seems like something that might be safe enough to be allowed, but I haven't found a way to do it yet. I'm using jQuery, and I've tried $('iframe').contents(), but I seem to have no permissions at all on that object. I've also checked $('iframe').attr('src'), but it remains as the pre-redirect URL. Is there another way?

A: Try this example (method 2) in which the author sets up another iframe inside the first, loading a page at the original domain.
The inner page is allowed to call javascript on the outer parent, since they are loaded in the same domain.
Simply load the inner page with appropriate parameters, which can be passed on to the parent.

A: No, you don't have access to any properties within an iframe.  You only have access to the outer positioning and styling properties.
This is why frames are such a pain to work with.  I usually only use them if I don't care what is done within them.
Can you not do a server-side authentication and token passing?  Instead of having the client do the authentication, can you not do that on your server?  You may need to do some extra work to create the HTTP request and parse the response, but you avoid any iframe issues.
Bottom line is iframes probably aren't the best to rely on(especially when it comes to cross-browser functionality) for important things like authentication.


text:
Q: Strange Texture array buffer limitations Within a WebGl fragment shader I'm using a texture generated from an array of 32bit values but it yields errors when going above a resolution of 7000x7000px this is far below the maximum texture resolution for my gpu 16384x16384px. gl.Unsigned works without issue at higher resolutions but not so when changed to gl.float .  Is this a known limitation when dealing with floats? Are there work arounds? any input much appreciated.
my texture parameters -
"gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, 8192, 8192, 0, gl.ALPHA, gl.FLOAT, Z_pixels)"

A: 7000*7000*32 bits per float*4 ~= 784 megabytes of memory. Perhaps that exceeded your graphic card memory capacity?
As per MSDN https://msdn.microsoft.com/en-us/library/dn302435(v=vs.85).aspx says "[gl.FLOAT] creates 128 bit-per-pixel textures instead of 32 bit-per-pixel for the image." so its possible that gl.ALPHA will still use 128 bits per pixel.


text:
Q: Capture microphone in IE10 I need to capture microphone audio in IE10. So far I have two semi-working solutions:

*

*getUserMedia from Microsoft's experimental WebRTC plugin:
http://www.html5labs.com/prototypes/media-capture-api-(2nd-updated)/media-capture-api-(2nd-update)/info
The issue with this is that while I can capture and replay the audio in the browser, I cannot send the audio to the server. In particular, it is not clear how to extract the audio data from the "blob" object:
function msStopRecordCallback(blob) {
      console.log(blob) // outputs {}
      console.dir(blob) // outputs {}

      playMediaObject.Play(blob); // This works!

}

*jRecorder: http://www.sajithmr.me/jrecorder-jquery The issue with this is that it relies on Flash to capture the audio, which is something I would like to avoid.
Are there any other ways to capture audio in IE10?

A: I recognize that my answer a bit late, but...
You may upload a blob to a server as following (Javascript):
function saveBlob(blob)
{
   var uploader = new CustomXMLHttpRequest();
   uploader.onpartreceived = function (response)
   {
     // TODO: handle the server response here
   };

   var base = window.location.toString();
   var uploadService = base.substr(0, base.lastIndexOf("/")) + "/api/upload";

   uploader.open("POST", uploadService, true);

   uploader.responseType = "text";

   var form = new FormData();
   form.append("fname", blob, "audio.wav");

   uploader.send(form);
}

On the server side, you may treat this blob as a file attachment, e.g. (C#):
public class UploadController : ApiController
{
   public async Task<HttpResponseMessage> PostFile()
   {
      // Check if the request contains multipart/form-data.
      if (!Request.Content.IsMimeMultipartContent())
      {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
      }

      var root = HttpContext.Current.Server.MapPath("~/App_Data");
      var provider = new MultipartFormDataStreamProvider(root);

      try
      {
        // Read the form data and return an async task.
        await Request.Content.ReadAsMultipartAsync(provider);

        var fileName = "";

        // get the uploaded files.
        foreach (var data in provider.FileData)
        {
          var file = new FileInfo(data.LocalFileName);

          // TODO: handle received file here
        }

        if (string.IsNullOrEmpty(fileName))
        {
          return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        return Request.CreateResponse(HttpStatusCode.OK);
      }
      catch (System.Exception e)
      {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
      }
  }
}

Hope this will help.


text:
Q: Infinite loop in Go I want to have the "for loop" to loop 3 times or until the user inputs something other than an integer. Below is my code, although this runs an infinite amount of times and prints out the first value the user enters.
package main

import "fmt"
import "bufio"
import "strconv"
import "os"
import "sort"

func main(){
    emptySlice := make([]int, 3) // Capacity of 3
    fmt.Println(cap(emptySlice))
    scanner := bufio.NewScanner(os.Stdin) // Creating scanner object
    fmt.Printf("Please enter a number: ")
    scanner.Scan() // Will always scan in a string regardless if its a number

    for i := 0; i < cap(emptySlice); i++ { // Should this not run 3 times?
            input, err := strconv.ParseInt(scanner.Text(), 10, 16)
                    if err != nil{
                        fmt.Println("Not a valid entry! Ending program")
                        break
                    }
                emptySlice = append(emptySlice, int(input)) // adds input to the slice
                sort.Ints(emptySlice) // sorts the slice
                fmt.Println(emptySlice) // Prints the slice
    }

}

A: I think there are a couple of minor bugs, but this version should work correctly:
package main

import "fmt"
import "bufio"
import "strconv"
import "os"
import "sort"

func main() {
    emptySlice := make([]int, 3) // Capacity of 3
    fmt.Println(cap(emptySlice))
    scanner := bufio.NewScanner(os.Stdin) // Creating scanner object

    for i := 0; i < cap(emptySlice); i++ { // Should this not run 3 times?
        fmt.Printf("Please enter a number: ")
        scanner.Scan() // Will always scan in a string regardless if its a number

        input, err := strconv.ParseInt(scanner.Text(), 10, 16)
        if err != nil {
            fmt.Println("Not a valid entry! Ending program")
            break
        }
        // emptySlice = append(emptySlice, int(input)) // adds input to the slice
        emptySlice[i] = int(input)
    }

    sort.Ints(emptySlice)   // sorts the slice
    fmt.Println(emptySlice) // Prints the slice

}

I've moved the prompt into the loop, and I've replaced the append call with a direct assignment to the previously allocated slice entries. Otherwise calling append will just increase the size of the slice.
I've moved the sort and the print outside of the loop, as these seemed to be incorrectly placed too.

A: The program in the question starts with cap(emptySlice) == 3. Given that each complete iteration of the loop appends a new value to empty slice, we know that cap(emptySlice) >= 3 + i.  It follows that the loop does not terminate.
My homework assignment is slightly different: Read up to three integers and print them in sorted order. Here's how I did it:
func main() {
    var result []int
    scanner := bufio.NewScanner(os.Stdin)
    for i := 0; i < 3; i++ {
        fmt.Printf("Please enter a number: ")
        if !scanner.Scan() {
            // Exit on EOF or other errors.
            break
        }

        n, err := strconv.Atoi(scanner.Text())
        if err != nil {
            // Exit on bad input.
            fmt.Println(err)
            break
        }
        result = append(result, n)
    }

    sort.Ints(result)
    fmt.Println(result)
}


text:
Q: WebChromeClient.FileChooserParams of onShowFileChooser cannot be resolved to a type I overwrote the method onShowFileChooser (WebView, ValueCallback, WebChromeClient.FileChooserParams) in the setWebChromeClient() of my activity, which implements a WebView, but eclipse gives me the "cannot be resolved to a type" error on the WebChromeClient.FileChooserParams parameter.
How can I fix it?
myWebView.setWebChromeClient(new WebChromeClient() {
        public void openFileChooser(ValueCallback<Uri> filePathCallback) {
            mFilePathCallback4 = filePathCallback;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
            startActivityForResult(
                    Intent.createChooser(intent, "File Chooser"),
                    REQUEST_FILE_PICKER);
        }

        public void openFileChooser(ValueCallback filePathCallback,
                String acceptType) {
            mFilePathCallback4 = filePathCallback;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
            startActivityForResult(
                    Intent.createChooser(intent, "File Chooser"),
                    REQUEST_FILE_PICKER);
        }

        public void openFileChooser(ValueCallback<Uri> filePathCallback,
                String acceptType, String capture) {
            mFilePathCallback4 = filePathCallback;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
            startActivityForResult(
                    Intent.createChooser(intent, "File Chooser"),
                    REQUEST_FILE_PICKER);
        }

        @Override
        public boolean onShowFileChooser(WebView webView,
                ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            mFilePathCallback5 = filePathCallback;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
            startActivityForResult(
                    Intent.createChooser(intent, "File Chooser"),
                    REQUEST_FILE_PICKER);
            return true;
        }

        public void onProgressChanged(WebView view, int progress) {
            // Make the bar disappear after URL is loaded, and changes
            // string to Loading...
            MyActivity.setTitle("Loading...");
            MyActivity.setProgress(progress * 100); // Make the bar
                                                    // disappear after URL
                                                    // is loaded

            // Return the app name after finish loading
            if (progress == 100)
                MyActivity.setTitle(R.string.app_name);
        }
    });

A: Please try updating your SDK to Android 5.0.


text:
Q: SSMS table properties show an exception for Index space on every table When getting table properties from a SQL 2014 server (12.0.4449) using SSMS 2014 (12.0.4100) or 2016 (13.0.15600) on any database or table I get the following text for the "Index space" property on the Storage tab:

An exception occurred while executing a Transact-SQL statement or
  batch.

This is the error:

A: Like Haris commented, it's likely an SSMS bug that Microsoft will have to resolve. But you should be able to run a trace or an Extended Event session to capture the TSQL that SSMS is using to get the data that you are after. Capture the TSQL and then run that in a query window. Or use the query from marc_s.

A: If possible, try to have your permissions level upgraded to db_owner, it can solve the issue.
That also explains why a co-worker with the same setup would be able to see the property but you don't.
But indeed, sp_spaceused should work without the extra permissions. Use with
sp_spaceused N'database_name.schema_name.table_name'


text:
Q: Changing bibliography style I am writing my CV using markdown and want to have multiple bibliography sections (one for journal articles, another for book chapters etc). I'm using the RefManagerR package to do this and it works nicely.
library("RefManageR")
BIB <- structure(list(structure(list(title = "Quantitative palaeotemperature records inferred from fossil pollen and chironomid assemblages from Lake Gilltjarnen, northern central Sweden", author = structure(list(structure(list(given = "K", family = "Antonsson", role = NULL, email = NULL, comment = NULL), .Names = c("given", "family", "role", "email", "comment")), structure(list(given = "SJ", family = "Brooks", role = NULL, email = NULL, comment = NULL), .Names = c("given", "family", "role", "email", "comment")), structure(list(given = "H", family = "Seppa", role = NULL, email = NULL, comment = NULL), .Names = c("given", "family", "role", "email", "comment"))), class = "person"), journal = "Journal of Quaternary Science", year = "2006", number = "8", pages = "831-841", volume = "21"), .Names = c("title", "author", "journal", "year", "number", "pages", "volume"), bibtype = "Article", key = "RID:0428130725771-5", dateobj = structure(1136070000, class = c("POSIXct", "POSIXt"), tzone = "", day.mon = 0L))), strings = structure(character(0), .Names = character(0)), class = c("BibEntry", "bibentry"))

NoCite(BIB)
PrintBibliography(BIB, .opts = list(style = "latex", bib.style = "authoryear",
                                    sorting = "ydnt"))

Which is rendered in the pdf as

Antonsson, K, S. Brooks and H. Seppa (2006). "Quantitative palaeotemperature records inferred from fossil pollen and chironomid assemblages from Lake Gilltjarnen, northern central Sweden". In: Journal of Quaternary Science 21.8, pp. 831-841.

I want to change the style of the reference. Basically, I want to remove the quote marks and the In:, and put initials after the name. I understand that the style is set using tools::bibstyle and that I need to make a routine called formatArticle but the example for tools::bibstyle only shows how to change the sort order and I cannot work out how to see the default JSS style.
Please can someone show me how to use bibstyle.
Alternatively, please can someone show me how to make multiple bibliography sections in a single document using the bibliography generator built into rmarkdown, so I can use a csl file.

A: Answering only the part about bibliography in multiple sections:
If you want to do it "using the bibliography generator built into rmarkdown", you will need to change the the latex template used for generating the pdf from the Rmarkdown file. Set the template at the YAML section with something like:
output:
  pdf_document:
    template: mytemplate.tex

There are references on how to work with templates.
An easier approach would be to add the multiple sections in the RMarkdown file itself, and print out the bibs. Example of an .Rmd file:
---
title: "2 bibs"
output: pdf_document
---

```{r init, echo=FALSE}
library("RefManageR")

## loading some bib entries from example file
file <- system.file("Bib", "biblatexExamples.bib", package = "RefManageR")
BibOptions(check.entries = FALSE)
bib <- ReadBib(file)

## Gerating the entries for the 2 sections
bib1 = bib[[5:6]]
bib2 = bib[[7:8]]
```

Intro text.

# Bib 1

```{r, results='asis', echo=FALSE}
NoCite(bib1)
PrintBibliography(bib1, .opts = list(style = "markdown", bib.style = "authoryear", sorting = "ydnt"))
```

# Bib 2

```{r, results='asis', echo=FALSE}
NoCite(bib2)
PrintBibliography(bib2, .opts = list(style = "markdown", bib.style = "authoryear", sorting = "ydnt"))
```


text:
Q: Get width of a single character from ttf-font in php? I'm creating an dynamic image, which creates headers on my page using PHPs GD-library. The problem is, that I need a line-wrapping system. It's not a problem itself, but first I need to get the width (in pixels) of current character.
I'm pretty curious about this, is there any way? Or do I need to manually specify width of every abc?
Martti Laine

A: You would have to do a imagettfbbox() on each single character.
Untested but should work:
$string = "Lorem Ipsum";
$size = 20;
$angle = 0;
$fontfile = "ARIAL.TTF";

$strlen = strlen($string);
for ($i = 0; $i < $strlen; $i++)
 {
    $dimensions = imagettfbbox($size, $angle, $fontfile, $string[$i]);
    echo "Width of ".$string[$i]." is ".$dimensions[2]."<br>";

 }

A: If you print the results of
$string = "Lorem Ipsum";
$size = 20;
$angle = 0;
$fontfile = "./fonts/arial.ttf";

$dimensions = imagettfbbox($size, $angle, $fontfile, $string);
print_r($dimensions);

you might get something` like:
Array
(
    [0] => -1
    [1] => 5
    [2] => 152
    [3] => 5
    [4] => 152
    [5] => -20
    [6] => -1
    [7] => -20
)

where each index is:
0   lower left corner, X position
1   lower left corner, Y position
2   lower right corner, X position
3   lower right corner, Y position
4   upper right corner, X position
5   upper right corner, Y position
6   upper left corner, X position
7   upper left corner, Y position

So the width should be index 2 - index 0. I dont quite get the minus 1 for index 0.
It is a bit odd that if you sum the total of each char in the string the results is 130 not 153.


text:
Q: Twilio API - Can't assign phone number to Messaging Service I'm trying to assign a newly created phone number to an existing Messaging Service from the Twilio API.
Here's my code so far:
Creating the Messaging Service
$createService = $twilio->messaging->v1->services
  ->create([
    "friendlyName" => "Service",
    "inboundRequestUrl" => "https://example.com/folder/file.php"
  ]
);

$messagingServiceId = $createService->sid;

Creating the phone number and assigning to the Messaging Service
$smsNumber = $_POST["smsNumber"];

$addPhoneNumber = $twilio->incomingPhoneNumbers
  ->create([
    "phoneNumber" => $smsNumber,
    "smsApplicationSid" => $messagingServiceId
  ]
);

With the previous code, I'm able Messaging Service is created, the phone number is added to the account but it is not assigned to the Messaging Service.
What am I missing here?
Thanks for your help.

A: Look at the Create A Phone Number code example for the PhoneNumber Resource.
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Find your Account Sid and Auth Token at twilio.com/console
// DANGER! This is insecure. See http://twil.io/secure
$sid    = "ACCOUNT_SID";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$phone_number = $twilio->messaging->v1->services("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                      ->phoneNumbers
                                      ->create("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // phoneNumberSid
                                      );

print($phone_number->sid);


text:
Q: Login repeats after authenticate, if i try to send a friends request Im trying to build a 'cheer action' for my app. It is a game in iPhone, so I want to post a 'welcome message' in the users wall (I will need 'public_stream' permission) and then invite his friends to visit my webpage.
Here my question.. I authenticate the user using:
_url = "http://www.facebook.com/dialog/oauth/?client_id=" + app_id + "&redirect_uri=" + app_net_folder + auth_response_uri + "&state=" + session_id;

I get response in my uri, and then I get the access_token, user_id, etc.
Then I post a message in his wall in this way:
_url = "https://www.facebook.com/dialog/apprequests?app_id=" + app_id;
_url += "&message=" + string_ToUrl(String_ToHTML(request_msg));

Now I want to invite his friends (using a multi friend list dialog). To do it, I can only use JavaScript FB.ui. In this way:
FB.init({appId  : app_id,   logging : false, frictionlessRequests: true, oauth : true});

FB.ui({method: 'apprequests', message: msg, title: title}, requestCallback);

When I do it, a window is opened asking me again for the user's login.. but my user has been already authenthicated. So I dont know how to say to FB in JavaScript that my user has been alredy authenthicated! (I even have the access_token, but I don't know how to use it in JavaScript functions).
Someone knows what am I doing wrong? or how to do those two actions asking just one time for the user's login?
Thanks!!

A: if you are already log in, you can get login user id using below code
var userId = FB.Facebook.apiClient.get_session().uid;
if(userId > 0 || userId != '')
{
  alert('user is already log in');
}

hope it's helpful to you


text:
Q: Styling Separator in WPF to match background I have a background with a custom color for a ContextMenu.  I added in a separator as so (between different menu items):
<Separator Background="#EDECEC" Margin="0" ></Separator>

The background color is #edecec.  However, I see a separator, and the color doesn't match the rest of the contextmenu.  It is lighter than the contextmenu.  Is there a way to change that? Thanks.

A: The Separator in menus has a default Template which ignores the Background, to override it add a respective style to some ancestor's Resources using the right key:
<Style x:Key="{x:Static MenuItem.SeparatorStyleKey}"
       TargetType="{x:Type Separator}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Separator}">
                <!-- ControlTemplate with a TemplateBinding to Background here -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: VSCode folder structure
I want to change the folder structure.. if you see in the folder "utils" i have another folder called "mocks" well.. what i want is change the structure to see 1 folder by folder.. something like this

Like the "services" folder which have just a 1 file.. i have the same structure, 1 folder inside another and 1 file but in the structure i see 1 folder in the same line. I don't know if i explained me

A: In VS Code we have a Setting called Compact File Structure.
If that setting is On then we Compact the structure.
How to turn it off?

*

*Go to settings

*Search for: Compact File

*Uncheck The compact file structure

*Save the file

Done.

A: This is a setting: explorer.compactFolders.
More info here: Compact folders in Explorer.

In the File Explorer, we now render single child folders in a compact form. In such a form, single child folders will be compressed in a combined tree element. Useful for Java package structures, for example.
Setting explorer.compactFolders controls this behavior. By default, this setting is turned on.


text:
Q: NSTask failed 22 terminating temporary process cocoa Using below code, I am getting this error:
NSTask: Task create for path '/Users/media/Library/Developer/Xcode/DerivedData/Manager-gnixeptcszdoubbnfcncumzypwge/Build/Products/Debug/lib' failed: 22, "Invalid argument".  Terminating temporary process.

I am not getting whats the issue behind this.
- (void)startProcessingVideo {

     NSLog(@"Processing Video Low Resolution");

    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    // NSTimeInterval is defined as double
    NSNumber *timeStampObj = [NSNumber numberWithInt:timeStamp];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterNoStyle];

    NSString *convertNumber = [formatter stringForObjectValue:timeStampObj];

    NSLog(@"timeStampObj:: %@", convertNumber);

    NSString *fileNameNumber = [convertNumber stringByAppendingString:[self genRandStringLength:8]];

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

    NSString *aString = [[NSString stringWithFormat:@"%@%@%@", thumbnailDirPath,@"/Mobile" ,fileNameNumber] retain];

    //NSString *string = [aString stringByAppendingString:@"_H"];

    fileNameMP4Mobile = [aString stringByAppendingString:@".mp4"];

    NSLog(@"string:::: %@", aString);

    [lblMessage setStringValue:@"Started!"];
    NSTask *task= [NSTask new];
    [task setLaunchPath:ffmpegPresetLaunchPath];
    [task setArguments:[NSArray arrayWithObjects:
                        @"-y",
                        @"-i",
                        inputFilePath,// @"1.wmv",
                        @"-vcodec",
                        @"libx264",
                        @"-fpre",
                        @"libx264-fast.ffpreset",
                        @"-b",
                        @"500k",
                        @"-s",
                        @"640*480",
                        @"-r",
                        @"30",
                        @"-aspect",
                        @"16:9",
                        @"-ab",
                        @"128k",
                        @"-ac",
                        @"2",
                        @"-ar",
                        @"44100",
                        fileNameMP4Mobile,nil]];
    [task setCurrentDirectoryPath:thumbnailDirPath];

    NSPipe *outputPipe = [NSPipe pipe];
    [task setStandardInput:[NSPipe pipe]];
    [task setStandardOutput:outputPipe];

    [task launch];
    [task waitUntilExit];
    [task release];

    NSData *outputData = [[outputPipe fileHandleForReading] readDataToEndOfFile];
    NSString *outputString = [[[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding] autorelease];
    [lblMessage setStringValue:@"Video Generated!"];

    [self startProcessingVideoHighResolution];
}

value for ffmpegPresetLaunchPath is:
ffmpegPresetLaunchPath = [[NSString stringWithFormat:@"%@%@", currentDir, @"/lib/"] retain];

Value in NSLOG:
ffmpegPresetLaunchPath::: /Users/media/Library/Developer/Xcode/DerivedData/FileManager-gnixeptcszdoubbnfcncumzypwge/Build/Products/Debug/lib/

Please help resolving this issue.

A: You are not providing the correct file to execute; you are passing its path (presumably).
You probably need something like:
ffmpegPresetLaunchPath = [[NSString stringWithFormat:@"%@%@", currentDir, @"/lib/ffmpeg"] retain];

Note: It's clear than error 22 is the errno value EINVAL, however there is no reference to it on the exec() manpage or execve() manpage., so I don't know how you're expected to determine the cause from just the error code.


text:
Q: $C$ Hermitian, show $\text{Tr}(C)=0 \iff \exists P,Q \text{ Hermitian s.t.} \,\, PQ-QP=iC$
Let $C$ be an $n\times n$ Hermitian matrix. Show that $$\text{Tr}(C)=0
 \iff \exists P,Q \text{ Hermitian s.t.} \,\, PQ-QP=iC.$$

Ideas: The right-to-left direction I have no problem with. For the left-to-right direction, I'm going to start with the fact that $$\text{Tr}(C)=0 \implies \exists A,B \in M_n \text{ s.t. } C = AB-BA.$$
I'm having trouble showing we can choose $A,B$ Hermitian. One method would be to try to show $A,B$ must be Hermitian, but that seems too strong. Along this road...
$\text{Tr}(iC)=0$, so we can write $iC=AB-BA$. $iC$ is diagonalizable with all imaginary eigenvalues, so it is skew-Hermitian. Thus $$BA-AB=-(AB-BA)=(AB-BA)^*\\=(AB)^* - (BA)^* = B^*A^*-A^*B^*.$$
But this hasn't gotten me anywhere.


text:
Q: Creating a new variable through another script in python I've been wondering how to accomplish this.
I have 2 python scripts, the major one calls to the other and pass them 3 variables, then this script which is only one function returns a tuple of lenght 4. And finally I call this script through the first one.
My question is is there any method to make that the tuple creates a new variable, e.g a matrix or various vectors in the first script and so avoid to call the function over and over.
Script 1
import numpy as np
import scipy.integrate as integrate
import matplotlib.pyplot  as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

from Funcion_gamma import Fgamma

import time

start_time = time.time()

"Aluminio"

E=7e10       #Modulo de Young
v=0.33       #Modulo de Poison
G=2.63e10    #Modulo de cizalladura
h=0.00286    #Anchura de la placa
a=0.85       #Lado 1 de la placa
b=0.65       #Lado 2 de la placa
rho=2703.6   #Densidad del material
Kmuelle=3

"M y N"

m=7
n=m

Fgamma(Kmuelle,a,m)

Script 2
import sympy as sp
import numpy as np

def Fgamma(KK,aa,M):

    'Definicion de las variables simbolicas'

    g, a, A, C, D, K, x = sp.symbols("g a A C D K x")

    'Funcion Gartner y sus derivadas'

    X=(A*sp.cos(g*x/a))+(sp.sin(g*x/a))+(C*sp.exp(-g*x/a))+(D*sp.exp(-g*(a-x)/a))
    dx1=sp.diff(X,x,1)
    dx2=sp.diff(X,x,2)

    'Ecuaciones a resolver'

    eq1= sp.Eq(X.subs(x,0),0)
    eq2= sp.Eq(dx2.subs(x,0)/dx1.subs(x,0),K)
    eq3= sp.Eq(X.subs(x,a),0)
    eq4= sp.Eq(dx2.subs(x,a)/dx1.subs(x,a),-K)

    'Resolucion de las ecuaciones'

    D1=sp.solve(eq1,D)
    eq33 = eq3.subs(D, D1[0])
    C33=sp.solve(eq33,C)
    D11=D1[0].subs(C,C33[0])
    eq22=eq2.subs([(C, C33[0]),(D,D11)])
    A22=sp.solve(eq22,A)

    eq44=eq4.subs([(C,C33[0]),(D,D11)])
    A44=sp.solve(eq44,A)

    'Obtencion de A'

    AF=A22[0]-A44[0]
    AFF=sp.sympify(AF.subs([(K,KK),(a,aa)]))

    'Calculo de las raices de gamma'

    nn=np.linspace(0,M,num=M,endpoint=False,dtype='int')
    gamma=np.zeros(M)
    Afinal=np.zeros(M)
    Cfinal=np.zeros(M)
    Dfinal=np.zeros(M)

    for jj in nn:
        gamma[jj]=sp.nsolve(sp.Eq(AFF,0),(3+(jj*np.pi)))
        Afinal[jj]=AFF.subs(g,gamma[jj])
        Cfinal[jj]=C33[0].subs([(A,Afinal[jj]),(a,aa),(g,gamma[jj])])
        Dfinal[jj]=D11.subs([(A,Afinal[jj]),(a,aa),(g,gamma[jj])])
    print gamma
    return gamma,Afinal,Cfinal,Dfinal

A: Suppose you have file name for both script be script1.py and script2.py in same directory
To call the function named Femma in file   script2.py in script1.py you will use.
In file script1.py
import script2
    script2.Femma(args)


text:
Q: Merging anonymous types How can I merge two anonymous types, so that the result contains the properties of both source objects?
var source1 = new
{
    foo = "foo",
    bar = "bar"
}

var source2 = new
{
    baz = "baz"
}

var merged = Merge(source1, source2) // <-- here's where the magic should happen

// merged:
// {
//      foo = "foo",
//      bar = "bar",
//      baz = "baz"
// }

A: So here's, what I finally came up with (inspired by @BlueMonkMN's answer):
public dynamic Merge(object item1, object item2)
{
    if (item1 == null || item2 == null)
        return item1 ?? item2 ?? new ExpandoObject();

    dynamic expando = new ExpandoObject();
    var result = expando as IDictionary<string, object>;
    foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties())
    {
        result[fi.Name] = fi.GetValue(item1, null);
    }
    foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties())
    {
        result[fi.Name] = fi.GetValue(item2, null);
    }
    return result;
}

A: The following works in .NET 3.5 (and probably 2.0 as well). I modified davehauser's answer.
    public static object MergeJsonData(object item1, object item2)
    {
        if (item1 == null || item2 == null)
            return item1 ?? item2 ?? new object();

        var result = new Dictionary<string, object>();
        foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties().Where(x => x.CanRead))
        {
            var Value = fi.GetValue(item1, null);
            result[fi.Name] = Value;
        }
        foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties().Where(x => x.CanRead))
        {
            var Value = fi.GetValue(item2, null);
            result[fi.Name] = Value;
        }
        return result;
    }

A: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace ConsoleApplication1
{
  class Program
  {
     static void Main(string[] args)
     {
        var source1 = new
        {
            foo = "foo",
            bar = "bar"
        };

        var source2 = new
        {
           baz = "baz"
        };

        dynamic merged = Merge(source1, source2);

        Console.WriteLine("{0} {1} {2}", merged.foo, merged.bar, merged.baz);
     }

     static MergedType<T1, T2> Merge<T1, T2>(T1 t1, T2 t2)
     {
        return new MergedType<T1, T2>(t1, t2);
     }
  }

  class MergedType<T1, T2> : DynamicObject
  {
     T1 t1;
     T2 t2;
     Dictionary<string, object> members = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);

     public MergedType(T1 t1, T2 t2)
     {
        this.t1 = t1;
        this.t2 = t2;
        foreach (System.Reflection.PropertyInfo fi in typeof(T1).GetProperties())
        {
           members[fi.Name] = fi.GetValue(t1, null);
        }
        foreach (System.Reflection.PropertyInfo fi in typeof(T2).GetProperties())
        {
           members[fi.Name] = fi.GetValue(t2, null);
        }
     }

     public override bool TryGetMember(GetMemberBinder binder, out object result)
     {
        string name = binder.Name.ToLower();
        return members.TryGetValue(name, out result);
     }
  }
}

A: You can't, if what you're expecting is a single object where you can access the properties in a compile-time type-safe way (as opposed to a result which is purely dynamic at execution time). The closest you could come would be:
var merged = Tuple.Create(source1, source2);

Console.WriteLine(merged.Item1.foo);
Console.WriteLine(merged.Item1.bar);
Console.WriteLine(merged.Item2.baz);

Bear in mind that anonymous types are created at compile-time. It's not like they're "dynamic" types. You could use ExpandoObject in .NET 4 for that, but it's not quite the same as an anonymous type with all the relevant properties in.


text:
Q: Add vertical space for individual lines in an array in LyX I know that I can add vertical space for individual lines in an array in LaTeX by including an optional argument after the line break (see example below). Is there way to do this in LyX without using a text editor to directly modify the LyX source file?
\[
\left[\begin{array}{cc}
\dfrac{1}{s} & \dfrac{1}{s}\\[1em]
\dfrac{1}{s} & \dfrac{1}{s}
\end{array}\right]
\]


text:
Q: validate integers for certain values in java I'm trying to verify that users input only 1, 2, or 3. So far I've used sc.hasNextInt() to validate integers, but not those specific ones. Can someone help? My code is below.
System.out.print("Enter Department Number: ");
while (!sc.hasNextInt())
{
    System.out.println("Invalid entry. Please enter 1, 2, or 3 for the
                       department number.");
    System.out.print("Enter Department Number: ");
    sc.next();
}
int department =  (sc.nextInt());

A: You do not account for a String-to-Int Conversion or the newLine character left unconsumed.
while (sc.hasNextLine()) {

   int choice = Integer.parseInt(sc.nextLine().trim());
   if (choice == 1 || choice == 2 || choice == 3)
      //do something

}

A: Your code should be:
System.out.print("Enter Department Number: ");
int department =  sc.nextInt();
while(department != 1 || department != 2 || department != 3 ) {
  System.out.println("Invalid entry. Please enter 1, 2, or 3 for the
                       department number.");
  System.out.print("Enter Department Number: ");
  department = sc.nextInt();
}

A: Read entire line and check that it matches regular expression:
int department;

System.out.print("Enter Department Number: ");
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    if (line.matches("[123]")) {
        System.out.println("Invalid entry. Please enter 1, 2, or 3 for the department number.");
        System.out.print("Enter Department Number: ");
    } else {
        department = Integer.parseInt(line);
        break;
    }
}

A: Use a while loop where you ask for the next integer and only break when it is inside the correct range:
Code:
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int value;
    while (true) {
        System.out.print("Enter Department Number: ");
        if (sc.hasNextInt()) {
            value = sc.nextInt();
            if (value < 1 || value > 3)
                System.out
                        .println("Invalid entry... must be between 1 and 3");
            else
                break;
        }
    }
    else
        sc.next(); // does not block when a string is putted in
    System.out.println(value);
}

A: Not very clean or coherent but
int input;
while(!sc.hasNextInt()||((input=sc.nextInt())>3&&input<1)))

A: You can proceed like this:
Scanner sc = new Scanner(System.in);
int departement;

do {
   System.out.print("Enter Department Number: ");
   departement = sc.nextInt();
}while (departement != 1 && departement != 2 && departement != 3);


text:
Q: Resources are not supported in serialized data Hello everyone m working on a project there is a bundle CustomerBundle when i call a function following errors are display can anyone tell me why this error coccured..

message": "Resources are not supported in serialized data. Path:
  Monolog\Handler\StreamHandler -> Symfony\Bridge\Monolog\Logger ->
  Symfony\Component\Cache\Adapter\FilesystemAdapter ->
  Symfony\Component\Cache\Adapter\TraceableAdapter ->
  Symfony\Component\Cache\DoctrineProvider ->
  Doctrine\Common\Annotations\CachedReader ->
  Doctrine\ORM\Mapping\Driver\AnnotationDriver ->
  Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain ->
  Doctrine\ORM\Configuration -> Doctrine\ORM\EntityManager ->
  CustomerBundle\Repository\CustomerRepository",
                  "class": "JMS\Serializer\Exception\RuntimeException",

this is my Customer entity page
/**
 * @ORM\ManyToOne(targetEntity="CompanyBundle\Entity\Company", inversedBy="company_customer")
 * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
 */
private $companyId;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="created_time", type="datetimetz")
 */
private $createdTime;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="modified_time", type="datetime")
 */
private $modifiedTime;

/**
 * @ORM\OneToMany(targetEntity="SalesBundle\Entity\SalesAccount", mappedBy="customerId" )
 */
private $sales_customer_id;

CustomerApiController controller
namespace CustomerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use CustomerBundle\Entity\Customer;

class CustomerapiController extends FOSRestController
{
    /**
     * @Rest\Post("/api/customer")
     */
    public function customerAction(Request $request)
    {
        $data = $this->getDoctrine()->getRepository(Customer::class);
        $data->find(1);
        return $data;
    }
}

A: I think you should have a look at this post. Similar problem can be solved in the same way.
Write a custom repository function and do the following instead of your "find(1)" :
public function findFirstElement()
{
    $qb = $this->createQueryBuilder('e');

    $qb->where('e.id = 1');

    return $qb->getQuery()->getArrayResult();
}


text:
Q: How to prevent the transfer of package using Scapy module? I'm using Scapy (Python) on Linux.
I scan the network traffic using sniff() function and
I want to drop only some of the packets I scanned, Is there any good way to do this?


text:
Q: How can I use emacs in the TopCoder Arena? TCEMacs looks like what I want, but I don't see installation instructions, and I can't launch the jar.

A: I'm assuming you're talking about version 0.2 of this plugin.
If that is correct, have you actually bothered looking at the contents of the tc_emacs-0.2.tar.gz file offered for download? Besides the .jar file it contains a README that clearly has installation instructions:

Install gnuserv. You can download it from
  http://meltin.net/hacks/emacs/ or just use a package if your GNU/Linux
  distribution provides one. The gnuserv must be working before
  launching the Arena. The easiest way is to put
(gnuserv-start)
in your .emacs file. The gnuserv will then be started together with
  Emacs.
Make sure that you have Emacs/W3 Browser installed in Emacs. You can
  check it by typing `M-x w3 '.
Put topcoder.el and TCEmacs.jar in some directory. The topcoder.el
  file should be loaded before using Emacs in the Arena. You can do that
  by typing `M-x load-library  /path/to/topcoder.el ' or you
  can just place
(load-library "/path/to/topcoder.el")
or, to load the file only when it is needed:
(autoload 'topcoder-set-problem "/path/to/topcoder.el")
in your .emacs file. I had some problems with autoloading, though. The
  keymap in the TopCoder mode did not sometimes work and I had to reload
  topcoder.el manually.
Make a work directory and set the topcoder-directory variable to its
  name. By default it points to a directory named topcoder in your home
  directory.
Launch the Arena applet and choose Options/Editor/Add. Type in a name
  (e.g. Emacs), TCEmacs as the entry point and a path to the TCEmacs.jar
  file in the ClassPath field.
Now choose a problem to solve. If everything went fine, you should see
  two new Emacs windows, one with a problem statement and the second one
  with a source code template.


text:
Q: Automata q0 ∈ F but no transitions to itself. I stumbled upon the following question, hoping someone could be of help.
Q: A secretive developer at your company refuses to reveal the details of her DFSA implementation for the gamepad controller M =< Q, Σ, , q0, F >. After a few drinks, she inadvertently reveals that q0 ∈ F. Can you name one sequence of commands that is accepted by her automaton? Justify your answer.
My thought process was the following: (always taking into consideration the attached diagram.)
Correct me if I'm wrong, but can one say that if he had to stay in the same position i.e. the transition would be ε to the robot he would reach state A?
Diagram
TIA

A: Yes, if the initial state is accepting, then the automaton accepts the empty sequence. (How you communicate the empty sequence to the automaton is not yet revealed.)


text:
Q: Python feedparser not using atom/WordPress namespace? I'm trying to use feedparser (an excellent library) to parse WordPress export files, and a (minor) inconsistency between WordPress version is causing me a huge headache.
WordPress 2.x doesn't include atom:link tags in the XML output (without_atom_tags.xml).  When parsed, namespaced elements are available without the prefix:
>>> feed = feedparser.parse("without_atom_tags.xml")
>>> print feed.entries[0].comment_status
u'open'

The XML from WordPress 3.x does contain atom:link tags (with_atom_tags.xml), and you must prefix namespace elements:
>>> feed = feedparser.parse("with_atom_tags.xml")
>>> feed.entries[0].wp_comment_status              # <-- Note wp_ prefix
u'open'
>>> feed.entries[0].comment_status
AttributeError: object has no attribute 'comment_status'

Interestingly, the prefixes aren't needed if I add xmlns:atom="http://www.w3.org/2005/Atom" to the root RSS element (with_atom_tags_and_namespace.xml).
I need to parse all these different formats without modifying the XML.  Is feedparser broken, or am I doing it wrong?  Can I do this without a bunch of nasty conditional code?

A: Could you add the missing namespaces (atom/wp) to the global list of supported namespaces in feedparser.py directly?


text:
Q: How to get rid of extra space at top of plot using ggplot2 I am using patchwork to combine two plots. Without limiting the y axis of the elevation plot, the scatter plot looks too steep for what I am trying to show (land elevation) but when I limit the axis I am left with loads of space which then squashes the below plot. Is there anyway to remove all that unwanted space to make the elevation plot (P2) neater?
st3<-read.csv("st3raw.csv",header=TRUE)
library(tidypaleo)
library(tidyverse)
theme_set(theme_bw(8))
library(grid)

st3<-pivot_longer(st3, cols=c(-Depth,-Sample,-Total,-
Elevation),names_to="species",values_to="rel_abund")

 st3$Sample <- as.character(st3$Sample)
 st3$Total<- as.character(st3$Total)
 P1<-ggplot(st3, aes(x = Depth,  y = rel_abund,group=1,fill=Sample)) +
   geom_col(position="identity",width=2) +
   facet_abundance(vars(species)) +
   labs(x = "Distance (m)", y = "Relative abundance")

  P1

P2<-ggplot(st3,aes(x=Depth, y=Elevation,colour=Sample))+geom_point()+
scale_x_continuous(breaks=seq(0,320,20))+
scale_y_continuous(limits=c(0,4),breaks=seq(0,1,.25))+
geom_line(size=0.5)+
geom_point(size=2)

P2

library(patchwork)

(P2) /
  P1

 structure(list(Sample = c(1L, 1L, 1L, 1L, 1L, 1L), Depth = c(24L,
 26L, 30L, 32L, 38L, 48L), AT.salsa = c(10.44226044, 0, 0, 0,
 0, 0), BH.wilberti = c(29.97542998, 0, 0, 0, 15.78947368, 0),
     CT.irregularis = c(2.088452088, 2.821869489, 11.76470588,
     1.213592233, 11.11111111, 0), DE.macrescens = c(4.422604423,
     26.45502646, 58.82352941, 28.6407767, 3.50877193, 66.66666667
    ), FT.inflata = c(50, 26.10229277, 27.45098039, 69.41747573,
    68.42105263, 25.14619883), GM.fusca = c(2.702702703, 43.73897707,
    1.960784314, 0.72815534, 1.169590643, 5.263157895), Total = c(0L,
    1L, 0L, 1L, 1L, 1L), Elevation = c(0.937, 0.85, 0.915, 0.868,
    0.836, 0.81)), row.names = c(NA, 6L), class = "data.frame")


text:
Q: Estimating position of peak in noisy sequence data I have a sequence of data with peaks in it; ideally, they represent a point I have to track in space. The point movement is rather smooth, but there are two problems:

*

*peaks change sign relatively to their surroundings (sometimes they are "below", other times they are "above"),

*there is noise, and sometimes signals are barely visible.

Luckily, I know that point position will not change drastically most of the times, therefore I could use knowledge I am confident into to estimate point position when I am not sure about it. Also, begin and end data will coincide (it's a loop).
Take a look this video to understand what is the (unlabeled) data I am working with (I had to skip some frames to upload it, movement is smoother in reality).
Knowing that in some points the downhill point is what I want to track, how can I estimate its position when peaks are barely visible and/or inverted?
I thought about using PGMs, but I have no idea on how to model this problem with continuous distributions and how to do inference with it. Another tool that I thought could be useful is Kalman Filter, but, again, I am not sure about to model it.


text:
Q: Aggregate $group returns wrong values I have a collection named donation
{
    "_id" : 1,
    "reqAmt" : 20,
    "filled" : [
        {
            userId : 1,
            depAmt : 5
        }
    ]
},

{
    "_id" : 2,
    "reqAmt" : 20,
    "filled" : []
},

Expected result
{
    "_id" : 1,
    "reqAmt" : 20,
    "filledAmt" : 5
},
{
    "_id" : 2,
    "reqAmt" : 20,
    "filledAmt" : 0
}

I tried with $unwind .but no luck. It always returns
{ "_id" : null, "filledAmt" : 0 }

Below are the codes
db.donation.aggregate([{$unwind:"$filled"},{$project:{"reqAmt":1,"filledAmt":1} },{$group:{"_id":null,"filledAmt":{"$sum":"$filled.depAmt"}}}])


text:
Q: Search all files in repository for pattern in Perforce Is there a way to search a repository for a pattern that could be contained in one or more code files...
i.e I have the an application, that has a dev, UAT and Prod folders, under each of these there are multiple sub-folders for the code, resource [images, etc], binaries, etc. The program has maybe 100 different code file (.java, .cs, .net, .egl, etc). I would want to click on the application root and do a search for a specific string within each of these files, without having to click on each file.
Is this doable?
I have tried to do the suggestion at https://www.perforce.com/blog/vcs/how-add-grep-command-search-your-helix-core-depot but that only seems to look for file names not the content within a file.
TYIA

A: Use p4 grep.
https://www.perforce.com/manuals/v18.1/cmdref/Content/CmdRef/p4_grep.html
e.g.:
p4 grep -e "a pattern" //depot/path/to/my/app/...

A: I recommend you take a look at the silver searcher. https://github.com/ggreer/the_silver_searcher
It's a tool that lets your recursively walk over files and highlight matches. It's like grep, but works over a directory and provides line numbers of the results.


text:
Q: Detect correct ball that will be hit first Suppose there are some static balls of radius $r$ in a $2D$ table. I will put one of them (let's call it $b$) with velocity $v$.
My question is: how to detect which ball will be hit first? I couldn't prove to myself my approach works and I'm pretty sure it doesn't.

*

*My thought: get all balls whose distance to the line formed by $b$ and $v$ is less than $r$. The answer would be the ball among those whose distance to $b$ is the minimum.

In the image, the nearest ball will be touch but the furthest ball will be touched first.
How can I correctly guess which will be chosen first?

A: Here's an insight: when two circles just touch, they are tangent. That means, right at the point when the moving ball hits another ball, you can draw a straight line through their centres of length exactly the sum of their radii.
This lets you adjust the "effective" distance of the balls depending on how far off the movement axis of the moving ball it is.
Concretely, for balls of equal radii $r$, WOLOG rotate the basis so that say $b=\vec{0}$ and $v$ is in the x-direction. Then a ball at position $(x,y)$ will be hit when the moving ball reaches $\left(x-\sqrt{4r^2-y^2},0\right)$

A: Draw boundaries with radius $2r$ around static balls. When center of moving ball reaches boundary, collision occurs.


text:
Q: Extract Date from pdf c# extracting the date when it lies in the first line same as the string
I've multiple pdf of the same format, all the pdf documents starts with string "BEGIN". Based on the string "BEGIN" I've to extract date which is in the second line. I was able to perform that code.
However my problem is that there are few documents where Date (MM/DD/YYY) and the string "BEGIN" lies in the first line. Here I can't extract the date because it's considering different string which is in the next line.
Below is my code;
string text = string.Empty;
text += PdfTextExtractor.GetTextFromPage(R, i);
int BEGIN_Location = 0;
string sSbeginValue = string.Empty;

 if (text.Contains("BEGIN"))
{
 BEGIN_Location = text.IndexOf("BEGIN", 0);
 sSbeginValue = text.Substring(BEGIN_Location + 6, 10);
}

A: here is my way to get date (xx.xx.xxxx) from pdf using Spire.Pdf
private string ParsePDF(string filepathname)
    {
        PdfDocument document = new PdfDocument();
        document.LoadFromFile(filepathname);

        StringBuilder content = new StringBuilder();
       string tex =  content.Append(document.Pages[0].ExtractText()).ToString();
        MessageBox.Show(tex);
        string pattern;
        pattern = @"\d{2,}.\d{2,}.\d{2,}";// 01_01_2019
        var m = Regex.Match(tex, pattern);
        if (!string.IsNullOrEmpty(m.Value))
        {
            return m.Value.Substring(0);
        }
        return "";
    }


text:
Q: Group of order $8p$ is solvable, for any prime $p$ Consider the following question:

Show that a group $G$ of order $8p$ is solvable, for any prime $p$.

I am kind of stuck, but here are my first attempts:
I chose the series of subroups $G>H_8>H_4>H_2>H_1=\{e\}$ where $H_k$ has order $k$. All of these subgroups exist due to Sylow's Theorems. We have the quotients $H_8/H_4\cong H_4/H_2 \cong H_2/H_1 \cong \mathbb Z/2\mathbb Z$, so $G>H_8\rhd H_4\rhd H_2\rhd H_1=\{e\}$. Only the factor $G/H_8 \cong \mathbb Z/p\mathbb Z$ is causing me a headache, because although its of prime order (and hence abelian) I don't know whether $H_8$ is normal in $G$ (unless $p=2$).
If $p\ne 2$, then the number $k$ of Sylow $2$-subgroups is $1$ mod $2$. Since $k$ divides $|G|$ we might have $k=1$ or $k=p$. If we had $k=1$ then $H_8$ would be the only Sylow $2$-subgroup (and hence normal in $G$). But how could we show this?
Or is there even an easier way to approach this problem?
$\ $
edit: I am going to try a different approach: The case $p=2$ is clear. When $p=3$ or $p=7$ the group has order 24 or 56 and since the smallest simple non-abelian group has order 60, the group must also be solvable in these exceptional cases (as Mariano pointed out).
In any other case we get a Sylow $p$-subgroup $H_p$ of order $p$, which is is normal in $G$. The quotient $G/H_p$ has order $8=2^3$; and prime power order implies solvable. So $G/H_p$ is solvable and $H_p$ is also solvable. And since the composition factors of $G$ are those of $H_p$ together with those of $G/H_p$, we conclude that $G$ is solvable iff $H_p$ and $G/H_p$ are solvable, which is the case. Hence $G$ is solvable if $|G|=8p$.

A: The number $n_p$ of $p$-Sylows divides $8$, so it is one of $1$, $2$, $4$ or $8$, and it is congruent to $1$ modulo $p$, so it is of the form $ap+1$ for some $a$.

*

*$n_p$ cannot be $2$ for then $ap=1$, and $p\neq1$.

*If $n_p$ is $4$, then $ap=3$ so $p=3$, and

*if $n_p$ is $8$, then $ap=7$ and $p=7$.
It follows that for most primes we have $n_p=1$ so the $p$-Sylow is normal, and
you can start the composition series on the other end!
Notice that when $p=3$ or $p=7$ the group has order $24$ or $56$ and, since the smallest simple non-abelian group has order $60$, the group must also be solvable in these exceptional cases.


text:
Q: upgrading the android sdk used in flutter package I would like to upgrade the android version in this flutter package :
https://pub.dev/packages/flutter_onfido
Currently it uses Android SDK: 9.3.1
Could you please tell me how to go about doing this ?


text:
Q: How can I start a Lottie animation from a specific starting point? Let's say a Lottie animation has a total duration of 30 seconds.
How can I start the animation from the 15-second mark as opposed to the beginning mark?
I haven't found anything in the documentation regarding this.
I am presently attempting to do it with this code:
animationView.play()
animationView.isHidden = true

DispatchQueue.main.asyncAfter(deadline: .now() + 15 {
   animationView.isHidden = false
}

The only issue would be the wait time between the user execution and the animation display.

A: Look :
animationView.play(fromFrame:, toFrame:, withCompletion:)

or
animationView.play(fromProgress:, toProgress:, withCompletion:)


text:
Q: Highlight a text displayed in eclipse editor area programatically I am developing a eclipse plugin in which i need to open up a text file in eclipse editor and highlight a line inside the file programatically.
To open a file and to highlight a text/line in eclipse editor area, i used below code,
fileStore = EFS.getLocalFileSystem().getStore(file.toURI());
page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
ITextEditor editor = (ITextEditor) IDE.openEditorOnFileStore( page, fileStore);
editor.selectAndReveal(startOffset, endOffset);

Now say i have a file with below contents
Line:1         xxxxxxxxxxxxxxxxxxx
Line:2         yyyyyyyyyyyyyyyyyyyy
:
:
Line: 20       aaaaaaaaaaaaaaaaaaaaa
Line: 21       bbbbbbbbbbbbbbbbbbbbb

Now i need to highlight Line:20 in above file. For that i need to start offset and end offset of that line. How can i achieve this in Java?
Thanks in advance.


text:
Q: How best to convince people to upgrade IE? I recently asked a question that got shot down for being too strongly worded. I'm having another go today because it's something I really am concerned about and I really do want feedback and ideas from the smart people on SO.
IE6 isn't quite the bane of my existence, but it's close. I'm a web-developer and spend too much time fixing things for IE6. Considering its age and relative quality, I'm shocked so many people are still using it.
I understand that some companies still use it for legacy internal webapp support but I've found two companies now that haven't upgraded solely because XP's automatic updates doesn't offer it by default (you have to go through the browser-based Windows Update to install IE7/8).
So forgetting those that need it, how would you convince an individual or organisation to upgrade to a newer version of IE?
Do warning banners work? I've considered skipping doing the IE6-fixing before and putting a "This site works best in..." statement up but surely having a poorly-rendered site makes me and/or my client look bad, not IE6.
There are also people who don't need to keep IE6 but cannot upgrade because they're in a controlled environment. What is the best way to influence them enough to get their admins to do something about the problem?
Note: As I said last time, I don't care about moving these people to another browser. I don't mind giving them the option but this certainly isn't supposed to be a Firefox/FOSS uber-alles thread.
I'm also not looking for a fight, just constructive ideas on making business types aware of browser technologies in the least damaging way.
Edit: There are a couple of "you can't force it" answers. I agree, but I feel I could influence it. I tell people when I see IE6 but I'm not sitting behind every IE6 user that accesses a site I've made.
Consider health warnings on cigarettes. They don't force people to stop smoking but they do educate in a succinct and (nowadays) fairly brutal way. There's no doubt that educating people has had a massive effect on the numbers of smokers.
IE6 is a lot less addictive than smoking so, yeah, pushing the education idea seems like it might be able to influence the right people to do the right thing.

A: Simple sales.
You have to find what motivates your users, and demonstrate to them how upgrading will benefit them.
The problem is for the users you're targeting (non-tech savvy usually, or else corporate policy bound), there isn't much to motivate them, other than scare tactics I suppose.
You could write very simple easy to maintain pages for IE only, and save the cool stuff for other browsers, and show them a preview of what another browser could do...

A: Here's a good one:  Microsoft SharePoint 2010 will not support IE6.
This will force the majority of most large companies to upgrade.

A: Oli,
I have been in your situation before.  In all cases, I make sure my CSS and Javascript renders and works well in IE6, but then I add progressive enhancements for later browsers.  Then I entice the customer by saying "I've added some extra things which you can see in newer browsers".  This itself at most times makes them intrigued to make the switch.

A: Download IE8, Google Chrome, Safari, or Firefox and show them how much faster they render a page than IE6.
Tell them that request caching does not work correctly with IE6 either (if you're using IIS)
But in all honesty, show them the speed of the newer browsers, especially if you are doing anything with a lot of javascript.  The new rendering speeds are phenomenal.

A: GMail showed IE6/7 users a small unobtrusive notification to the effect of, "Want your GMail to work better/faster? Click here". The landing page offered upgrades to Chrome, FF3, and IE8.
I think if more sites spread the word about the end-user benefits of installing free, upgraded software from trusted names; that would go a very long way.

A: I think the best you can hope for is hacking the CSS, but using a banner.
A Note to Everyone: Friends don't let friends use IE6.

A: Ignoring installations where IE6 is mandated, consider segmenting your application, with basic (though non-buggy and usable) functionality available to IE6 users, and advanced functionality available only to newer browsers.  Draw users to newer browsers with the promise of cool stuff.

A: I think for now the best thing is to deal with it.  I'd try to make your site fully compatible with IE6 & up.  But, you could still include browser detection in the site that tells the user that they're using a browser that may not work properly for your site.
I've seen sites do this before.  Bank of America's online banking comes to mind.  In the past they'd put up a message to this affect when you ran Google Chrome.  You can have a warning message stating that the site may not work properly with your browser, even though it does for the most part.  This is one way to encourage the user to upgrade.  But it's a fine line.  If you overdo it you'll inevitably scare off some users who are unwilling or unable (think public libraries, schools, etc) to upgrade their browser.

A: IMO, essentially you're just wasting your time if you try to do this. No matter how much educating you do, as long as Windows XP is the dominant OS, you're still going to have to support IE6, because a good portion of IE users are just using what came with their OS and aren't going to upgrade, period. You might convince some people to upgrade, but you won't convince enough to make a difference in whether or not you continue to support IE6. It wasn't until Windows 98 finally went away that IE4 could safely be ignored.
If Windows 7 makes a better showing than Vista did, then perhaps in 3 years or so we won't have to worry about IE6 any more, but until then it's just a fact of life you'll have to deal with. If you want to convince people to upgrade simply because you want to help them have a better experience, then that might be a worthy goal, but trying to convince them to upgrade so that you no longer have to support that browser will just be an exercise in futility.

A: You can't force them, especially if IT in their companies mandates IE6.
EDIT: I agree about educating people, but although someone is educated, he still can't upgrade unless IT allows it.

A: I think you are thinking the wrong way about it. Supposing every one of us takes our decisions based on effort vs advantages, do you think that upgrading the browser (lot of work and very difficult for a non techie) has enough advantages to justify doing it? Maybe not!

A: All it takes is time, vista ships with IE7, windows 7 will ship IE8. Although corporations will not switch over overnight, time will fix this

A: If you're serving up content that your consumer base really cares about, but your site can't realistically function on IE 6, then I do a check if they're using browsers you don't support (IE 6) and if they are redirect them to a page specific to their browser (limited capabilities, not well supported, etc.) or just a page that says they're using a browser you don't support.
The point here is this: If they really care, then they'll harp on their IT department to get it installed.  However, if you just let them use your site, but in a broken sense, then they'll just think your site is terrible and needs to get fixed.

A: My current company still mandates IE6 and I suspect that it is because they have a lot of internal sites that don't work in IE7.  There is not much you can do about that.  At least I can also use Firefox for sites outside of the company.

A: A few less fingernails and toes should convince them.

A: If you're the vendor supporting a web application which your customer insists upon using with IE6 rather than an updated browser, I'd say try to offer them upgrade incentives (e.g. lower support contract fees, a one-time renewal discount, or some "enhanced" feature set which would magically be enabled once they upgrade their lowest common denominator browser-wise).
I'd agree with some of the previous sentiments mentioned about warning banners, they'd be annoying and useless.
If the company is so big and/or bureaucratic that they are a hard sell in terms of upgrading, it might take years for them to get "current".  A hospital I once worked for was just finishing an upgrade to Windows NT 4 while XP had already been out a year.
Personally, if I had any influence over such a situation I would enclose with my annual invoice a very obvious raise in my support or dev fees substantially every year IE6 remains in use at the customer's site, while at the same time presenting them the attractively lower-priced option of upgrading their browser right alongside.

A: Well, you could always tell them it is 8 years old.  Probably older than their TV or car.  Most people will willing upgrade to a newer model if they can get it free.  Just put it in terms of other things (like cars and TVs) to get them an idea of how old it really is.  This should work well with upper management types as they lose alot of technical focus...usually. :)

A: I think that this is a problem that will sort itself out overtime. Newer apps are starting to use HTML5 features, something that I doubt IE will support within the next 5 years. This alone should start to move customers away from older browsers.

A: The best way I can think of getting people to upgrade awayfrom IE6 is to buy a new computer or upgrade their operating systems.
People don't keep IE6 because they like it. They keep it because their IT department requires it. This can be either because they have in house software which they cannot upgrade or because their IT department doesn't want to be bothered, but the former is more likely.
However, I believe XP is the last OS that you could get with IE6. Vista and Win7 don't support it so users and IT departments have no choice.

A: You'd think that tabbed browsing would be enough of a selling point.

A: The only way that you will be able to "force" upgrades is to create a must-have application for enterprise that requires the latest version of Internet Exploder to function.
Chances of that, however, are slim.
A far better option is to actually develop your web application with your target market in mind. If you are developing a product for enterprise where legacy browsers are the norm, then develop to cater for that.
You can only go so far in holding your visitors hand. If they are not willing to change their behaviour with browser choice then it really is not your problem.
At the end of the day, if we decided that we absolutely must cater for everyone, then you can forget all about any of the advancements that have been made in browser technology over the last 15 years and have (close on) 100% coverage. But thats just ridiculous.
Basically - develop for your target market using cross-browser compatible technologies and degrade functionality/styling as neccessary - and realise that you can't please everybody all the time

A: i think the best way is to repackage your site only for IE7+(displaying the old version for IE6) and advertise it on your IE6 site in an attractive way like "NEW" "UPGRADE TO GO TO V2, the NEW FEATURED THING" and other deceptive but harmless ways of marketing :P . basically, make it attractive for them to move on to IE7/FF/etc. or people wont think it would be worth the effort.
the move would be logarithmically or even exponentially paced, i.e as users start moving, more users would get convinced its worth it, something like peer pressure :P

A: You'd have to make a good argument. For example how FF is more secure because it generally runs using less privileges than IE6.
There was some funny img on digg, a notice from school admins upgrading to firefox, and that was one of the reasons.
edit: I use ie6update.com's script on my popular site to help those poor ie6 users upgrade :P

A: You could prove it to them by scanning their machine with something like HiJackThis  to show them how compromised their existing computer is by not having the latest IE.

A: Are you aware of the Stop Living In the Past script? Just plop the script on your website to encourage IE6 users to upgrade, with a friendly, non-condemning message and link to the latest IE.

A: Simple!.. Newer versions have not been thoroughly tested and therefore are not supported!.. Newer versions of many software products also introduce unsuspecting passive features which are marketing oriented and even eavesdrop on confidential information!

A: Be not the first by whom the new are tried,
Nor yet the last to lay the old aside.
-- Alexander Pope

A: You cannot convince people to upgrade. The only people left who have IE6 either don't care or work in large corporations/government who have no control over which browser they use.
A banner or warning is just going to annoy them all.

A: From my experiences, if you're having rendering issues, it's typically a deeper issues with your css.  Typically, I make one stylesheet and it runs more or less identically in both IE and Firefox.
For example, centering a div using auto margins won't work in IE if you don't explicitly include a doctype.  This is really a normal expectation for an html document so the rendering issue isn't an issue to begin with.
These sorts of things travel up the totem pole.  Unless you're using ASP.NET web controls, you should have no trouble making your divs render correctly in all browsers using a single stylesheet.

A: Create one standard for the web.
Then fix IE.

A: I'm not an IE user so my comments will speak more to the software life cycle.  Until Microsoft quits supporting it, and they may have (see my first statement), you're stuck supporting it.  Once Microsoft abandons it, then you can abandon it unless you have a requirement or need to do otherwise in which case this question would be moot.  At least one other person recommended branching your work to have a basic IE6 version and a more elaborate IE7/8 version.  I don't know how web development is done, but in the embedded world I would be starting a new source branch with each new release of IE an merging just the bug fixes back to the previous branches.  This keeps all the new feature development current with the latest product, in your case IE8.  The point that the other contributor and i are trying to make with this is that people, including those who manage IT departments and large companies will eventually want the new features or will subcumb to the fact that there is no new development going on for their platform.

A: Advantages  of browser upgrading
http://www.browser-update.org/


text:
Q: Why did "Open a pull request" remind occuer when I push to Github with some account in different PCs I was learning some new features about the Android JetPack and I init a repo on the Github to record my every step of the learning. I use some account push both in my home PC and work PC. This repo starts in my home PC but after I push a commit in work PC, my dev branch reminds me to "Open a pull request" and I'm totally confused. I browsed the commit history of dev branch, all come from one single account. I could really need some help to terminate this remind.
open a pull request opration
pull request remind

A: Any time you push code to a non-default branch or to a fork, GitHub will suggest that you might want to open a pull request, regardless of the system or account you used.  It's common in many environments to share a single repository, and GitHub has no idea whether you're using a pull request workflow or not.  Since many users want to open a pull request in this case and use the UI to do so, it always opens a notification in the UI to suggest that.  There does not appear to be a way to turn this functionality off.


text:
Q: How do I specify the Android API Level in PhoneGap? The default PhoneGap app wants me to get API 17. However I have 18 and would rather use that. How do I specify which version of the API to use?  I did some searching of some config files in my project but didn't see anything specifying the level to be 17.
I'm developing on Windows and want to build android locally.
I've followed the developer guide so that I have a phonegap project called hello that has the following folders:

*

*.cordova

*

*hooks

*config.json

*build (empty)

*merges (empty)

*platforms (empty)

*plugins

*www

*

*css

*img

*js

*res

*spec

*config.xml

*icon.png

*index.html

*spec.html

I tried phonegap add platform android but errored saying 'platform add android' is not a node

A: You shouldn't edit AndroidManifest.xml. You can/should do it cordova config.xml file in preference:
<preference name="android-targetSdkVersion" value="14" />
<preference name="android-minSdkVersion" value="14" />

A: For Android 6.0 (API 23) , Android version is specified in project.properties file.
It is placed just close AndroidManifest.xml in ProjectDir/platforms/android directory.
If it can help.

A: The way I handle platform customizations is to create a separate directory called config with this structure:
   config
       android
           AndroidManifest.xml
           images
       ios
           images

Then I write a hook to copy the files from config to platforms/android/... (either after_prepare or after_platform_add depending on how often I want to copy over the files).
That way you can modify AndroidManifest.xml and still keep the platforms directory totally under control of Cordova CLI.

A: Please do not modify AndroidManifest.xml in your platforms directory. With current cordova/phonegap version, this should not be necessary anymore (you can ignore platforms from version control!).
Instead set:
<preference name="android-minSdkVersion" value="14" />

All possible configs are available here: http://docs.build.phonegap.com/en_US/2.9.0/configuring_basics.md.html (the document says, it works for phonegap build, but it works the same for cordova/phonegap cli!).
EDIT: New Link http://docs.phonegap.com/phonegap-build/configuring/preferences/#android-minSdkVersion

A: You need to set it in the AndroidManifest.xml within your Android project
<uses-sdk android:minSdkVersion="18"
        android:targetSdkVersion="18"
        android:maxSdkVersion="18"
        />

Change the minSdkVersion, targetSdkVersion and maxSdkVersion according to your requirements.


text:
Q: Typescript deep omit with dot notation As template literal types are now supported in TypeScript, is it possible to have something like the following?
interface Data {
  a: number;
  b: {
    c: number;
    d: number;
  }
}

type OmitDeep<T, K> = ...

type WithoutC = OmitDeep<Data, 'b.c'>

Where WithoutC will be inferred as:
interface WithoutC {
  a: number;
  b: {
   d: number
  }
}

A: You can use this type to map dotted path to an array path:
type UnDot<T extends string> =
    T extends `${infer A}.${infer B}` ? [A, B] : ''

type ProperyArray = UnDot<'a.b'>; // ["a", "b"]

And then use this answer to remove nested properties:
Types for deleting object at specific nested path
Edit for any number of nesting levels:
type UnDot<T extends string> =
    T extends `${infer A}.${infer B}`
    ? [A, ...UnDot<B>]
    : [T];

A: In addition to Roberto's wonderful answer, the full solution looks like this one:
type Tail<T extends any[]> = ((...t: T) => void) extends ((
    h: any,
    ...r: infer R
) => void)
    ? R
    : never;

type DeepOmit<T, Path extends string[]> = T extends object ?
    Path['length'] extends 1 ? Omit<T, Path[0]> : {
        [K in keyof T]: K extends Path[0] ? DeepOmit<T[K], Tail<Path>> : T[K];
    } : T;

type UnDot<T extends string> =
    T extends `${infer A}.${infer B}`
    ? [A, ...UnDot<B>]
    : [T];

type Nested = {
    a: number;
    b: {
        c: number;
        d: number;
    }
};

type Omitted =  DeepOmit<Nested, UnDot<'b.c'>>

const foo: Omitted = {a: 1, b: { c: 1, d: 2 } }; // error
                                 ~~~~

Typescript playground


text:
Q: Reading a Maths equation Hello I have encountered an equation from number theory that I don't quite understand. I am working on my own, so it is difficult to know what I am looking at or decide what to search for on Google to gain understanding. I understand the symbol for integer.
Can someone please explain this equation to me in detail as well as refer websites to me that may provide some useful notes:
$Z[\sqrt{−5}] = \{a + b \sqrt{−5} : a, b ∈ Z\} ⊂ C$,
Thank you.

A: What is says is that the set of numbers in $\Bbb Z[\sqrt {-5}]$ is all numbers of the form $a+b\sqrt{-5}$ where $a,b$ are integers and it forms a subset of $\Bbb C$, the complex numbers.  Some examples are $2+3\sqrt{-5}, -4-999\sqrt{-5}, 15$ (because $b$ may be zero), and $8 \sqrt {-5}$ (because $a$ may be zero).  This is a definition of the set, so in a sense no explanation is needed.  It will turn out that this is a ring, which they will probably go on to prove.  That means you can add, subtract, and multiply these numbers and that multiplication distributes over addition like you are used to in the integers.  Any such set $Z[\sqrt{k}]$ is a ring.

A: This is a definition of the set Z[-sqrt(5)]
The set $Z[\sqrt{-5}] $
$=$   is
$\{ a+b \sqrt{-5} $    numbers of this form
$ : a, b$   the numbers
$ ∈\mathbb{ Z} $  are members of the set Z
$ \} ⊂ C $   ia a subset of the complex numbers.


text:
Q: How to avoid `IllegalAccessError` when inner classes access protected outer class super I am using an inner class in a Spring Controller. It is having problems accessing protected fields/methods from it's parent classes super class.
Research suggests that this is caused by differing class-loaders in some way but I don't know enough about Spring to be certain.
class SuperBaseController {
    protected String aField;

    protected void aMethod() {

    }
}

@Controller
class OuterMyController extends SuperBaseController {

    class Inner {

        public void itsMethod() {
            // java.lang.IllegalAccessError: tried to access method
            aMethod();
        }

        public void getField() {
            // java.lang.IllegalAccessError: tried to access field
            String s = aField;
        }
    }

    void doSomething () {
        // Obviously fine.
        aMethod();
        // Fails in the Inner method call.
        new Inner().itsMethod();

        // Obviously fine.
        String s = aField;
        // Fails in the Inner method call.
        new Inner().getField();
    }
}

Are there any simple techniques to avoid/fix this issue? Preferably ones that do not involve making the fields/methods public.
I have confirmed that the ClassLoader attributes of the outer class is not the same as that of the super class.

A: I created the following classes:
public class BaseController
{
    protected String field;
    protected void method()
    {
        System.out.println("I'm protected method");
    }
}

@RestController
@RequestMapping("/stack")
public class StackController extends BaseController
{
    class Inner
    {
        public void methodInvocation()
        {
            method();
        }
        public void fieldInvocation()
        {
            field = "Test";
        }
    }
    @RequestMapping(value= {"/invoca"}, method= {RequestMethod.GET})
    public ResponseEntity<String> invocation()
    {
        Inner in = new Inner();
        in.fieldInvocation();
        in.methodInvocation();
        return new ResponseEntity<String>("OK", HttpStatus.OK);
    }
}

I tried to invoke the rest service and I had no issue. Now I'm using this configuration for Spring (annotation based annotation):
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "it.spring.controller" })
@PropertySource( value={"classpath:config.properties"}, encoding="UTF-8", ignoreResourceNotFound=false)
public class DbConfig
{
}

@Configuration
@EnableWebMvc
@Import(DbConfig.class)
@PropertySource(value = { "classpath:config.properties" }, encoding = "UTF-8", ignoreResourceNotFound = false)
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
}

As you can see I used the @Import annotation and in my web.xml I use this configuration:
<servlet>
    <servlet-name>SpringDispSvlt</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </init-param>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>it.WebMvcConfig</param-value>
    </init-param>
    <init-param>
        <param-name>dispatchOptionsRequest</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
</servlet>

By using this configuration I had no issue in invoking protected fields and/or method inside an inner class
If you can't adapt your configuration to this one.. may you post the configuration you used?
I hope it can be useful
Angelo

A: How about:
class OuterMyController extends SuperBaseController {
    private String getAField() { return super.aField; }
    protected void aMethod() { super.aMethod(); }
    ...
}

Now the inner class uses its outer class's methods so there's no illegal access, and the outer class's methods have access to the protected fields of the base class.

A: class SuperBaseController {
protected String aField;

protected void aMethod() {

    }
}

@Controller
class OuterMyController extends SuperBaseController {

    public void itsMethod() {
        aMethod();
    }

    public void getField() {
        String s = aField;
    }

class Inner {
    public void innerItsMethod() {
        itsMethod();
    }
    public void innerGetField() {
    String s = getField();
    }
}

void doSomething () {
    aMethod();
    new Inner().itsMethod();
    String s = aField;
    new Inner().getField();
    }
}

Does this work?
Also, you may have to define which object is running the method.
(e.g. Inner.getField(), or SuperBaseController.aMethod())