text:
Q: match multiple columns from gzip files I would like to match multiple columns between file1.txt and file2.gz without unzipping file2.
file 1.txt:
1       11710779        -
1       12919623        CC

file2.gz:

1       13380   .       C       G       7829.15 VQSRTrancheSNP99.60to99.80      AC=30;AC_AFR=14;AC_AMR=1;AC_Adj=15;AC_EAS=0;AC_FIN=0
1       13382   .       C       G       320.40  VQSRTrancheSNP99.60to99.80      AC=3;AC_AFR=0;AC_AMR=0;AC_Adj=1;AC_EAS=0;AC_FIN=0;AC
1

I want to match $1,$2,3 in file1.txt with $1,$2,$4 in file.gz and return all lines in file2.
I tried
awk -F '\t' 'NR==FNR{c[$1$2$4]++;next};c[$1$2$3] > 0' file2.gz file1.txt

and
 awk -F '\t'  'NR==FNR{a[$1,$2,$3]++;next} (a[$1,$2,$4])' file1.txt file2.gz

Both commands did not work. Contents in file1 exist in file2 when I grep some of them individually.
I'm not sure if I need to unzip file2 first before running the command. I can't unzip the file as it's too big.

A: Try this approach:
$ cat > test.in
1 2
3 4
$ gzip test.in
$ awk '{print $1}' <(gunzip -c test.in.gz)
1
3

A: zcat file2.txt.gz | awk -F '\t'  'NR==FNR{a[$1,$2,$3]++;next} a[$1,$2,$4]' file1.txt -

The two file arguments to awk are file1.txt and  -.  The second file, -, tells awk to read from stdin where we have piped in file2.txt.gz
Example
Let's consider these two sample files:
$ cat file1.txt
1       11710779        -
1       12919623        CC
1       13382   C

And:
$ zcat file2.txt.gz
1       13380   .       C       G       7829.15 VQSRTrancheSNP99.60to99.80      AC=30;AC_AFR=14;AC_AMR=1;AC_Adj=15;AC_EAS=0;AC_FIN=0
1       13382   .       C       G       320.40  VQSRTrancheSNP99.60to99.80      AC=3;AC_AFR=0;AC_AMR=0;AC_Adj=1;AC_EAS=0;AC_FIN=0;AC

Now, let's run our command:
$ zcat file2.txt.gz | awk -F '\t'  'NR==FNR{a[$1,$2,$3]++;next} a[$1,$2,$4]' file1.txt -
1       13382   .       C       G       320.40  VQSRTrancheSNP99.60to99.80      AC=3;AC_AFR=0;AC_AMR=0;AC_Adj=1;AC_EAS=0;AC_FIN=0;AC


text:
Q: C# Automapper 6.1.1 - Collection/List destination properties loses values Entity Framework 6 I have a problem when mapping collections with Automapper 6 and I can't find a solution. In the updatedArticle object below I have the old Created and Updated values left after mapping since they do not exist on the view model. However the values for Created and Updated in Descriptions are lost. The values that do come in via the view model are all updated correctly. What am I doing wrong? Automapper also loses Entity Framework 6 mapping for Article since those values are lost as well.
Controller method:
public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
    Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
    Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
    return Ok();
}

Mapping:
Mapper.Initialize(cfg =>
{
    cfg.CreateMap<ArticleViewModel, Article>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore());

    cfg.CreateMap<DescriptionViewModel, Description>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore())
        .ForMember(x => x.ArticleId, opt => opt.Ignore())
        .ForMember(x => x.Article, opt => opt.Ignore());
}
Mapper.AssertConfigurationIsValid();

Viewmodels:
public class ArticleViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<DescriptionViewModel> Descriptions { get; set; }
}

public class DescriptionViewModel
{
    public int Id { get; set; }

    public string Heading { get; set; }
}

Models:
public class Article : IEntity<int>
{
    public Article()
    {
        Descriptions = new List<Description>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Name { get; set; }

    public virtual ICollection<Description> Descriptions { get; set; }
}

public class Description: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}

A: Finally solved it after two days frustration. Installed AutoMapper.Collection from https://github.com/AutoMapper/AutoMapper.Collection
PM> Install-Package AutoMapper.Collection
PM> Install-Package AutoMapper.Collection.EntityFramework

All I had to change was cfg.AddCollectionMappers(); and EqualityComparison. Example:
Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();

    cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);

    cfg.CreateMap<DescriptionViewModel, Description>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);
}
Mapper.AssertConfigurationIsValid();

A: Have you tried this without lazy loading? I had some issues with EF Lazy Loading and AutoMapper myself. First of all it is very inefficient.
See related
Answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trendnet KVM switch does not work witk ubuntu 22.04 My Trendnet KVM switch used to work well with ubuntu 20.04. After upgrading to 22.04 the scroll lock key does not work to switch computers.
The problem is not with the switch since it works with Windows OS.


text:
Q: Webview is blank or loading same page for different urls A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import my.stayactive.plan.ActiveHelper.ApiException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class StayActiveActivity extends Activity implements OnItemClickListener {

    //private EditText m_search_text;
    protected EditText m_zip;
    private ListView m_search_results;
    private Button m_search_btn;
    private JSONArray m_results;
    private LayoutInflater m_inflater;
    private InputMethodManager m_ctrl;
    private Spinner m_radius;
    private Spinner m_activity_selector;
    public static int radius = 0;
    public static String activities;
    public String url;
    public String trackBack;
    public static String assetId;

    static final private int EXIT_ID = Menu.FIRST;

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

        setContentView(R.layout.main);
       // m_search_text = (EditText) findViewById(R.id.search_text);
        m_zip = (EditText) findViewById(R.id.zip);
        m_search_btn = (Button) findViewById(R.id.search_button);
       // m_searchm_results = (ListView) findViewById(R.id.lview);
        m_search_btn .setOnClickListener(go_handler);

        m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        m_inflater = LayoutInflater.from(this);
        addListenerOnSpinnerItemSelection();
        addListenerOnSpinner1ItemSelection();

      m_search_results = (ListView)findViewById(R.id.lview);
      m_search_results.setOnItemClickListener(this);

    }

    public void addListenerOnSpinnerItemSelection() {
        m_radius = (Spinner) findViewById(R.id.spinner);
        m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
      }

    public void addListenerOnSpinner1ItemSelection(){
        m_activity_selector = (Spinner) findViewById(R.id.spinner1);
        m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);

        menu.add(0, EXIT_ID, 0, R.string.exit);
        return true;
        }
    @Override
    public boolean onOptionsItemSelected (MenuItem item){

        switch (item.getItemId()){
        case EXIT_ID:
            finish();
            return true;

        }

        return super.onOptionsItemSelected(item);

    }

    OnClickListener go_handler = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
            m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);

            //String searchText = Uri.encode(m_search_text.getText().toString());
            String zip = Uri.encode(m_zip.getText().toString());

            new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
            // Show a toast showing the search text
            Toast.makeText(getApplicationContext(),
                    getString(R.string.search_msg) + " " +
                    activities, Toast.LENGTH_LONG).show();
        }
    };

    private class SearchTask extends AsyncTask<String, Integer, String>
    {

        ProgressDialog dialog;

            @Override
            protected void onPreExecute() {

                dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");

                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                try {
                    String result = ActiveHelper.download(params [0]);
                    return result;
                } catch (ApiException e) {
                    e.printStackTrace();
                    Log.e("alatta", "Problem making search request");
                }
                return "";
            }
            @Override
            protected void onPostExecute(String result) {
                dialog.hide();
                try {
                    JSONObject obj = new JSONObject(result);
                    m_results = obj.getJSONArray("_results");
                    if (m_results == null || m_results.length() == 0)
                    {
                        Toast.makeText(getApplicationContext(),
                                "No Results found for " + activities,
                                Toast.LENGTH_LONG).show();

                    }
                    else
                        m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

    private class JSONAdapter extends BaseAdapter
    {
        public JSONAdapter(Context c){

        }

        public int getCount()
        {
        return  m_results.length();
            }

        public Object getItem(int arg0){
            return null;
        }

        public long getItemId(int pos){
            return pos;

        }

        public View getView(int pos, View convertView, ViewGroup parent) {
            View tv;
            TextView t;

            if (convertView == null)
                tv = m_inflater.inflate (R.layout.item, parent, false);
            else
                tv = convertView;
            try {
                /* For each entry in the ListView, we need to populate
                 * its text and timestamp */
                t = (TextView) tv.findViewById(R.id.text);
                JSONObject obj = m_results.getJSONObject(pos);

                t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|&quot|&amp|;|)(.|\n)*?>", ""));
                        //("\\<.*?\\>", ""))

                t = (TextView) tv.findViewById(R.id.created_at);
                JSONObject meta = obj.getJSONObject("meta");
              //  url = meta.getString("eventURL");
                trackBack = obj.getString("url");
                assetId = meta.getString("assetTypeId");
                //String eventDate = meta.getString("startDate");
                Calendar currentDate = Calendar.getInstance();
                long dateNow = currentDate.getTimeInMillis();

               String eventDate = meta.getString("startDate");
               String endDate = meta.getString("endDate");
               SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd");
               Date date = null;
               Date date2 = null;
            try {
                date = formatter.parse(eventDate);
                date2 = formatter.parse(endDate);
            } catch (java.text.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
               long modifiedDate= date.getTime();
               long modifiedEndDate = date2.getTime();

                if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)

                {

                    t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));

                }
                    else {
                    t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
                }

            } catch (JSONException e) {

                Log.e("alatta", e.getMessage());
            }
            return tv;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        /*try {
        JSONObject obj = m_results.getJSONObject(position);
        JSONObject meta = obj.getJSONObject("meta");
        url = meta.getString("eventURL");

        //Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
        //StayActiveActivity.this.startActivity(intent);

        } catch (JSONException e) {

            Log.e("alatta",e.getMessage());
        }*/

        // TODO Auto-generated method stub
        final CharSequence[] items = {"Register", "Additional Information"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Please Select an Option");
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                if (which == 0){

                    Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
                    StayActiveActivity.this.startActivity(intent1);

                }

                else if ( which == 1){
                Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
                StayActiveActivity.this.startActivity(intent);

                }

            }
        });
    AlertDialog alert = builder.create();
    alert.show();

    }}

WebViewActivity
package my.stayactive.plan;

import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

    public class WebViewActivity extends StayActiveActivity {

            private WebView webView;

            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.webview);

                webView = (WebView) findViewById(R.id.webView);
                WebSettings setting = webView.getSettings();
                setting.setJavaScriptEnabled(true);
                if (url != null && url.length()>0) {
                webView.loadUrl(url);

            }
              }

            }

A: You didn't pass URL to your WebViewActivity. To do that:

*

*Before calling startActivity(), attach your URL to the intent with setData().

*In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.

Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;

//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);

To retrieve data:
//...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //...
    Uri uri = getIntent().getData();

    //...
    webView.loadUrl(uri.toString());
}

A: My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return false;
        }
});

Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.


text:
Q: Add Timestamp USB barcode scanner I bought a USB Honeywell 5145 barcode scanner
And want to add for each scan system- time and date. I searching for a way to connect with the USB port for data tweaking. Tried Gnome terminal but that does not did the trick so far.


text:
Q: Advantages of ShingleFilter\n-GramTokenizer? I have been using standard Analyzer for indexing and searching in Lucene. I recently came across Shingles (2 word shingles\bigrams)and the only advantage I found so far in my research, is that phrase searches will be faster.
On the downside, my index size increased.
I am not very sure what are the real advantages\features my application would benefit by using Shingles.
How would it affect my other existing searches (Stem\Fuzzy etc. Searches) if I index by tokenizing my documents using Shingles/NGramTokenizer?
Can somebody please shed some light on this topic?

A: It won't affect your other searches, however the size of index will be very large compared to the one indexed using Standard Analyzer.


text:
Q: Why is StackExchange API generating an answer with ID = 0? I've been trying to get the StackExchange API to work correctly over the last couple of days and while there seems to be progress, I'm still not getting the end result.
I'm testing it out using the https://api.stackexchange.com/docs/create-answer form and am trying to post a new answer to the "sandbox" question with ID of 51812.  I enter in the ID, body, key and access_token (based on my App key and an access_token I got when authenticating) and when I run the API request (/2.2/questions/51812/answers/add) using the parameters, I get back what looks like a valid JSON response (vs. some error response) but yet I still do not see the actual answer/body associated with the Question 51812.  The strange thing is the "answer_id" in the response JSON is 0, which doesn't seem right either.
Any explanation or suggestions as to why the API isn't working / answer isn't actually getting created?
Here is the JSON response I get:
{
  "items": [
    {
      "owner": {
        "reputation": 1,
        "user_id": 269870,
        "user_type": "registered",
        "profile_image": "https://www.gravatar.com/avatar/5597f8d6d5d75f3421516b9b0ff8c100?s=128&d=identicon&r=PG&f=1",
        "display_name": "Dave",
        "link": "http://meta.stackexchange.com/users/269870/dave"
      },
      "is_accepted": false,
      "score": 0,
      "last_activity_date": 1409802888,
      "creation_date": 1409802888,
      **"answer_id": 0,**
      "question_id": 51812
    }
  ],
  "has_more": false,
  "quota_max": 10000,
  "quota_remaining": 9998
}


text:
Q: Unable to generate the .xlsx file I have a text file which is in tab deliminator and following is my code to generate its Excel.
protected void to_excel(object sender, EventArgs e)
    {
        string filepath = Path.Combine(Server.MapPath("~/Files"), fileupload.FileName);
        fileupload.SaveAs(filepath);
        string fname = fileupload.PostedFile.FileName;
        DataTable dt = (DataTable)ReadToEnd(filepath);
        string sFilename = fname.Substring(0, fname.IndexOf("."));
        HttpResponse response = HttpContext.Current.Response;
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=" + sFilename + ".xls");
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
        System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
        dg.DataSource = dt;
        dg.DataBind();
        dg.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    private object ReadToEnd(string filePath)
    {
        DataTable dtDataSource = new DataTable();
        string[] fileContent = File.ReadAllLines(filePath);
        if (fileContent.Count() > 0)
        {
            string[] columns = fileContent[0].Split('\t');
            for (int i = 0; i < columns.Count(); i++)
            {
                dtDataSource.Columns.Add(columns[i]);
            }
            for (int i = 1; i < fileContent.Count(); i++)
            {
                string[] rowData = fileContent[i].Split('\t');
                dtDataSource.Rows.Add(rowData);
            }
        }
        return dtDataSource;
    }

This code works fine since i am generating 2003 excel file (.xls).
But if i am generating a 2007 (.xlsx) by changing the code to
Response.AddHeader("content-disposition", "attachment;filename=" + sFilename + ".xlsx");

i get an error like this.
I did my homework and came to know that this error is because the .xlsx file generated by my program is done by using HTML (markup language) XML (markup language) which should actually be done for a 2007 excel file.
My question is what changes should i do so that i get the desired result i.e. I get the 2007 excel sheet!!!

A: You can create the Excel with multiple Worksheet using DataSet like
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using System.Data;
using System.IO;

[HttpPost]
    public ActionResult CreateExcel(int id)
    {
        DataSet dataSet = new DataSet(); //Your Data Set
        if (dataSet.Tables.Count > 0)
        {
            System.Data.DataTable dt1 = new System.Data.DataTable();
            System.Data.DataTable dt2 = new System.Data.DataTable();
            dt1 = dataSet.Tables[0];
            dt2 = dataSet.Tables[1];

            if (dt1.Rows.Count > 1 && dt2.Rows.Count > 1)
            {
                var excel = new Microsoft.Office.Interop.Excel.Application();
                var workbook = excel.Workbooks.Add(true);

                AddExcelSheet(dt1, workbook);
                AddExcelSheet(dt2, workbook);

                //KK-Save the excel file into server path
                string strLocation = "~/Upload/TempExcel/";
                string fName = "Report_" + DateTime.Now.ToString("MMddyyyyHHmmss") + ".xlsx";
                string strPath = Path.Combine(Server.MapPath(strLocation), fName);
                workbook.SaveAs(strPath);
                workbook.Close();

                //KK-Generate downloading link view page
                System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
                Response.ClearContent();
                Response.Clear();
                //Response.ContentType = "application/vnd.ms-excel";  //This is for office 2003
                Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AppendHeader("Content-Disposition", "attachment; filename=YourReport.xlsx");
                Response.TransmitFile(strPath);
                Response.Flush();
                Response.End();

                //KK-Deleting the file after downloading
                if (System.IO.File.Exists(strPath))
                    System.IO.File.Delete(strPath);
            }
        }

        return View();
    }

    /// <summary>
    /// KK-This method add new Excel Worksheet using DataTable
    /// </summary>
    /// <param name="ds"></param>
    private static void AddExcelSheet(System.Data.DataTable dt, Workbook wb)
    {
        Excel.Sheets sheets = wb.Sheets;
        Excel.Worksheet newSheet = sheets.Add();

        int iCol = 0;

        foreach (DataColumn c in dt.Columns)
        {
            iCol++;
            newSheet.Cells[1, iCol] = c.ColumnName;
            newSheet.Cells[1, iCol].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.RoyalBlue);
            newSheet.Cells[1, iCol].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
            newSheet.Cells[1, iCol].Font.Bold = true;
            newSheet.Cells[1, iCol].BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin);
        }

        int iRow = 0;
        foreach (DataRow r in dt.Rows)
        {
            iRow++;

            // add each row's cell data...
            iCol = 0;

            foreach (DataColumn c in dt.Columns)
            {
                iCol++;
                newSheet.Cells[iRow + 1, iCol] = r[c.ColumnName];
                newSheet.Cells[iRow + 1, iCol].BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin);
            }
        }

    }

A: You should check the OpenXML SDK:
http://msdn.microsoft.com/en-us/library/office/gg278328.aspx
Alternatively, you can check the various commercial libraries listed here:
http://polymathprogrammer.com/spreadsheetopenxml/spreadsheetcodelibrariescomparison.pdf
I had a good experience with Aspose Cells.
PS: your code doesn't generate a valid xls file, but html that gets somehow correctly interpreted by excel.

A: You have to use extended libraries which I recommend using EPPlus which is a .net library that reads & writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
Library
and then replace the code
protected void to_excel(object sender, EventArgs e)
    {
        string filepath = Path.Combine(Server.MapPath("~/Files"), fileupload.FileName);
        fileupload.SaveAs(filepath);
        string fname = fileupload.PostedFile.FileName;
        DataTable dt = (DataTable)ReadToEnd(filepath);
        string sFilename = fname.Substring(0, fname.IndexOf("."));
        sFilename = sFilename + ".xlsx";
        MemoryStream ms = DataTableToExcelXlsx(dt, "Sheet1");
        ms.WriteTo(HttpContext.Current.Response.OutputStream);
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
        HttpContext.Current.Response.StatusCode = 200;
        HttpContext.Current.Response.End();
    }

public void toexcel(DataTable dt, string Filename)
    {
        MemoryStream ms = DataTableToExcelXlsx(dt, "Sheet1");
        ms.WriteTo(HttpContext.Current.Response.OutputStream);
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Filename);
        HttpContext.Current.Response.StatusCode = 200;
        HttpContext.Current.Response.End();
    }
    public bool IsReusable
    {
        get { return false; }
    }
    public static MemoryStream DataTableToExcelXlsx(DataTable table, string sheetName)
    {
        MemoryStream Result = new MemoryStream();
        ExcelPackage pack = new ExcelPackage();
        ExcelWorksheet ws = pack.Workbook.Worksheets.Add(sheetName);
        int col = 1;
        int row = 1;
        foreach (DataColumn column in table.Columns)
        {
            ws.Cells[row, col].Value = column.ColumnName.ToString();
            col++;
        }
        col = 1;
        row = 2;
        foreach (DataRow rw in table.Rows)
        {
            foreach (DataColumn cl in table.Columns)
            {
                if (rw[cl.ColumnName] != DBNull.Value)
                    ws.Cells[row, col].Value = rw[cl.ColumnName].ToString();
                col++;
            }
            row++;
            col = 1;
        }
        pack.SaveAs(Result);
        return Result;
    }

I got this solution here


text:
Q: Problems Installing mongodb pecl package: /tmp/pear/temp/mongodb/configure: ./configure.lineno: line 1: syntax error: unterminated quoted string I am building a custom mdocker image bases on (FROM) php:7.0-fpm-alpine image and I need to install the mongodb extention so my Dockerfile has the following content
FROM php:7.0-fpm-alpine
MAINTAINER John Doe <jdoe@example.com>

RUN apk update &&\
    apk add --update --virtual build_deps gcc g++ autoconf make openssl-dev pcre-dev &&\
    docker-php-source extract &&\
    pecl install mongodb && \
    docker-php-ext-enable mongodb && \
    docker-php-source delete && \
    apk del build_deps autoconf gcc g++ make && \
    rm -rf /var/cache/apk/* && \
    rm -rf /tmp/*

But when I build the following image above I get the following output (output from alpine package installs have been ommited):
downloading mongodb-1.3.0.tgz ...
Starting to download mongodb-1.3.0.tgz (927,842 bytes)
.........................................................................................................................................................................................done: 927,842 bytes
417 source files, building
running: phpize
Configuring for:
PHP Api Version:         20151012
Zend Module Api No:      20151012
Zend Extension Api No:   320151012
building in /tmp/pear/temp/pear-build-defaultuserfgCbfi/mongodb-1.3.0
running: /tmp/pear/temp/mongodb/configure --with-php-config=/usr/local/bin/php-config
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for a sed that does not truncate output... /bin/sed
expr: syntax error
sh: 0: unknown operand
expr: syntax error
sh: 0: unknown operand
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ISO C89... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
checking for PHP prefix... /usr/local
checking for PHP includes... -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib
checking for PHP extension directory... /usr/local/lib/php/extensions/no-debug-non-zts-20151012
checking for PHP installed headers prefix... /usr/local/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... no
configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
checking for gawk... no
checking for nawk... no
checking for awk... awk
checking if awk is broken... no
checking whether to enable mongodb support... yes, shared
checking OpenSSL dir for mongodb... yes
checking whether to use system default cipher list instead of hardcoded value... no
checking PHP version... 70022
/tmp/pear/temp/mongodb/configure: ./configure.lineno: line 1: syntax error: unterminated quoted string
ERROR: `/tmp/pear/temp/mongodb/configure --with-php-config=/usr/local/bin/php-config' failed
Removing intermediate container 288e5589f2ca

Which as you can see I get the following error:

/tmp/pear/temp/mongodb/configure: ./configure.lineno: line 1: syntax error: unterminated quoted string

So do you fellows have an idea how to fix this?

A: Your problem is that whoever wrote the pecl script for mongodb tested it on bash and not on sh. So the script is not compatible with sh. Solution is simple, run it through bash
FROM php:7.0-fpm-alpine
MAINTAINER John Doe <jdoe@example.com>

RUN apk update &&\
    apk add --update --virtual build_deps bash gcc g++ autoconf make openssl-dev pcre-dev &&\
    docker-php-source extract &&\
    /bin/bash -lc "pecl install mongodb" && \
    docker-php-ext-enable mongodb && \
    docker-php-source delete && \
    apk del build_deps && \
    rm -rf /var/cache/apk/* && \
    rm -rf /tmp/*

Also for apk del you just need to give the virtual packages name


text:
Q: php error: Class 'Imagick' not found I am getting the error "Class 'Imagick' not found".  Somehow I need to make this library accessible to php. I am using Php 5.2.6 on Fedora 8. my php_info has no mention of ImageMagick.
I have tried: yum install ImageMagick and restarted apache, which didn't work.
I also added extension=imagick.ext to my php.ini file and restarted apache, which didn't work.

A: Debian 9
I just did the following and everything else needed got automatically installed as well.
sudo apt-get -y -f install php-imagick
sudo /etc/init.d/apache2 restart

A: For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update

Remove obsolete things
apt-get autoremove

For the libraries of ImageMagick
apt-get install libmagickwand-dev

for the core class Imagick
apt-get install imagemagick

For create the binaries, and conections in beetween
pecl install imagick

Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini

Restart Apache
service apache2 restart

I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.

A: Install Imagic in PHP7:
sudo apt-get install php-imagick

A: From: http://news.ycombinator.com/item?id=1726074
For RHEL-based i386 distributions:
yum install ImageMagick.i386
yum install ImageMagick-devel.i386
pecl install imagick
echo "extension=imagick.so" > /etc/php.d/imagick.ini
service httpd restart

This may also work on other i386 distributions using yum package manager. For x86_64, just replace .i386 with .x86_64

A: Ubuntu
sudo apt-get install php5-dev pecl imagemagick libmagickwand-dev
sudo pecl install imagick
sudo apt-get install php5-imagick
sudo service apache2 restart

Some dependencies will probably already be met but excluding the Apache service, that's everything required for PHP to use the Imagick class.

A: For MAMP running on Mac OSX
Find out the what version of PHP and install the right version via brew
brew install homebrew/php/php56-imagick

Add the extension by modifying the php.ini template in MAMP

Verify the Imagick

A: On an EC2 at AWS, I did this:
 yum list | grep imagick

Then found a list of ones I could install...
 php -v

told me which version of php I had and thus which version of imagick
yum install php56-pecl-imagick.x86_64

Did the trick. Enjoy!

A: Docker container installation for php:XXX Debian based images:
RUN apt-get update && apt-get install -y --no-install-recommends libmagickwand-dev
RUN pecl install imagick && docker-php-ext-enable imagick
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* || true

A: imagick become not supported in <= php7.0
the Ideal Solution is alternative Package Please find this here
https://github.com/DantSu/php-image-editor

A: Install Base Imagick Repos
Many of these answers are great, if you are using PHP5, but PHP8 offers too many features to just pass up, and imagick is a bit different here.
Install the base imagick repos:
sudo apt-get install php8.0-imagick php8.1-imagick imagemagick php-imagick php-pear php-dev

Install Imagick's Extension into PHP
You may want to omit php8.1-imagick if you are not up to version 8.1 yet. php-pear is where the pecl command lives, so, if that doesn't install correctly, you'll get an error when you need to do the next command...
sudo pecl install imagick

Update PHP.ini
Find your php.ini file with...
php -i | grep  -i php.ini

You may get output like...
Configuration File (php.ini) Path => /etc/php/8.1/cli
Loaded Configuration File => /etc/php/8.1/cli/php.ini

Open this file and add to the end of the file this text: extension=imagick.so.
Restart PHP
Then restart your server.  Any of these will do:
systemctl restart apache2
/etc/init.d/apache2 restart
sudo service apache2 graceful

Check if the Install Worked

*

*See the results of phpinfo() on a web page, which should mention imagick.

*See the results of simulated phpinfo() info calls from the command line with  php -r "echo phpinfo();" | grep 'imagick';.

*See the internal storage of phpinfo() from the command line with php -i | grep 'imagick'.

*See the installed packages containing imagick in the name with dpkg --list | grep 'imagick'.

Note: These are all important, because while I was debugging, I was able to see Imagick installed at lower layers (i.e. with dpkg), but was not seeing it in the higher layers (i.e. with phpinfo(); through webhost).  Cheers.


text:
Q: How to perform a custom JSON deserialization with Jackson that respects a custom annotation? I am trying to deserialize JSON into a custom POJO that I am not able to modify.  That POJO has annotations from a different custom internal serialization framework that I'm not able to use.  How can I create a custom deserializer that will respect these annotations?
Here is an example POJO:
public class ExampleClass {
    @Property(name = "id")
    public String id;

    @Property(name = "time_windows")
    @NotNull
    public List<TimeWindow> timeWindows = new ArrayList<>();

    public static class TimeWindow {
        @Property(name = "start")
        public Long start;

        @Property(name = "end")
        public Long end;
    }
}

So in this case, the deserializer would look for fields in the JSON that correspond to the Property annotations, and use the value in that annotation to decide what field to grab.  If a property doesn't have the Property annotation, it should be ignored.
I have been going through the Jackson docs but haven't been able to find exactly what I need.  Is this a place where an AnnotationIntrospector would be useful?  Or possibly a ContextualDeserializer?
Any pointers in the right direction would be greatly appreciated!

Update: I tried implementing the advice in the comments, but without success.
Here is my initial implementation of the introspector:
class CustomAnnotationInspector : JacksonAnnotationIntrospector () {
    override fun hasIgnoreMarker(m: AnnotatedMember?): Boolean {
        val property = m?.getAnnotation(Property::class.java)
        return property == null
    }

    override fun findNameForDeserialization(a: Annotated?): PropertyName {
        val property = a?.getAnnotation(Property::class.java)
        return if (property == null) {
            super.findNameForDeserialization(a)
        } else {
            PropertyName(property.name)
        }
    }
}

And here is where I actually use it:
// Create an empty instance of the request object.
val paramInstance = nonPathParams?.type?.getDeclaredConstructor()?.newInstance()

// Create new object mapper that will write values from
// JSON into the empty object.
val mapper = ObjectMapper()

// Tells the mapper to respect custom annotations.
mapper.setAnnotationIntrospector(CustomAnnotationInspector())

// Write the contents of the request body into the StringWriter
// (this is required for the mapper.writeValue method
val sw = StringWriter()
sw.write(context.bodyAsString)

// Deserialize the contents of the StringWriter
// into the empty POJO.
mapper.writeValue(sw, paramInstance)

Unfortunately it seems that findNameForDeserialization is never called, and none of the JSON values are written into paramInstance.  Can anybody spot where I'm going wrong?
Thank you!

Update 2: I changed the code slightly, I'm now able to identify the property names but Jackson is failing to create an instance of the object.
Here's my new code:
val mapper = ObjectMapper()

// Tells the mapper to respect CoreNg annotations.
val introspector = CustomAnnotationInspector()
mapper.setAnnotationIntrospector(introspector)

val paramInstance = mapper.readValue(context.bodyAsString,nonPathParams?.type)

My breakpoints in the custom annotation introspector are getting hit.  But I'm getting the following exception:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `app.employee.api.employee.BOUpsertEmployeeRequest` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

Here is the POJO I'm trying to deserialize:
public class BOUpsertEmployeeRequest {
    public BOUpsertEmployeeRequest () { }

    @NotNull
    @Property(name = "xref_code")
    public String xrefCode;

    @Property(name = "first_name")
    public String firstName;

    @Property(name = "last_name")
    public String lastName;

    @Property(name = "email_address")
    public String emailAddress;

    @Property(name = "phone")
    public String phone;

    @Property(name = "address")
    public List<String> address;

    @Property(name = "employment_status")
    public String employmentStatus;

    @Property(name = "pay_type")
    public String payType;

    @Property(name = "position")
    public String position;

    @Property(name = "skills")
    public List<String> skills;

    @Property(name = "gender")
    public String gender;
}

As far as I can tell it has a default constructor.  Anybody have any idea what the problem is?
Thank you!

A: Method hasIgnoreMarker is called not only for fields, but also for the constructor, including the virtual one:

Method called to check whether given property is marked to be ignored. This is used to determine whether to ignore properties, on per-property basis, usually combining annotations from multiple accessors (getters, setters, fields, constructor parameters).

In this case you should ignore only fields, that are not marked properly:
static class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector {
    @Override
    public PropertyName findNameForDeserialization(Annotated a) {
        Property property = a.getAnnotation(Property.class);
        if (property == null) {
            return PropertyName.USE_DEFAULT;
        } else {
            return PropertyName.construct(property.name());
        }
    }

    @Override
    public boolean hasIgnoreMarker(AnnotatedMember m) {
        return m instanceof AnnotatedField
                && m.getAnnotation(Property.class) == null;
    }
}

Example:
class Pojo {
//    @Property(name = "id")
    Integer id;
//    @Property(name = "number")
    Integer number;
    @Property(name = "assure")
    Boolean assure;
    @Property(name = "person")
    Map<String, String> person;
}

String json =
        "{\"id\" : 1, \"number\" : 12345, \"assure\" : true," +
        " \"person\" : {\"name\" : \"John\", \"age\" : 23}}";

ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new CustomAnnotationIntrospector());
Pojo pojo = mapper.readValue(json, Pojo.class);

System.out.println(pojo);

Pojo{id=null, number=null, assure=true, person={name=John, age=23}}

Note: Custom Property annotation should have RetentionPolicy.RUNTIME (same as JsonProperty annotation):
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
    String name();
}

A: I will suggest a different approach:
In the runtime, with the bytecode instrumentation library Byte Buddy and its Java agent, re-annotate the fields with the proper Jackson Annotations. Simply implement the logic via reflection. See the following example:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.dynamic.DynamicType.Builder;
import net.bytebuddy.dynamic.DynamicType.Builder.FieldDefinition.Valuable;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyJsonIgnore {
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyJsonProperty {
  String name();
}

public class Sample {
  public static void main(String[] args) throws JsonProcessingException {
    ByteBuddyAgent.install();
    ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.fromInstalledAgent();
    ByteBuddy byteBuddy = new ByteBuddy();
    AnnotationDescription jsonIgnoreDesc =
        AnnotationDescription.Builder.ofType(JsonIgnore.class).build();

    Builder<Person> personBuilder = byteBuddy.redefine(Person.class);

    for (Field declaredField : Person.class.getDeclaredFields()) {
      Valuable<Person> field = personBuilder.field(ElementMatchers.named(declaredField.getName()));

      MyJsonProperty myJsonProperty = declaredField.getAnnotation(MyJsonProperty.class);
      if (myJsonProperty != null) {
        AnnotationDescription jsonPropertyDesc =
            AnnotationDescription.Builder.ofType(JsonProperty.class)
                .define("value", myJsonProperty.name())
                .build();
        personBuilder = field.annotateField(jsonPropertyDesc);
      }

      MyJsonIgnore myJsonIgnore = declaredField.getAnnotation(MyJsonIgnore.class);
      if (myJsonIgnore != null) {
        personBuilder = field.annotateField(jsonIgnoreDesc);
      }
    }

    personBuilder.make().load(Sample.class.getClassLoader(), classReloadingStrategy);

    Person person = new Person("Utku", "Ozdemir", "Berlin");

    ObjectMapper objectMapper = new ObjectMapper();
    String jsonString = objectMapper.writeValueAsString(person);
    System.out.println(jsonString);
  }
}

class Person {
  @MyJsonProperty(name = "FIRST")
  private String firstName;

  @MyJsonProperty(name = "LAST")
  private String lastName;

  @MyJsonIgnore private String city;

  public Person(String firstName, String lastName, String city) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.city = city;
  }
}

In the example above, I

*

*create MyJsonProperty and MyJsonIgnore annotations and a Person class for the demonstration purpose

*instrument the current Java process with the Byte buddy agent

*create a bytebuddy builder to redefine the Person class

*loop over the fields of the Person class and check for these annotations

*add an additional annotation to each of those fields (on the builder), Jackson's JsonProperty (with the correct field name mapping) and JsonIgnore.

*after being done with the fields, make the new class bytecode and load it to the current classloader using the byte buddy agent's class reloading mechanism

*write a person object to the stdout.

It prints, as expected:
{"FIRST":"Utku","LAST":"Ozdemir"}

(the field city is ignored)
This solution might feel like an overkill, but on the other side, it is pretty generic solution - with a few changes in the logic, you could handle all the 3rd party classes (which you are not able to modify) instead of handling them case by case.


text:
Q: Calling appcmd results in the wrong password being set I'm trying to call appcmd from within Go. The code below shows success, but the password is set to the wrong thing. If I remove the inner quotes (on the second line of main) it works, but then it doesn't work when the password includes spaces! Now WITH the quotes, if I type in cmd.exe the command exactly as it outputs, it works! So what the heck! Why does it work with the quotes directly in cmd but not when called from Go?
I really don't want to be that guy who says you can't use spaces in passwords because I can't figure out why it doesn't work! UGH!
package main

import (
    "bytes"
    "fmt"
    "os/exec"
    "strconv"
    "strings"
    "syscall"
)

func main() {
    iisPath := "C:\\WINDOWS\\sysWOW64\\inetsrv\\"
    callAppcmd(iisPath, "-processModel.password:\"password\"")
}

func callAppcmd(iisPath string, param string) {
    stdOut, _, _, exitCode := runCommand(
        iisPath+"appcmd.exe",
        "set",
        "apppool",
        "/apppool.name:DefaultAppPool",
        param)

    printOut(stdOut)
    printOut(strconv.Itoa(exitCode))
}

func printOut(text string) {
    fmt.Println(text)
}

func runCommand(commands ...string) (string, string, error, int) {
    printOut(strings.Join(commands, " "))
    cmd := exec.Command(commands[0], commands[1:]...)
    cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()

    exitCode := 0

    if exitError, ok := err.(*exec.ExitError); ok {
        exitCode = exitError.ExitCode()
    }

    return out.String(), stderr.String(), err, exitCode
}

Output:
C:\WINDOWS\sysWOW64\inetsrv\appcmd.exe set apppool /apppool.name:DefaultAppPool -processModel.password:"password"
APPPOOL object "DefaultAppPool" changed

0

A: It seems to format the string with backticks is a solution to this, which will not do automatic escaping and can process the quotes properly.
cmd := exec.Command(`find`)
cmd.SysProcAttr.CmdLine = `find "SomeText" test.txt`

Please refer to the below link.
exec with double quoted argument


text:
Q: How to prevent selection of new added element on top of JTable? I have a JTable that contains one row. I'am using multiple selection interval as a selection mode, besides a new row will be inserted on top of the table after 5 seconds from execution. My problem is: When I run the code and select the first row, after 5 seconds a new row is added (this is OK) but I got two selected rows which I do not want because I need to preserve the old selection,that means after adding the new row only the second row is selected. How to resolve this problem using multiple selection interval mode? Here is my code:
   public static void main(String args[]) {
    Object[][] rowData = { { "Hello", "World" }, { "By By", "World" } };
    Object[] columnNames = { "A", "B" };
    JFrame frame = new JFrame("Selecting JTable");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final DefaultTableModel model = new DefaultTableModel(rowData,columnNames);

    JTable jtable = new JTable(model);
    jtable.setSelectionMode(
            ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    JScrollPane scrollPane1 = new JScrollPane(jtable);
    frame.add(scrollPane1, BorderLayout.CENTER);
    frame.setSize(640, 300);
    frame.setVisible(true);
    try {
        Thread.sleep(6000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    model.insertRow(0, rowData[0]);
}

A: You can call removeRowSelectionInterval method right after you insert the row.
Something like:
int newRowIndex = 0;
model.insertRow(newRowIndex, rowData[0]);
jtable.removeRowSelectionInterval(newRowIndex, newRowIndex);


text:
Q: Remove specific dataset and not pop last one added I am trying to remove/hide/pop a certain dataset from my chart when I have more than 2. pop(ing) it only removes the last dataset push(ed). Please see below:
$('#radar2015').on('change', function () {
        var newDataset2 = {
            label: '2016',
            data: [2019, 552, 750, 1280, 1190, 2345, 2123, 534, 1234],
            backgroundColor: 'rgba(0, 183, 253, .25)',
            borderColor: 'rgb(0, 183, 253)',
            borderWidth: 2
        };
        if ($(this).is(':checked')) {
            radarChart.data.datasets.push(newDataset2);
        }
        else {
            radarChart.data.datasets.pop();
        }
        radarChart.update();
    });
    $('#radar2016').on('change', function () {
        var newDataset3 = {
            label: '2017',
            data: [3235, 1125, 2650, 1380, 990, 2345, 123, 1234, 1234],
            backgroundColor: 'rgba(220, 40, 180, .25)',
            borderColor: 'rgb(220, 40, 180)',
            borderWidth: 2
        };
        if ($(this).is(':checked')) {
            radarChart.data.datasets.push(newDataset3);
        }
        else {
            radarChart.data.datasets.pop();
        }
        radarChart.update();
    });

A: You need to use filter() for removing specific values from array
radarChart.data.datasets.filter((item) => {
 // condition for removing dataset
});

Note: filter() returns a new Array everytime

Example from MDN:
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);


text:
Q: Modelling abstract compositions with type-safety I have a structural problem that I could use your help with. I'll explain the abstract problem first, then an example to illustrate the problem.
Consider an abstract class A holding a number of instances of an abstract class B, also assume the following methods in A: void a.foo1(B val) and B a.foo2(). The problem arises when we inherit the classes (A' inherits A and B' inherits B) and demand that the relation A has to B should be the same as A' has to B'. That is, in A': void a.foo1(B' val) and B' a.foo2(). The second method will work, but not the first one (unless we do a unsafe type-cast). In other words, in A': a.foo1(B val) should be illegal unless parameter is an instance of B'. I've tried to model this relationship with generics/templates with little sucess.
This problem arises when making a graph framework. Here we have classes Graph and GraphVertex. (In my actual implementation I overload GraphVertex's delete operator.) In C++:
template<class T> class Graph; // Forward reference.

template<class T> class GraphVertex
{
    public:
        GraphVertex(Graph<T> &graph) : m_graph(graph){}
        virtual ~GraphVertex() {}

        ... // Abstract methods, using T parameter.

        void remove()
        { m_graph.removeVertex(this); }
    protected:
        Graph<T> &m_graph;
}

template<class T> class Graph
{
    public:
        virtual ~Graph(){}

        ...

        virtual GraphVertex<T> *add(T val) = 0;
        virtual void removeVertex(GraphVertex<T> *vertex) = 0; // <--- !!!
}

The problem here is the removeVertex method. Lets say we have implemented the classes with AdjacencyMatrixGraph and AMGVertex. When removing a vertex in the AdjacencyMatrixGraph we need more data than is provided in the abstract base class GraphVertex. We know that the parameter type should be AMGVertex but sending another type as parameter would not generate an (compile-time) error.
To solve this problem I've tried to add a new template parameter, specifying the implemented type. That is:
template<class T, class G> class GraphVertex
{
    public:
        GraphVertex(G &graph) : m_graph(graph) {}
        ~GraphVertex() {}

        ...

        void remove() { m_graph.removeVertex(this); }

    protected:
        G &m_graph;
}

template<class T, class V> class Graph
{
    public:
        virtual ~Graph() {}

        ...

        virtual V *add(T val) = 0;
        virtual void removeVertex(V *vertex) = 0;
}

template<class T> AdjacencyMatrixGraph; // Forward declaration.

template<class T> AMGVertex : public GraphVertex<T, AdjacencyMatrixGraph<T>>
{ ... }

template<class T> AdjacencyMatrixGraph : public Graph<T, AMGVertex<T>>
{ ... }

However, this will not work. It is not possible to use the base class Graph due to circular reference of the base classes.
Graph<int> *p = new AdjacencyMatrixGraph<int>(); // Won't work.

The example above has the same problems in Java with generics.
So, is there anyway to model the relation in a type-safe way? Or am I stuck with casting pointers around?
Thank you for reading!
EDIT:
An example usage of the above could look like:
Graph<int> *someGraph = getSomeGraph();
GraphVertex<int> *newVertex = someGraph->add(3);
...
newVertex->remove();

A: Nice example (+1). The problem is in your OO design, so a type-safe solution is not possible:
Since A' is also of type A, it must follow the contract described in A. Hence foo1 of A' must accept arbitrary B as parameter, not only B'.
The return type of foo2 in A' must be of type B. Since B' is of type B, the   covariant return type B' is allowed for foo2 (since n J2SE 5.0.).
Update:
To solve this dilemma, I would do a redesign, since your A' is not really an A. So either

*

*A' does not inherit from A, or

*A does not contain foo1 at all, or

*A must contain void a.foo1(B' val) instead.

If redesigning is too much a trouble for you, you will have to give up type safety, and, for instance, throw an Illegal Argument Exception if foo1 in A' is called with a B that is not a B'. This is quite similar to how java.util.Collection handles optional operations.

A: "When removing a vertex in the AdjacencyMatrixGraph we need more data than is provided in the abstract base class GraphVertex".
I think you should write an Interface which offers the data that are needed.
If you have two sub-classes with same behavior at one point and the base-class cannot add this bahavior in it's class, because it wont't fit to every subclass you can characterize sub-classes with same bahavior with an extra interface.

A: After some experimenting I have concluded that the general design cannot be changed to be 100% type-safe. However, there are some situations where you can help ensure that the offended method is only called with the correct sub-type.
Taking the graph example, what we need to do is to insure that a sub-class of GraphVertex (in this case AMGVertex) only can access the related sub-class of Graph (that is for AMGVertex, class AdjacencyMatrixGraph). Hence insuring that the correct type is inserted at the removeVertex(GraphVertex *v) method. To do this, a non-public visibility can be used for methods that are accessed by the abstract class GraphVertex. Also the visibility of the constructors of all the sub-types of GraphVertex must be non-public. Of course the constructor of AMGVertex must be visible from AdjacencyMatrixGraph and the removeVertex must be visible from AMGVertex. In C++ this can be done with friends.
template<class T> class GraphVertex
{
    public:
        virtual ~GraphVertex() {}
        void remove() { m_graph.removeVertex(this); }

    protected:
        GraphVertex(Graph<T> &graph) : m_graph(graph) {}
        Graph<T> &m_graph;
}

template<class T> class Graph
{
    friend class GraphVertex<T>;
    public:
        virtual GraphVertex<T> add(T value) = 0;

    protected: // Or private?
        virtual void removeVertex(GraphVertex<T> *v) = 0;
}

template<class T> class AMGVertex : public GraphVertex<T>
{
    friend class AdjacencyMatrixGraph<T>;

    protected: // Or private?
        AMGVertex(AdjacencyMatrixGraph<T> &graph)
        : GraphVertex<T>(graph) {}
}

template<class T> class AdjacencyMatrixGraph : public Graph<T>
{
    public:
        AMGVertex *add(T value) { ... } // Calls AMGVertex's constructor.

    protected: // Or private?
        void removeVertex(GraphVertex<T> *v) // Only visible from this class and through base class.
        { ... }
}

So, AMGVertex can only be created from AdjacencyMatrixGraph, and hence a call to AMGVertex::remove() will always call AdjacencyMatrixGraph::removeVertex(GraphVertex *v) with the correct sub-class as parameter.
It is however still possible to circumvent this, simply by creating a new vertex type with a AdjacencyMatrixGraph as m_graph. This is because the friendship from vertex to graph is in the abstract base-class.
So a 100% type-safe solution is (at least from what I've gathered) not possible.
In Java I believe similar results can be achieved with nested classes (to overcome visibility limitations).
Thank you for the replies! If someone has a better solution, let us know.


text:
Q: regex in Notepad++: remove any number of lines between two given expressions Input file:
[keyword1]
text0
"text1" = "text2"

[text3 keyword1 text4]
[text5]
[keyword2 text6]
"text7" = "text8"
"text9"
"text10" = "text11"

[text12]
"text13" = "text14"
text15

I want to match each 'entry' in full, if it contains a keyword in its first line. What I mean by 'entry in full' is: the first line, which is always in rectangular brackets, and any number of lines below it, basically until we hit the next [ character.
I know how to do it if I knew beforehand how many lines there would be in each 'entry', e.g. for just one line below I'd do something like this:
^\[(.+)(keyword1|keyword2)(.+)\]\r\n(.+)\r\n

But I don't know how to do it with an arbitrary number of lines. I have experimented a bit with the ". matches newline" feature of NP++, but all that got me so far was that the expressions will greedily match the whole file to the end.
Help?
//edit: so, the desired output based on the above example would be (maintaining original line numbers for clarity):
[text5]
[text12]
"text13" = "text14"
text15

//edit#2: cleared up the example input / desired output so that it's clear they are not meant literally. Q has already been answered though :)

A: This pattern should cover all your bases: \n^.*[^][\n]+$
Here's a demo
\n removes any new line characters before the line
^.* is designed to catch the "line x:" part
[^][\n]+$ matches one or more characters that aren't new lines, or square brackets up until the end of the line.

A: You can use the following pattern (with . matches newline checked) and replace with nothing:
\[[^\]]*?(with keyword)[^\]]*?\][^\[]*

Replace in the parenthesis with all the keywords separated by pipes |.
Basically searches for the pattern with square brackets and searching until keyword is found inside the brackets without checking the next line.
Since the . matches newline option is checked, we want to be careful when to greedily match.
Demo in action


text:
Q: how to use axios to sign in with OAuth I just started learning MERN stack last week with Brad Traversy's MERN course: https://www.udemy.com/mern-stack-front-to-back/
In the course, he separated front-end and back-end and use back-end as REST API. In the back-end, he has a POST route (/api/auth) that returns a JWT token and the API is used in the react app axios. Then, the response is used for the value of the header x-auth-token, so that the authentication middleware could help to authenticate. As an computer science newbie working as an internship right now, I am required to make a web app for my company for internal use which uses slack OAuth for authentication. Now here is the problem: when I use axios, the response is some HTML codes like this:
GET https://slack.com/oauth/authorize?
scope=identity.basic,identity.email,identity.avatar&client_id=48321353297.675712837139 in postman, result:

<!DOCTYPE html>
<html lang="en-US" class="">
    <head>
        <script type="text/javascript">
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
    'gtm.start': Date.now(),
    'event' : 'gtm.js',
    'secure_page' : false,
});
var firstScript = document.getElementsByTagName('script')[0];
var thisScript = document.createElement('script');
thisScript.async = true;
thisScript.src = '//www.googletagmanager.com/gtm.js?id=GTM-KH2LPK';
firstScript.parentNode.insertBefore(thisScript, firstScript);
</script>
        <script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(e) {
    var gtmDataLayer = window.dataLayer || [];
    var gtmTags = document.querySelectorAll('*[data-gtm-click]');
    var gtmClickHandler = function(c) {
        var gtm_events = this.getAttribute('data-gtm-click');
        if (!gtm_events) return;
        var gtm_events_arr = gtm_events.split(",");
        for(var e=0; e < gtm_events_arr.length; e++) {
            var ev = gtm_events_arr[e].trim();
            gtmDataLayer.push({ 'event': ev });
        }
    };
    for(var g=0; g < gtmTags.length; g++){
        var elem = gtmTags[g];
        elem.addEventListener('click', gtmClickHandler);
    }
});

        </script>
        <script type="text/javascript">
(function(e,c,b,f,d,g,a){e.SlackBeaconObject=d;
e[d]=e[d]||function(){(e[d].q=e[d].q||[]).push([1*new Date(),arguments])};
e[d].l=1*new Date();g=c.createElement(b);a=c.getElementsByTagName(b)[0];
g.async=1;g.src=f;a.parentNode.insertBefore(g,a)
})(window,document,"script","https://a.slack-edge.com/bv1-6-8cacda2/slack_beacon.bc058f2eca7b7d633d5a.min.js","sb");
window.sb('set', 'token', '3307f436963e02d4f9eb85ce5159744c');
sb('set', 'user_' + "batch", "signup_api");sb('set', 'user_' + "created", "2019-06-03");sb('set', 'user_id', "UK781P40Y");
sb('set', 'name_tag', "wemine" + '/' + "klaus.chau");
window.sb('track', 'pageview');
</script>
        <meta charset="utf-8">
        <script type="text/javascript">window.location.href = "https:\/\/slack.com\/oauth\/authorize?scope=identity.basic,identity.email,identity.avatar&client_id=48321353297.675712837139&tracked=1";</script>
    </head>
    <body></body>
</html>

I think the problem is that it is sending me the 'confirm login page' instead of the jwt token I needed from the redirectURI.
Would it be possible for me to implement like what Brad did in the course even though I am not logging in with password and email?
Thanks
Resources that could be referenced:
https://github.com/bradtraversy/devconnector_2.0/blob/master/routes/api/auth.js
https://github.com/bradtraversy/devconnector_2.0/blob/master/client/src/actions/auth.js
https://github.com/bradtraversy/devconnector_2.0/blob/master/client/src/reducers/auth.js

A: You cannot Ajax(axios or request or XMLHttprequest) to get the OAuth or any external auth tokens. Because here is the flow,

*

*You click a login button

*Goes to the passport(or any auth) route.

*The auth provider redirects to the original OAuth provider(like fb, google, slack etc)

*You login THERE, in THEIR SITE.

*It redirects back to another route of your passport application that decrypts the request body and gets the token.

*It returns the token.

So basically for the redirection (step 3) to work, you need to redirect or a href to the passport route(which will be a GET route) which will inturn redirect to google/fb/slack.
Hope you understood why you cannot use Ajax to fetch from external authentication providers.


text:
Q: change a column from nvarchar like YYYYMM to date type getting last day of month I have a table called TABLE1 with a column called COL1 which values are nvarchar like this 202001. (YYYYMM)
I want to change the format of COL1 from nvarchar to date type (YYYY-MM-DD) getting also the last day of month.
From a nvarchar like 202001 then I want as ouput 2020-01-31 in date type with day = 31 because is last day of january.
I already tried with:
alter table TABLE1
alter column COL1  Date;
But got following error:
"Conversion failed when converting date and/or time from character string."


text:
Q: How to use movement for classical music with Apple Music? Apple Music groups tracks in classical music albums by work and movement, which is great. Here's an example:

When I add albums to my library, however, the grouping is lost. Here is how that same album appears in my library:

According to this MacWorld article it is possible to edit the tracks to specify that they include work and movement grouping, however, this requires that one input the information manually, which is tedious and should be unnecessary considering that information is clearly there in Apple Music.
Am I missing something? Is it possible to preserve this grouping when adding classical music albums to iTunes from Apple Music?

A: Only the tedious method. It is especially inconvenient on iOS. I use the Cesium player on iOS to better sort by Genre and Composer.


text:
Q: Dynamic Tabs with Global behaviourSubject? I'm trying to hide and show tabs depending on where you are in the Ionic app. I'm currently trying to use a global boolean behaviourSubject to achieve this. I have the following code which has been trimmed for brevity.
In my provider/service globals.ts I have the following:
@Injectable()
export class AppGlobals {
    public showActionTabs:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

    setShowActionTabs(val){
        this.showActionTabs.next(val);
    }

    getShowActionTabs(): Observable<boolean>{
        return this.showActionTabs.asObservable();
    }
}

Then in my tabs.ts I have:
export class TabsPage {
    public showTabs: boolean;

    constructor(private _appGlobals: AppGlobals) {
        this._appGlobals.getShowActionTabs().subscribe((value:boolean) => {
            this.showTabs = value;
            console.log("new val: ", value, this.showTabs);
        });
    }

    ngOnInit() {
        setInterval(function() {
            console.log("inside init:", this.showTabs);
        }, 5000);
    }
}

In my products.ts page I have:
export class ProductsPage {

    constructor(private _appGlobals: AppGlobals) {}

    ngOnInit() {
        this._appGlobals.setShowActionTabs(true);
    }
}

In my product-details.ts I have:
export class ProductDetails {

    constructor(private _appGlobals: AppGlobals) {}

    ngOnInit() {
        this._appGlobals.setShowActionTabs(false);
    }
}

Then finally in my tabs.html I have:
<ion-tabs class="side-tabs">
    <ion-tab *ngIf="showTabs" (ionSelect)="toggleSearch()" tabTitle="Search" tabIcon="custom-search"></ion-tab>
    <ng-container *ngFor="let tab of tabs; let i = index; trackBy: trackByFn">
        <ion-tab *ngIf="!tab.hasAction" tabTitle="{{ tab.title }}" tabIcon="{{ tab.icon }}"></ion-tab>
    </ng-container>
    <ion-tab *ngIf="showTabs" (ionSelect)="toggleCompare()" tabTitle="Compare" tabIcon="custom-compare"></ion-tab>
</ion-tabs>

However when I am navigating between the pages, the tabs still do not hide and show accordingly.
Can someone explain where I'm going wrong? My understanding of this method was that the behaviourSubject takes the values from other classes/components and then allows that to be applied somewhere else.
Thanks in advance, it's very appreciated. If you need more detail, please ask.
EDIT
My question code has been updated to reflect the answer from @Bhetzie. Currently the tabs still are not showing or hiding although this.showTabs is being set correctly via the behaviourSubject as far as I can tell.
OUTCOME
So after some extensive digging I came to the conclusion that the ion-tabs were the culprit to the global behaviourSubject/ngIf seemingly not working together. I ripped them out and made my own tabs using the side menu template provided by Ionic. This fixed my issue and now the tabs swap out dynamically.

A: I think you are missing a getter for the showActionTabs.
It is always going to set showTabs as whatever the behavior subject is initialized as.
You can try:
service globals.ts
getShowActionTabs(): Observable<boolean>{
        return this.showActionTabs.asObservable();
    }

tabs.ts
this._appGlobals.getShowActionTabs().subscribe((value:boolean) => { this.showTabs = value;
    console.log(value);
});


text:
Q: Is there a polynomial of degree 2 such that $f (0) = 1, f (2) = 2$ and $f (3) = 2$? I was wondering if there exist a polynomial whith these.
I've trying, but since I only started to see polynomials I don't how to get to the correct answer
Any help?

A: Yes, there is.  Write your polynomial as $ax^2+bx+c$ and substitute in the values, giving
$$a0^2+b0+c=1\\a2^2+b2+c=2\\a3^2+b3+c=2$$
The first gives $c=1$, leaving you two equations in two unknowns to solve.

A: Yes, it is
$$P(x)=\frac{(x-2)(x-3)}{(1-2)(1-3)}\color{red}{f(1)}$$
$$+\frac{(x-1)(x-3)}{(2-1)(2-3)}\color{red}{f(2)}$$
$$+\frac{(x-1)(x-2)}{(3-1)(3-2)}\color{red}{f(3)}$$
$$=\frac 12(x^2-5x+6)-2(x^2-4x+3)+(x^2-3x+2)$$

A: Hint: Solve the system of equations
$$f(0)=c=1$$
$$f(2)=4a+2b+1=2$$
$$f(3)=9a+3b+1=2$$ in $$a,b,c$$


text:
Q: Random Walk Martingale Proof Let $S_n$ be a random walk with $P(S_{n+1}=S_n+1|S_n)=p<\frac{1}{2}$ and $1-p=q=P(S_{n+1}=S_n-1|S_n)$.
Let $\tau=min(n:S_n=0)$
Prove that $S_n-(p-q)n)^2-n(1-(p-q)^2)$ is a martingale.
How do we go about proving whether a certain random variable is a martingale?

A:
"How do we go about proving whether a certain random variable is a martingale?"

Call your random variable $X = (X_n)_n$.
You need to show that $E(X_{n+1} \mid X_1, ..., X_n) = X_n$. Note that this is equivalent to $E( X_{n+1} - X_n \mid X_1, ..., X_n ) = 0$.
I would suggest looking at $X_{n+1} - X_n$, and expanding some squares. Also, you can replace the conditioning on $\sigma(X_1, ..., X_n)$ by $\sigma(S_1, ..., S_n)$, since by knowing $X_1, ..., X_n$ you can determine $S_1, ..., S_n$.
Now you just need to calculate some things like $E(S_{n+1}^2 \mid S_n)$ and $E(S_{n+1} \mid S_n)$.


text:
Q: Reference request: What is the definition of a quasi-finite morphism of algebraic stacks? Is there a generally accepted definition of quasifinite morphisms of Artin stacks?
It's not in the stacks project. I also checked LMB and Olsson's books but couldn't find a definition, though it's possible I didn't look hard enough.
I know if the morphism is representable then there's the obvious definition in terms of pullbacks being quasi-finite, but what about the general case?
References would be appreciated!

A: A definition is given in the Stacks project (it comes from a paper by David Rydh), see Tag 0G2L.

A: See
Angelo Vistoli
Intersection theory on algebraic stacks and on their moduli spaces
Inventiones mathematicae (1989)
Volume: 97, Issue: 3, page 613-670
EUDML  |  Intersection theory on algebraic stacks and on their moduli spaces.
More precisely, Definition (1.8) : the morphism is of finite type and the geometric fibers are finite, in the sense that they admit a finite atlas.


text:
Q: Why isn't tmplItem() giving my data back? If I had any, I'd be tearing my hair out at this one.
Basically, why isn't this bit of jQuery templating working?
http://jsfiddle.net/PTBak/1/
I've used templating before and I can't see the difference / why it's not returning the data.

A: This is because you are trying to access your tmplItem on something that was not generated by tmpl : the #content container. You are putting your generated content inside it and the #content element doesn't have anything to do with the generated content.
The best approach is to wrap your whole template into a single element and access that element to get the tmplItem(). In your example, I wrapped your template into a #myItem div and access this element instead because it was generated by jQuery.tmpl
http://jsfiddle.net/PTBak/3/


text:
Q: Why are mobs spawning at light level 7 in my house? (Minecraft v. 1.12.1) I built a sky mansion, but sometimes mobs spawn inside. Light levels are all above 7 where there are like three or four of them. All other fields are up to 13 light.
It happens very rarely, maybe once every 10 days, but if it's a creeper, once is too much.
Any ideas as to why this is happening?

A: If the block that they're spawning at is next to a wall, light up the other side of the wall. Grouped spawning mobs only need one of the blocks in the spawn area to be less than 7 to spawn and will sometimes spawn on other sides of walls.
If they are not spawning next to a wall, or the opposite side of the wall is solid and not hollow, check the lighting again - they can spawn at light level 7, but no higher.


text:
Q: Add multiple columns based on conditions I am trying to add multiple new columns based on a condition but when I run the code for making a new column, the last new column made from the conditions is replaced.
new_df <- df %>% mutate(dat1_dat2_new = case_when(
  dat1 == 0 & dat2 == 0 ~ 'TW',
  dat1 == 0 & dat2 == 1 ~ 'FS',
  dat1 == 1 & dat2 == 0 ~ 'FW',
  dat1 == 1 & dat2 == 1 ~ 'TS'))
new_df$dat1_dat2_new

but when I run
new_df <- df %>% mutate(dat3_dat4_new = case_when(
      dat3 == 0 & dat4 == 0 ~ 'TW',
      dat3 == 0 & dat4 == 1 ~ 'FS',
      dat3 == 1 & dat4 == 0 ~ 'FW',
      dat3 == 1 & dat4 == 1 ~ 'TS'))
    new_df$dat3_dat4_new

it replaces new_df$dat1_dat2_new

A: In the second code, you are replacing the original new_df with the new new_df. You never actually added a new column after dat1_dat2_new. You need - new_df <- new_df %>% rest of the code in the second case.
Also, a simpler way would be to create both new columns in a single mutate -
new_df <- df %>%
  mutate(
    dat1_dat2_new = case_when(
      dat1 == 0 & dat2 == 0 ~ 'TW',
      dat1 == 0 & dat2 == 1 ~ 'FS',
      dat1 == 1 & dat2 == 0 ~ 'FW',
      dat1 == 1 & dat2 == 1 ~ 'TS'
    ),
    dat3_dat4_new = case_when(
      dat3 == 0 & dat4 == 0 ~ 'TW',
      dat3 == 0 & dat4 == 1 ~ 'FS',
      dat3 == 1 & dat4 == 0 ~ 'FW',
      dat3 == 1 & dat4 == 1 ~ 'TS'
    )
  )


text:
Q: DI in layered application with isolation Suppose that we have three layers; UI, Business, Data. We are using DI. I don't wan't Data layer to be accessible from UI.

The problem is about DI registration of Data layer. Composition root is in UI and I don't wan't to have any reference to Data there. I've found this answer. As I understand, we should reference to all layers and think they are libraries not layers. This way I can specify that my Business layer use Data layer or anything else that I want. After all this is why DI is around.
It's correct, but there is a problem! We shouldn't use Data layer at UI. But once a developer accidentally referenced from UI to Data, and another one injected something from Data layer to a UI class directly. So he skipped the Business layer that I never want.
How can I handle such situations? I'd like to have some limitations, but on the other hand I want the DI flexibility.
Of course some folks believe that we can have a separate library just for dependency registration.

What is the best pattern here?

A: The answer you linked to has two answers that explain that having the composition root and the UI layer in the same assembly is not a problem:

*

*You're mistaking logical layers with physical boundaries: assemblies are deployment units and can contain multiple logical layers. Layers can even be spread across assemblies. Think about the 4+1 view. The composition root might be in the same assembly as your UI, but it is not in the UI layer and although the Composition Root depends on the Data Access Layer, the UI layer does not (although its assembly does).

*Having code reviews is important for the quality or your software and the sharing of knowledge within the team. If you're not doing code reviews right now, you should definitely start doing them. Those code reviews can include checks for architectural guidelines, such as the rule you described in your question.

*While assembly separation gives you compile-time support, most architectural rules can't be checked by the compiler. Besides, the compiler will not complain when a developer adds a reference to the DAL assembly. Developers will always find ways to break the rules. Again, code reviews help a lot. And additionally, as an architect, you can start using tools such as NDepend to automate verifying some architectural rules. But when you apply constructor injection, unit tests can be used as well, since dependencies can be found by simply reflecting over the constructors of types in your UI layer.

But if you think this is a problem, why don't you just move the UI layer in its own assembly? The startup assembly doesn't need to have the UI layer! If you create a Windows Forms application, move all the Forms to their own assembly. If you're creating a ASP.NET MVC application, move the Controllers and views to their own assembly. Depending on the type of application you're building, you will have to apply certain tricks to get this working, but for most project types in .NET this is possible.
The real question is, is this worth the trouble? If you want this in order to prevent having to do code reviews, you are fooling yourself.


text:
Q: How to join/align axes for a perfect corner in matplotlib? I am using the following matplotlib rc parameter file, but I find that the axes are not fully closed or joined to form a perfect corner as shown in the figure:

The matplotlibrc parameter file is given below:
lines.linewidth : 1.0               # Line width (in points).
lines.linestyle : -                 # Line style.
lines.color : blue                  # Line color.

font.family : serif
font.serif : Palatino, Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Charter, serif

text.color : black
text.usetex : true

axes.facecolor : FFFFFF         # axes background color
axes.edgecolor : 000000         # axes edge color
axes.linewidth : 1.0            # edge linewidth
axes.grid : true                # display grid or not
axes.titlesize : large          # fontsize of the axes title
axes.labelsize : 9              # fontsize of the x any y labels
axes.labelweight : normal       # weight of the x and y labels
axes.labelcolor : 000000
axes.axisbelow : true
axes.formatter.limits : -7, 7
axes.color_cycle : E41A1C, 377EB8, 4DAF4A, 984EA3, FF7F00, FFFF33, A65628, F781BF, 999999       # color cycle for plot lines
polaraxes.grid : true           # display grid on polar axes
axes3d.grid : true              # display grid on 3d axes

xtick.major.size : 4            # Major tick size (in points).
xtick.minor.size : 2            # Minor tick size (in points).
xtick.major.width : 1           # Major tick width (in points).
xtick.minor.width : 1           # Minor tick width (in points).
xtick.major.pad : 6             # Distance to major tick label (in points).
xtick.minor.pad : 6             # Distance to the minor tick label (in points).
xtick.color : 000000            # Tick label colors.
xtick.labelsize : 8             # Tick label font size (in points).
xtick.direction : in            # Tick direction

ytick.major.size : 4            # Major tick size (in points).
ytick.minor.size : 2            # Minor tick size (in points).
ytick.major.width : 1           # Major tick width (in points).
ytick.minor.width : 1           # Minor tick width (in points).
ytick.major.pad : 6             # Distance to major tick label (in points).
ytick.minor.pad : 6             # Distance to the minor tick label (in points).
ytick.color : 000000            # Tick label colors.
ytick.labelsize : 8             # Tick label font size (in points).
ytick.direction : in            # Tick direction

grid.color : 999999             # Grid color.
grid.linestyle : :              # Grid line style.
grid.linewidth : 0.5            # Grid line width (in points).
grid.alpha : 1.0                # Grid line transparency.

legend.fancybox : true      # if true, use a rounded box for the
legend.isaxes : true
legend.numpoints : 1            # the number of points in the legend line
legend.fontsize : 9
legend.borderpad : 0.5          # border whitespace in fontsize units
legend.markerscale : 1.0        # the relative size of legend markers vs. original
legend.labelspacing : 0.5       # the vertical space between the legend entries in fraction of fontsize
legend.handlelength : 2.        # the length of the legend lines in fraction of fontsize
legend.handleheight : 0.7       # the height of the legend handle in fraction of fontsize
legend.handletextpad : 0.8      # the space between the legend line and legend text in fraction of fontsize
legend.borderaxespad : 0.5      # the border between the axes and legend edge in fraction of fontsize
legend.columnspacing : 2.       # the border between the axes and legend edge in fraction of fontsize
legend.shadow : false
legend.frameon : true           # whether or not to draw a frame around legend
legend.scatterpoints : 1        # number of scatter points

Have I set something wrong in the settings or is there another way of properly aligning the axes?
Update
It seems that the default settings have the same problem as shown below:

A: Which Version of Matplotlib are you using?
This appears to be a known bug in Matplotlib Version 1.3.1, which is still the standard one for my Ubuntu. I upgraded to 1.4 and now everything works fine. You have to manually (more or less) build Version 1.4, however...


text:
Q: Why are empty and non empty TikZ matrix cells not equally placed? I wanted to draw an almost empty matrix of nodes with TikZ similar to the left most one below. All nodes would have same size (through minimum width and minimum height) and no separation between columns and rows. But when I include a text which needs two lines I obtain the central matrix and, if the text just needs one line the right most one. I don't know what's wrong. Do you? I'm using CVS version of TikZ.
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{matrix}

\tikzset{
proces/.style={draw, minimum height=15mm, minimum width=2cm, outer sep=0pt, text width=1.5cm, align=center}
}

\begin{document}
\begin{tikzpicture}

\matrix (A) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & \\
 & \\
};

\begin{scope}[xshift=4.5cm]
\matrix (A) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & OOO OOO \\
 & \\
};
\end{scope}

\begin{scope}[xshift=9cm]
\matrix (B) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & A \\
 & \\
};
\end{scope}

\end{tikzpicture}
\end{document}

A: What's happened here is that the matrix of nodes has quietly set anchor=base on each of your matrix subnodes.  The problem with this is that when the node has text in it then the base anchor is not in the same place as the center anchor.  So your nodes are lining up so that their bases are in a line but this means that their centers (and thus their boundary) are not.
The simplest solution is to put nodes={anchor=center}, or you could add it to the proces style, after the matrix of nodes to revert this change.
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{matrix}

\tikzset{
  process base/.style={
    draw,
    minimum height=15mm,
    minimum width=2cm,
    outer sep=0pt,
    text width=1.5cm,
    align=center
  }
}

\begin{document}
\begin{tikzpicture}[
  proces/.style={
    process base,
  }
]

\matrix (A) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & \\
 & \\
};

\begin{scope}[xshift=4.5cm]
\matrix (B) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & OOO OOO \\
 & \\
};
\end{scope}

\begin{scope}[xshift=9cm]
\matrix (C) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & A \\
 & \\
};
\end{scope}

\foreach \lbl in {A,B,C} {

\draw[line width=3mm,green] (\lbl-1-1.base) -- (\lbl-1-2.base);
\draw[ultra thick,red] (\lbl-1-1.center) -- (\lbl-1-2.center);

}
\end{tikzpicture}

\begin{tikzpicture}[
  proces/.style={
    process base,
    anchor=center,
  }
]

\matrix (A) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & \\
 & \\
};

\begin{scope}[xshift=4.5cm]
\matrix (B) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & OOO OOO \\
 & \\
};
\end{scope}

\begin{scope}[xshift=9cm]
\matrix (C) [matrix of nodes,nodes=proces,nodes in empty cells] {
 & A \\
 & \\
};
\end{scope}

\foreach \lbl in {A,B,C} {

\draw[line width=3mm,green] (\lbl-1-1.base) -- (\lbl-1-2.base);
\draw[ultra thick,red] (\lbl-1-1.center) -- (\lbl-1-2.center);

}

\end{tikzpicture}

\end{document}


text:
Q: How to remove an alphabet from a list of numbers in Matlab? I have a list of numbers in a column vector. In those numbers i have an alphabet M which appears at random intervals..
this link How to delete zero components in a vector in Matlab?
display how to remove the Zero, i tried to adapt how to remove M, but in vain.!
How do I replace this M by 0?
I tried this code but to no avail.!
I called all my sample data N.

N=[4.6
  6.7
  4.1
  3.1
   M
  2.6]
N(N==M) = [];
  i also tried this code
  sample=N(N~=M);

My real data is loaded from a text file:
filename='x.txt';
N=importdata(filename)

A: The problem is that your M items are never being imported by importdata in the first place!
importdata is the wrong function to use for complex data. If you put this in x.txt:

4.6
  6.7
  4.1
  3.1
  M
  2.6

Then the output of N=importdata(filename) is simply the first four values. It can't handle the M.  You should notice this, because the size of N should be smaller than the number of values in your file.
Instead, use textscan, telling it that M is an invalid item and should be replaced with 0:
fid = fopen('x.text');
N = textscan(fid,'%f','treatAsEmpty',{'M'},'EmptyValue',0);
fclose(fid);
N{1}

ans =

    4.6000
    6.7000
    4.1000
    3.1000
         0
    2.6000

Additional note: it's probably a bad idea to put 0 in where you mean this value was bad, because it will affect the results you get from other functions. I would set EmptyValue to NaN instead.

A: Assumes that you do not really have numbers, but numbers as a string. This means that you can use the function strrep.
try:
A = ['1 2 3 4 M 6'];
strrep(A,'M', '0');

A: Hey unfortunately you haven't provided what kind of datatype you have in N. As given by OP double doesn't make sense, because M is not a valid double value as far as I know.
So I assume that you have a cell array containing doubles or strings placed in cells. If so this code works:
N={ 1 2 2 42 5 12 'M' 'm' 123}
alphabet=['A':'Z','a':'z'];

for k=1:numel(N)
    if ismember(N{k},alphabet)
        N{k}=0;
    end
end
display(N)

resulting in following console output:
input
N =

    [1]    [2]    [2]    [42]    [5]    [12]    'M'    'm'    [123]

output
N =

    [1]    [2]    [2]    [42]    [5]    [12]    [0]    [0]    [123]

You can change what the replacement is in the if statement.
The code can be modified to fit a string as input:
N=['1 2 2 42 5 12 M m 123']
alphabet=['A':'Z','a':'z'];

for k=1:numel(N)
    if ismember(N(k),alphabet)
        N(k)='0';
    end
end
display(N)


text:
Q: Front Product List Grid in Custom Module I need to display a collection in the front-end of magento like the grid shown to list products for a particular category by default.
I want the grid in a custom module to display a custom collection with all the features of pagination and sorting.
Please help me.

A: In app/design/frontend/base/default/layout/catalog.xml, you have something like :
<catalog_category_default translate="label">
    Catalog Category (Non-Anchor)
    <reference name="left">
        <block type="catalog/navigation" name="catalog.leftnav" after="currency" template="catalog/navigation/left.phtml"/>
    </reference>
    <reference name="content">
        <block type="catalog/category_view" name="category.products" template="catalog/category/view.phtml">
            <block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
                <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
                    <block type="page/html_pager" name="product_list_toolbar_pager"/>

                </block>
                <action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
                <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
                <action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
                <action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
                <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
                <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
            </block>
        </block>
    </reference>
</catalog_category_default>

It sets everything for a list of product, you can reuse it with the app/design/frontend/base/default/template/catalog/product/list.phtml and app/design/frontend/base/default/template/catalog/category/view.phtml... Additionnaly, there is layer/view.phtml that can be of an interest for you but with so few information, it is difficult to give an accurate answer.


text:
Q: Memory encryption and memory zero unknowns- assist my understanding I want to protect my users data as much as possible! In this scenario I'm trying to protect data-in-use/data-in-memory against certain memory attacks or at least make it more difficult for nefarious people to get at my users' data.
I do not really understand how Flutter & Dart handle memory or really any language for that matter. So I'm looking for some insight, direction or confirmation in what I'm trying to do here without needing a masters in computer science. While I'm using Flutter/Dart this is also a generalized question.
My modus operandi here is simple, when done with some sensitive data I want to:

*

*Encrypt data for memory zero

*Zero all encrypted memory

Does this do what I intend?
If this does not do what I intend or is pointless in any way, please explain why.
/*
    - Symmetric encryption
    - Encryption before putting data into transit
    - This symmetric key and nonce are asymmetrically encrypted with authorized users public keys
    - Authorized users can decrypt the key
    - Sensitive data is encrypted then zeroed
  */
  Future<String> symmetricallyEncrypt(Sale sale) async {
    String saleJson = jsonEncode(sale);
    final symmetricKey = await secureStorage.read(key: kSSKeySymmetric);
    final symmetricNonce = await secureStorage.read(key: kSSKeySymmetricNonce);
    final symmetricCypher = AesCrypt(padding: PaddingAES.pkcs7, key: symmetricKey!);
    final encryptedSale = symmetricCypher.gcm.encrypt(inp: saleJson, iv: symmetricNonce!);

    /* --- ENCRYPTED ZERO --- */
    encryptedZero(saleJson);
    encryptedZero(symmetricKey);
    encryptedZero(symmetricNonce);
    encryptedZero(symmetricCypher.toString());

    return encryptedSale;
  }

  /*
    Encryption zero method
      - Encrypts shredding input
      - Zeros all inputs
  */
  Future<void> encryptedZero(String shredding) async {
    String? asymmetricPublicZeroKey = await secureStorage.read(key: kSSKeyMemoryZeroAsymmetricPublic);
    String encryptedShredding = RSAPublicKey.fromPEM(asymmetricPublicZeroKey!).encrypt(shredding);
    asymmetricPublicZeroKey = '';
    encryptedShredding = '';
    shredding = '';
  }

A: I get what you're asking but think it's not the right way to think about the security of your memory.
What's the threat actor - another process? The operating system? The root user?
If you don't trust the root user, the OS, and the hardware, you've already lost.
If you have to trust them, then what else is your threat actor? You have to trust your application. So the only other things are other applications running on the same system.
The operating system prevents other applications from reading your memory space (SEG FAULT, etc). And the OS zeros out your application's memory pages before passing them to another process.
But that's not the whole story - read https://security.stackexchange.com/questions/29019/are-passwords-stored-in-memory-safe for even more details.