text:
Q: Changing Session Variables via Query String Parameters We have a calendar at www.CrownCountry.com/calendar/index.aspx. The header control contains a dropdown box and a button that lets you select/filter the categories that are displayed. I believe this is handled with a session variable. We would like to be able to link from other sites and pass query string that would allow us to send to the site where the category we choose is already displayed/redirected.
Here is the header.ascx.cs code:
     //Using Statements @1-9FD2A1C9
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Globalization;
using calendar;
using calendar.Data;
using calendar.Configuration;
using calendar.Security;
using calendar.Controls;

//End Using Statements

namespace calendar.header{ //Namespace @1-D4456FBF

//Forms Definition @1-5B635B51
public partial class headerPage : System.Web.UI.UserControl
{
//End Forms Definition

//Forms Objects @1-79CEC0F7
    protected HMenuDataProvider HMenuData;
    protected NameValueCollection HMenuErrors=new NameValueCollection();
    protected bool HMenuIsSubmitted = false;
    protected FormSupportedOperations HMenuOperations;
    protected System.Resources.ResourceManager rm;
    protected string headerContentMeta;
    protected string PageStyleName;
    protected NameValueCollection PageVariables = new NameValueCollection();
//End Forms Objects

//Page_Load Event @1-55207E05
private void Page_Load(object sender, System.EventArgs e)
{
//End Page_Load Event

//Page_Load Event BeforeIsPostBack @1-C7FCE06D
    PageItem item=PageItem.CreateFromHttpRequest();
    if (!IsPostBack)
    {
            PageDataProvider PageData=new PageDataProvider();
            PageData.FillItem(item);
            html_header.Text=item.html_header.GetFormattedValue();
            HMenuShow();

    }
//End Page_Load Event BeforeIsPostBack

//Label html_header Event BeforeShow. Action Custom Code @31-2A29BDB7
    // -------------------------
    html_header.Text = CommonFunctions.str_calendar_config("html_header");
    // -------------------------
//End Label html_header Event BeforeShow. Action Custom Code

//Page_Load Event tail @1-FCB6E20C
}
//End Page_Load Event tail

//Page_Unload Event @1-72102C7C
private void Page_Unload(object sender, System.EventArgs e)
{
//End Page_Unload Event

//Page_Unload Event tail @1-FCB6E20C
}
//End Page_Unload Event tail

//Record Form HMenu Parameters @65-E37A0CD0
    protected void HMenuParameters()
    {
        HMenuItem item=HMenuItem.CreateFromHttpRequest();
        try{
            HMenuData.Seslocale = TextParameter.GetParam("locale", ParameterSourceType.Session, "", null, false);
        }catch(Exception e){
            HMenuErrors.Add("Parameters","Form parameters: " + e.Message);
        }
    }
//End Record Form HMenu Parameters

//Record Form HMenu Show method @65-8D502A38
    protected void HMenuShow()
    {
        if(HMenuOperations.None)
        {
            HMenuHolder.Visible=false;
            return;
        }
        HMenuItem item=HMenuItem.CreateFromHttpRequest();
        bool IsInsertMode=!HMenuOperations.AllowRead;
        item.yearHref = "year.aspx";
        item.monthHref = "index.aspx";
        item.weekHref = "week.aspx";
        item.lbl_dayHref = "day.aspx";
        item.searchHref = "search.aspx";
        item.add_eventHref = "events.aspx";
        item.RegLinkHref = "registration.aspx";
        item.loginHref = "login.aspx";
        item.profileHref = "profile.aspx";
        item.administration_linkHref = "admin/index.aspx";
        item.logoutHref = "index.aspx";
        item.logoutHrefParameters.Add("Logout",System.Web.HttpUtility.UrlEncode((1).ToString()));
        HMenuErrors.Add(item.errors);
//End Record Form HMenu Show method

//Record Form HMenu BeforeShow tail @65-3E6C21EA
        HMenuParameters();
        HMenuData.FillItem(item,ref IsInsertMode);
        HMenuHolder.DataBind();
        HMenuyear.InnerText=Resources.strings.cal_year;
        HMenuyear.HRef = item.yearHref+item.yearHrefParameters.ToString("None","", ViewState);
        HMenumonth.InnerText=Resources.strings.cal_month;
        HMenumonth.HRef = item.monthHref+item.monthHrefParameters.ToString("None","", ViewState);
        HMenuweek.InnerText=Resources.strings.cal_week;
        HMenuweek.HRef = item.weekHref+item.weekHrefParameters.ToString("None","", ViewState);
        HMenulbl_day.InnerText=Resources.strings.cal_day;
        HMenulbl_day.HRef = item.lbl_dayHref+item.lbl_dayHrefParameters.ToString("None","", ViewState);
        HMenusearch.InnerText=Resources.strings.cal_search;
        HMenusearch.HRef = item.searchHref+item.searchHrefParameters.ToString("None","", ViewState);
        HMenuadd_event.InnerText=Resources.strings.cal_add_event;
        HMenuadd_event.HRef = item.add_eventHref+item.add_eventHrefParameters.ToString("None","", ViewState);
        HMenuRegLink.InnerText=Resources.strings.cal_registration;
        HMenuRegLink.HRef = item.RegLinkHref+item.RegLinkHrefParameters.ToString("None","", ViewState);
        HMenulogin.InnerText=Resources.strings.CCS_Login;
        HMenulogin.HRef = item.loginHref+item.loginHrefParameters.ToString("GET","", ViewState);
        HMenuprofile.InnerText=Resources.strings.cal_profile;
        HMenuprofile.HRef = item.profileHref+item.profileHrefParameters.ToString("None","", ViewState);
        HMenuadministration_link.InnerText=Resources.strings.cal_administration;
        HMenuadministration_link.HRef = item.administration_linkHref+item.administration_linkHrefParameters.ToString("GET","", ViewState);
        HMenuadministration_link_spacer.Text=item.administration_link_spacer.GetFormattedValue();
        HMenulogout.InnerText=Resources.strings.CCS_LogoutBtn;
        HMenulogout.HRef = item.logoutHref+item.logoutHrefParameters.ToString("None","", ViewState);
        HMenuuser_login.Text=Server.HtmlEncode(item.user_login.GetFormattedValue()).Replace("\r","").Replace("\n","
");
        item.styleItems.SetSelection(item.style.GetFormattedValue());
        HMenustyle.Items.Add(new ListItem("- " + Resources.strings.cal_style + " --",""));
        HMenustyle.Items[0].Selected = true;
        if(item.styleItems.GetSelectedItem() != null)
            HMenustyle.SelectedIndex = -1;
        item.styleItems.CopyTo(HMenustyle.Items);
        item.localeItems.SetSelection(item.locale.GetFormattedValue());
        HMenulocale.Items.Add(new ListItem("- " + Resources.strings.cal_language + " --",""));
        HMenulocale.Items[0].Selected = true;
        if(item.localeItems.GetSelectedItem() != null)
            HMenulocale.SelectedIndex = -1;
        item.localeItems.CopyTo(HMenulocale.Items);
        item.categoriesItems.SetSelection(item.categories.GetFormattedValue());
        //HMenucategories.Items.Add(new ListItem("-- " + Resources.strings.cal_category + " --",""));
        HMenucategories.Items.Add(new ListItem("-- " + "All Locations" + " --",""));
        HMenucategories.Items[0].Selected = true;
        if(item.categoriesItems.GetSelectedItem() != null)
            HMenucategories.SelectedIndex = -1;
        item.categoriesItems.CopyTo(HMenucategories.Items);
//End Record Form HMenu BeforeShow tail

//Record HMenu Event BeforeShow. Action Custom Code @85-2A29BDB7
    // -------------------------
    HMenustyle.Value = Utility.GetPageStyle();

    if ( System.Web.HttpContext.Current.Session["category"] != null )
        HMenucategories.Value = (string)System.Web.HttpContext.Current.Session["category"];

    HMenuadd_event_hide.Visible = CommonFunctions.AddAllowed();

    if (DBUtility.UserId != null) HMenuLoginPanel.Visible = false;
    else HMenuuser_logout.Visible = false;

    if (CommonFunctions.str_calendar_config("registration_type") == "0")
        HMenuRegLinkPanel.Visible = false;

    if (CommonFunctions.str_calendar_config("change_style") == "0")
        HMenustyle.Visible = false;

    if (CommonFunctions.str_calendar_config("change_language") == "0")
    {
        HMenulocale.Visible = false;
    }
    else
    {
        string[] languages = CommonFunctions.calendar_languages.Split(new char[] { ';' });
        HMenulocale.Items.Clear();
        HMenulocale.Items.Add(new ListItem("-- " + ((System.Resources.ResourceManager)System.Web.HttpContext.Current.Application["rm"]).GetString("cal_language") + " --",""));
        for (int i=0; i< languages.Length-1; i+=2)
            HMenulocale.Items.Add(new ListItem(languages[i+1], languages[i]));
    }

    if ( System.Web.HttpContext.Current.Session["lang"] != null )
        HMenulocale.Value = (string)System.Web.HttpContext.Current.Session["lang"];

    if (DBUtility.UserId == null || Convert.ToInt32(DBUtility.UserGroup) < 100) {
        HMenuadministration_link.Visible = false;
        HMenuadministration_link_spacer.Visible = false;
    }
    // -------------------------
//End Record HMenu Event BeforeShow. Action Custom Code

//Record Form HMenu Show method tail @65-A59B4DAC
        if(HMenuErrors.Count>0)
            HMenuShowErrors();
    }
//End Record Form HMenu Show method tail

//Record Form HMenu LoadItemFromRequest method @65-A707A715
    protected void HMenuLoadItemFromRequest(HMenuItem item, bool EnableValidation)
    {
        item.style.IsEmpty = Request.Form[HMenustyle.UniqueID]==null;
        item.style.SetValue(HMenustyle.Value);
        item.styleItems.CopyFrom(HMenustyle.Items);
        item.locale.IsEmpty = Request.Form[HMenulocale.UniqueID]==null;
        item.locale.SetValue(HMenulocale.Value);
        item.localeItems.CopyFrom(HMenulocale.Items);
        item.categories.IsEmpty = Request.Form[HMenucategories.UniqueID]==null;
        item.categories.SetValue(HMenucategories.Value);
        item.categoriesItems.CopyFrom(HMenucategories.Items);
        if(EnableValidation)
            item.Validate(HMenuData);
        HMenuErrors.Add(item.errors);
    }
//End Record Form HMenu LoadItemFromRequest method

//Record Form HMenu GetRedirectUrl method @65-43027B73
    protected string GetHMenuRedirectUrl(string redirectString ,string removeList)
    {
        LinkParameterCollection parameters = new LinkParameterCollection();
        if(redirectString == "") redirectString = Request.Url.AbsolutePath;
        string p = parameters.ToString("GET",removeList,ViewState);
        if(p == "") p="?";
        return redirectString + p;
    }

//End Record Form HMenu GetRedirectUrl method

//Record Form HMenu ShowErrors method @65-7401630F
    protected void HMenuShowErrors()
    {
        string DefaultMessage="";
        for(int i=0;i<HMenuErrors.Count;i++)
        switch(HMenuErrors.AllKeys[i])
        {
            default:
                if(DefaultMessage != "") DefaultMessage += "
";
                DefaultMessage+=HMenuErrors[i];
                break;
        }
    }
//End Record Form HMenu ShowErrors method

//Record Form HMenu Insert Operation @65-FC9CA6B9
    protected void HMenu_Insert(object sender, System.EventArgs e)
    {
        HMenuIsSubmitted = true;
        bool ErrorFlag = false;
        HMenuItem item=new HMenuItem();
        string RedirectUrl = "";
        bool EnableValidation = false;
//End Record Form HMenu Insert Operation

//Record Form HMenu BeforeInsert tail @65-FD00A2CF
    HMenuParameters();
    HMenuLoadItemFromRequest(item, EnableValidation);
//End Record Form HMenu BeforeInsert tail

//Record Form HMenu AfterInsert tail  @65-418DB8A4
        ErrorFlag=(HMenuErrors.Count>0);
        if(ErrorFlag)
            HMenuShowErrors();
        else
            Response.Redirect(RedirectUrl);
    }
//End Record Form HMenu AfterInsert tail

//Record Form HMenu Update Operation @65-EE26601D
    protected void HMenu_Update(object sender, System.EventArgs e)
    {
        HMenuItem item=new HMenuItem();
        item.IsNew = false;
        HMenuIsSubmitted = true;
        bool ErrorFlag = false;
        string RedirectUrl = "";
        bool EnableValidation = false;
//End Record Form HMenu Update Operation

//Record Form HMenu Before Update tail @65-FD00A2CF
        HMenuParameters();
        HMenuLoadItemFromRequest(item, EnableValidation);
//End Record Form HMenu Before Update tail

//Record Form HMenu Update Operation tail @65-418DB8A4
        ErrorFlag=(HMenuErrors.Count>0);
        if(ErrorFlag)
            HMenuShowErrors();
        else
            Response.Redirect(RedirectUrl);
    }
//End Record Form HMenu Update Operation tail

//Record Form HMenu Delete Operation @65-75936562
    protected void HMenu_Delete(object sender,System.EventArgs e)
    {
        HMenuIsSubmitted = true;
        bool ErrorFlag = false;
        string RedirectUrl = "";
        bool EnableValidation = false;
        HMenuItem item=new HMenuItem();
        item.IsNew = false;
        item.IsDeleted = true;
//End Record Form HMenu Delete Operation

//Record Form BeforeDelete tail @65-FD00A2CF
        HMenuParameters();
        HMenuLoadItemFromRequest(item, EnableValidation);
//End Record Form BeforeDelete tail

//Record Form AfterDelete tail @65-9C7BA282
        if(ErrorFlag)
            HMenuShowErrors();
        else
            Response.Redirect(RedirectUrl);
    }
//End Record Form AfterDelete tail

//Record Form HMenu Cancel Operation @65-0397F3CC
    protected void HMenu_Cancel(object sender,System.EventArgs e)
    {
        HMenuItem item=new HMenuItem();
        HMenuIsSubmitted = true;
        string RedirectUrl = "";
        HMenuLoadItemFromRequest(item, true);
//End Record Form HMenu Cancel Operation

//Record Form HMenu Cancel Operation tail @65-AE897FBA
        Response.Redirect(RedirectUrl);
    }
//End Record Form HMenu Cancel Operation tail

//Record Form HMenu Search Operation @65-2D6DDB03
    protected void HMenu_Search(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        HMenuIsSubmitted = true;
        bool ErrorFlag=false;
        HMenuItem item=new HMenuItem();
        HMenuLoadItemFromRequest(item, true);
        ErrorFlag=(HMenuErrors.Count>0);
        string RedirectUrl = "";
//End Record Form HMenu Search Operation

//Button Button_Apply OnClick. @89-31E31719
        if(((Control)sender).ID == "HMenuButton_Apply")
        {
            RedirectUrl = GetHMenuRedirectUrl("", "style;locale;categories");
//End Button Button_Apply OnClick.

//Button Button_Apply Event OnClick. Action Custom Code @90-2A29BDB7
    // -------------------------
    if (HMenucategories.Value!="" && Convert.ToInt32(HMenucategories.Value) > 0) System.Web.HttpContext.Current.Session["category"] = HMenucategories.Value;
    else System.Web.HttpContext.Current.Session["category"] = null;
    // -------------------------
//End Button Button_Apply Event OnClick. Action Custom Code

//Button Button_Apply OnClick tail. @89-FCB6E20C
        }
//End Button Button_Apply OnClick tail.

//Record Form HMenu Search Operation tail @65-22A7DC8D
        if(ErrorFlag)
            HMenuShowErrors();
        else{
            string Params="";
            foreach(ListItem li in HMenustyle.Items)
                if(li.Selected && !"".Equals(li.Value))
                    Params += "style="+Server.UrlEncode(li.Value)+"&";
            foreach(ListItem li in HMenulocale.Items)
                if(li.Selected && !"".Equals(li.Value))
                    Params += "locale="+Server.UrlEncode(li.Value)+"&";
            foreach(ListItem li in HMenucategories.Items)
                if(li.Selected && !"".Equals(li.Value))
                    Params += "categories="+Server.UrlEncode(li.Value)+"&";
            if(!RedirectUrl.EndsWith("?"))
                RedirectUrl += "&" + Params;
            else
                RedirectUrl += Params;
            RedirectUrl = RedirectUrl.TrimEnd(new Char[]{'&'});
            Response.Redirect(RedirectUrl);
        }
    }
//End Record Form HMenu Search Operation tail

//OnInit Event @1-6E9A00B9
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        rm = (System.Resources.ResourceManager)Application["rm"];
        Utility.SetThreadCulture();
        PageStyleName = Utility.GetPageStyle();
        if(((CCSCultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture).Encoding != null)
            Response.ContentEncoding = System.Text.Encoding.GetEncoding(((CCSCultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture).Encoding);
        headerContentMeta = "text/html; charset=" +  ((CCSCultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture).Encoding;
        InitializeComponent();
        this.Load += new System.EventHandler(this.Page_Load);
        this.Unload += new System.EventHandler(this.Page_Unload);
        base.OnInit(e);
        HMenuData = new HMenuDataProvider();
        HMenuOperations = new FormSupportedOperations(false, true, true, true, true);
//End OnInit Event

//Page header Event AfterInitialize. Action Custom Code @91-2A29BDB7
    // -------------------------
    if ((CommonFunctions.str_calendar_config("default_style")).Length > 0 && System.Web.HttpContext.Current.Session["style"] == null)
        System.Web.HttpContext.Current.Session["style"] = CommonFunctions.str_calendar_config("default_style");

    if ((CommonFunctions.str_calendar_config("default_language")).Length > 0 && System.Web.HttpContext.Current.Session["lang"] == null)
    {
        //System.Web.HttpContext.Current.Session["lang_semaphore"] = "SET";
        string LangRedirect = Request.ServerVariables["SCRIPT_NAME"];
        LangRedirect = LangRedirect + "?" + CommonFunctions.CCAddParam(Request.ServerVariables["QUERY_STRING"], "locale", CommonFunctions.str_calendar_config("default_language"));
        Response.Redirect(LangRedirect);
    }

    if (
        (CommonFunctions.str_calendar_config("menu_type")).Length == 0 ||
        (CommonFunctions.str_calendar_config("menu_type")).Trim() != "Horizontal"
       ) HMenuHolder.Visible = false;
    // -------------------------
//End Page header Event AfterInitialize. Action Custom Code

//OnInit Event tail @1-CF19F5CD
        PageStyleName = Server.UrlEncode(PageStyleName);
    }
//End OnInit Event tail

//InitializeComponent Event @1-722FC1EE
    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///
    private void InitializeComponent()
    {
    }
    #endregion
//End InitializeComponent Event

//Page class tail @1-F5FC18C5
}
}
//End Page class tail

A: It seems the category is being picked up from the Session indeed:
if ( System.Web.HttpContext.Current.Session["category"] != null )
        HMenucategories.Value = (string)System.Web.HttpContext.Current.Session["category"];

To use a querystring parameter to change the filtering, I suggest that you pick up that value from the querystring and drop it into the Session. Add the following code somewhere before the code above.
if(!String.IsNullOrEmpty(Request.QueryString["category"]))
    Session.Add("category", Request.QueryString["category"]);

And then just use links of the type

www.CrownCountry.com/calendar/index.aspx?category=somecategory

A: This should be simple, can you not just check the GET values on Page_Init and assign them to the session variables?
So without looking at your code it'd be (for each value):
void Page_Init(object sender,EventArgs e)
{
    Session["value"] = Request.Querystring["value"];
}

However you'll have to be very careful about what variables are exposed to the user, as it may be possible to manipulate your app into performing actions you didn't intend.


text:
Q: What is the form of a verb after "achieve" Which form is correct, achieve+to+verb  or achieve+verb+ing?

*

*I have achieved to play piano well.

*I have achieved playing piano well.

A: Achieve takes a noun phrase as a direct object. If a verbal form is used it should take a gerund as a direct object, not an infinitive.

I have achieved playing piano well.

There is no simple rule for telling which verbs take which verbal forms as an object; some take gerunds, some take infinitives, and some can take either (OWL). The trend is that stative verbs (like "achieve") are more likely to take a gerund, and action verbs are more likely to use an infinitive, but there are many exceptions (TFD).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bunyan is displaying /n in the output .! I am using bunyan logs to display my messages . Its displaying \n in the output after every key-value pair . How to remove it ? Following is the screen shot of the output .
 here is the image

A: This is just formatting. The text has line-changes which is displayed by the newline character "\n". Everything after the newline character should be displayed on the next line. Since this is just a string the terminal doesn't know how to display it.
If you have bunyan installed globally, you can pipe that response through bunyan cli.
node runsomething.js | bunyan
OR you don't have to have it globally installed if you run it through an npm script.
package.json
{
  "scripts": {
    "start": "node runsomething.js | bunyan",
  }
}

and run it via the start command
npm start
Relevant documentation: https://github.com/trentm/node-bunyan#cli-usage


text:
Q: Компилятор не видит класс внутри класса Есть 2 класса в 2-х файлах:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

using Dig.FMD_;

public class LB : MonoBehaviour {
}

и
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

namespace Dig.FMD_
{

    [ExecuteInEditMode]
    public class LineRenderer_ : MonoBehaviour
    {
        public LB test;//< bug
    }
}

Компилятор ругается, пишет что в классе LineRenderer_:
error CS0246: The type or namespace name `LB' could not be found. Are you missing an assembly reference?
Почему LB не виден в LineRenderer_???

A: Оберните LB в какой-нибудь namespace, можно тупо тот же Dig.FMD_, тогда ничего больше делать не придется - в ином случае в файле класса LineRenderer_ (кстати, на кой ляд вам "_" в конце имен?) нужно прописать using этого нового неймспейса.

A: У Вас класс LineRenderer_ объявлен в пространстве имен Dig.FMD_. Когда Вы в нем обращаетесь к идентификатору LB, который ищется в этом же пространстве имен и во всех пространствах, указанных в using
Но там его нет. LB у Вас определен в глобальном пространстве имен. Вот и ссылайтесь на глобальное пространство
public class LineRenderer_ : MonoBehaviour
{
    public global::LB test;
}


text:
Q: Gradle build did not finished I am getting these 2 errors while building my android project and I don't know what they mean.
Error#1:The number of method references in a .dex file cannot exceed 64K.
Error#2:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_91\bin\java.exe'' finished with non-zero exit value 2

A: You need to enable multi-dex support. Check this answer for more details and instructions how to enable it.


text:
Q: Ask for matrix lib for java (PCA / linear Regress) I am doing a java project. We have to add PCA and linear regress function to this project. Could you tell me java lib that can do these matrix's things? Many Thanks!
BTW, I used to use Matlab Builder For Java to convert the matlab code into the ".jar". However, boss deny this option for the reason of efficency.

A: Here is an excellent site benchmarking different Java matrix libraries.

Java Matrix Benchmark (JMatBench) is a tool for evaluating Java linear
  algebra libraries for speed and stability. This tool can be used by
  users to select the best library for their application and by
  developers for identifying bugs and weaknesses. Its goal is to help
  improve the state of high performance computing on the Java platform.
JMatBench rigorously tests performance across a wide range of matrix
  sizes and linear algebra operations. The runtime performance benchmark
  measures how fast each library can run under optimal conditions. It
  generates accurate results by taking in account JavaVM runtime
  optimizations, dynamically adjusts to the platform it is run on, and
  uses well established good benchmarking techniques. The stability
  benchmark evaluates several standard linear algebra operations for
  their accuracy, sensitivity, and ability to handle overflow/underflow
  conditions.


text:
Q: How to kill/close a service of another android app I have an android app got it from Google play, I can kill this app from my app using:
 KillApplication("Appname");

But this app has a service keep running. I tried to kill this service by:
 KillApplication("Appname.serviceName");

But it doesn't kill the service "serviceName". Any suggestion please?
Edit: I just forgot to write the method "KillApplication"
public void KillApplication(String KillPackage)
{
    ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
    am.killBackgroundProcesses(KillPackage);

}

A: Try this code in mainactivity.
ActivityManager.killBackgroundProcesses(PackageName);

Add permissions in Manifest file
android:name="android.permission.KILL_BACKGROUND_PROCESSES"


text:
Q: Qt & double buffering - are there any neat tricks to capture pixels or manipulate the back buffer? I'm migrating an application to Qt from MFC.
The MFC app would use GDI calls to construct the window (a graph plot, basically).  It would draw to a memory bitmap back buffer, and then BitBlt that to the screen.  Qt, however, already does double buffering.
When the user clicks and drags in the graph, I'd like that section of the window to be inverted.
I'd like to find the best way to do this.  Is there a way to do something like grabWindow() that will grab from the widget's back buffer, not the screen?  ...  maybe a BitBlt(..., DST_INVERT) equivalent?
I saw setCompositionMode() in QPainter, but the docs say that only works on painters operating on QImage.  (Otherwise I could composite a solid rectangle image onto my widget with a fancy composition mode to get something like the invert effect)
I could do the same thing as MFC, painting to a QImage back buffer...  but I read that hardware acceleration may not work this way.  It seems like it'd be a waste to reimplement the double buffering already provided to you in Qt.  I'm also not so sure what the side effects of turning off the widget's double-buffering may be (to avoid triple-buffering).
At one point, I had a convoluted QPixmap::grabWidget() call with recursion-preventing flags protecting it, but that rendered everything twice and is obviously worse than just drawing to a QImage.  (and it's specifically warned against in the docs)
Should I give up and draw everything to a QImage doing it basically like I did in MFC?
EDIT:
Okay, a QPixmap painter runs at approximately the same speed as direct now.  So, using a QPixmap back-buffer seems to be the best way to do this.
The solution was not obvious to me, but possibly if I looked at more examples (like Ariya's Monster demo) I would have just coded it the way it was expected to be done and it would have worked just fine.
Here's the difference.  I saw help system demos using this:
    QPainter painter(this)

in the start of paintEvent().  So, it seemed to naturally follow to me that to double buffer to a QPixmap then paint on the screen, you needed to do this:
    QPainter painter(&pixmap);
    QPainter painterWidget(this);
    ...  draw using 'painter' ...
    painterWidget.drawPixmap(QPoint(0,0), pixmap);

when in fact you are apparently supposed to do this:
    QPainter painter;
    painter.begin(&pixmap);
    ... draw using 'painter' ...
    painter.end();
    painter.begin(this);
    painter.drawPixmap(QPoint(0,0), pixmap);
    painter.end();

I can see that my way had two active painters at the same time.  I'm not entirely sure why it's faster, but intuitively I like the latter one better.  It's a single QPainter object, and it's only doing one thing at a time.  Maybe someone can explain why the first method is bad?  (In terms of broken assumptions in the Qt rendering engine)

A: Assuming you don't really want to pixel values from your offscreen buffer (but rather, just drawing something again on top of it and blit again to the screen), you should use QPixmap as the buffer, not QImage. Using the latter disables all painting acceleration as Qt falls back using its software raster engine, hence the use QPixmap. If you use OpenGL graphics system, you can still benefit from it.
For an example on how to do this, check my last code on running the Monster demo, it needs to have an offscreen pixmap to due the motion blur effect via repeated painting with source over composition mode.
To disable Qt's backing store (which is generally not a good idea), use the Qt::WA_PaintOnScreen for your top-level widget.
A bit unrelated, but you might want to have a look QRubberBand widget.

A: Drawing on top of the graph area you should be able to use composition modes to invert. Draw white using the Difference composition mode. The following example is a subclass of a QLabel showing a pixmap:
void Widget::paintEvent(QPaintEvent *pe)
{
    // make sure we paint background
    QLabel::paintEvent(pe);

    // paint the overlay
    if (!selectionRect.isNull()) {
        QPainter p(this);
        p.setCompositionMode(QPainter::CompositionMode_Difference);
        p.fillRect(selectionRect,QColor("#FFFFFF"));
    }
}

alt text http://chaos.troll.no/~hhartz/yesManInverted.png

A: The simplist, most straightforward answer I know of is to do it like you were doing before, to a QImage, and use the QImage as the source for your widget on the screen.
Another option might be to add a transparent widget over your graph, which only draws the inverted part of the graph.  I don't think this will optimize the drawing at all, however.  It will likely cause the underlying graph to be drawn, and then the overlay of the inverted part.


text:
Q: Find Numbers that Start with 31 and End with 21 on the given Interval I am looking for a function (with integer / math operation, instead of string) that would determine whether input number starts with 31 and end with 21.
For example, given array of integers below:
{ 341521, 513135, 434632, 312321, 315364, 312421 }
The function should return 312321 and 312421.
I still don't have it completed, but here's what I have so far (C#):
public bool IsValidId(int input)
{
    var result = input >= 310000 && input < 320000;

    if (result)
    {
        // Check for anything ending with 21, maybe something like
        // var endWith = (double) ((input / 21) / 100);
        // then check if endWith has decimal..
    }

    return result;
}

A: This could be acheived quite simply using strings by using startsWith and endsWith but if you dont want to use strings at all you can keep find the digit in a number using the Math.log10 and Math.pow functions. I would try to explain the use of these functions but my mathematics nomenclature is so rusty I'm certain I will fail horribly. I commented to code to explain the uses of the variables.
public static void main(String [] args) {
    int [] checks = new int[] { 341521, 513135, 434632, 312321, 315364, 312421 };
    for(int check : checks) {
        System.out.println(check + " " + startsWithEndsWith(check, 31, 21));
    }
}

public static boolean startsWithEndsWith(int value, int startWithNumber, int endsWIthNumber) {
    // get the number of digits for each of our inputs
    int numValueDigits = (int) Math.log10(value);
    int numStartsDigits = (int) Math.log10(startWithNumber);
    int numEndsDigits = (int) Math.log10(endsWIthNumber);

    // if the value doesnt have as many digits as either our starting or ending numbers then its impossible to be true
    if(numValueDigits < numStartsDigits || numValueDigits < numEndsDigits) {
        return false;
    }

    // for each of our startWithNumber digits check if the number in the value matches the corrisponding number in the startsWithNumber
    for(int i=0;i<=numStartsDigits;i++) {
        if(getDigitAt(value, numValueDigits-i) != getDigitAt(startWithNumber, numStartsDigits-i)) {
            return false;
        }
    }

    // for each of our endsWithNumber digits check if the number in the value matches the corrisponding number in the endsWithNumber
    for(int i=0;i<=numEndsDigits;i++) {
        if(getDigitAt(value, i) != getDigitAt(endsWIthNumber, i)) {
            return false;
        }
    }

    // nothing failed therefore its valid
    return true;
}

/**
 * returns the digit at the specified location, starting at 0 would be the 1's place. Returns 0 if the location is higher than the number
 * @param num
 * @param location 0<=location<=9
 * @return
 */
private static int getDigitAt(int num, int location) {
    // divide our number by 10^location to make the digit at the location
    // be in the 1's position, then modulus that by 10 to extract the digit
    return (int) (num/Math.pow(10, location)) % 10;
}

A: You can get the n-th digit of a number by dividing its remainder with 10^n by 10^(n-1) and you take the integer part (~math.floor).
int((3123 % 10^4) / 10^3) = 3
int((3123 % 10^3) / 10^2) = 1
int((3123 % 10^2) / 10^1) = 2
int((3123 % 10^1) / 10^0) = 3

A: Just loop for all numbers, each of them use O(1) to check if they fulfill the conditions: Let C be the current number

*

*C%100 == 21

*Let d = floor(log(C) + 1), if (d-2 >= 0 && C/10^(d-2) == 31)

If C fulfills both conditions, then it is one of the 31*21 number
Of course, why not just use string to check C[0,1] == "31" && C[len-2, len-1] == "21"?


text:
Q: Jquery click event won't recognize elements from PHP list When i load the list of items from MySQL using PHP,jquery event click won't recognize them. Jquery is working on all other elements on the page except the option tag which is created through for loop.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<script src="js/js.js"></script>
<script>
$(document).ready(function(){

    $(document).on('click', '.option', function(e){
alert('cls2 clicked');
e.preventDefault();

});

});

</script>

<select>
 <?php
include "konekcija.php";
  $upit="SELECT * FROM galerije group by naziv_galerije";
    $rez = $connection->query($upit);

foreach ($connection->query($upit) as $r)
{
$ispis.="  <option value='{$r['id_galerije']}' class='option'>
{$r['naziv_galerije']}</option>";
}
echo $ispis;
?>


text:
Q: Changing Jquery to AJAX url GET First of all I want to apologize for the title couldn't find a better title.
I am new to ajax and I want to change my jquery to ajax. I wanted to do it in the same jquery but the jquery I am using already have a url and I dont think you can use two url at the same time.
My current jquery this works and if  you understand this, you should be able to understand what I want to
$(document).ready(function(){
    $('#selected').hide();
    $('#button').click(function(){
        var pid = $('#pid').val();
        var length = $('#length').val();
        var Category = $('#Category').val();
        var Qty = $('#Qty').val();
        var qty = $('#Qty').val();
        var price = '\u00A3' + parseInt($('#pricetag').text().replace(/^\D/, ''), 10) * qty;
        var category = $('#Category').text();
        var length = $('#length').val();
        if (!/^[1-9]\d?$/.test(Qty)){
            alert('Quantity should not be below 1 or null');
            return false; // don't continue
        }
        else {
        $('#sprice').text(price);
        $('#scategory').text(category);
        $('#slength').text(length);
        $('#selected').slideDown();
        }
        $.ajax({
            url: 'cart.php',
            type: 'POST',
            data: { pid:pid,
            length:length,
            Qty:Qty,
            Category:Category },
            success: function(data)
            {

            }
        });
    });
});

If you notice I needed to hide my div called selected. This isn't the right way to do it.
My selected div

            Price:

            Category:

            Length:

I try this ajax code i found on w3school
function showitem(str)
{
var xmlhttp;
if (str.length==0)
  {
  document.getElementById("showtxt").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("showtxt").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","showitem.php?pid="+str,true);
xmlhttp.send();
}

but it doesn't work because I am inexperience with it.
Want I want to do
I don't want to hide the selected because if you disable javascript it shows.
What I intend to do it. if that when you click the add button onclick using the ajax, it will send the length, pid, category and Qty to showitem.php and in this showitem.php it will calculate multiply price * Qty and then echo out into

            Price:

            Category:

            Length:

showitem.php
<?php
include('global.php');
    dbconnect();
$id=$_POST["pid"];
$Category=$_POST["Category"];
$length=$_POST["length"];
$qty=$_POST["Qty"];
$stmt2 = $conn->prepare("
SELECT Product.Name as ProductName, Category.Name, Category.CatID, Length, Price
FROM Itemised_Product, Product, Category
WHERE Itemised_Product.ppid =:item_id
AND Hair_Length = :length  AND Category.Name = :Category Limit  1");
$stmt2->bindParam('id',$id);
$stmt2->bindParam('length',$length);
$stmt2->bindParam('Category',$length);
$stmt2->bindParam('length',$length);
$stmt2->execute();
$price = $row["Price"];
foreach ($_SESSION["item_price"]as $each_item) {
$pricetotal = $price * $each_item['Qty'];
$i = 0;
$rows2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows2 as $row2) {
            if ($i == 0) {
        echo '

            Price:
            ' . $totalprice . '

            Category:
            ' . $Category . '

            Length:
            '.$length.'

';
            }
        }
        }
?>

Please help me. if you dont understand the question please leave a comment and i will try and explain it in more details

A: You should use Jquery to handle all the completed Ajax stuff for you , this is sample  Jquery Ajax code
var price = $('#sprice').html();
var length = $('#scategory').html();
var category = $('#slength').html();
$.ajax({
            //this is the php file that processes the data
            url: "showitem.php",

            //GET method is used
            type: "GET",

            //pass the data
            data: '&price='+price+'&category'+category+'&length='+length,
            //Do not cache the page
            cache: false,

             beforeSend: function(){
            //do something before data is sent

            },
             complete: function(html){
             //do soemthing after data has been sent
             },

            //success
            success: function (html) {
            //do something with the result
            },

            error : function ()
            {
            //something went wrong
            }

        });


text:
Q: Using JavaScript to advance to next video in Dash.js I found a workaround on the Wowza Streaming Engine forum that showed how to use JavaScript to advance to the next video in a list of filepaths for use with an m3u8 playlist, which worked using this method I adapted for my Rails view:
<script>
    <% string = "" %>
    <% request = HTTParty.get("http://localhost:4567/playlist") %>
    <% playlist = JSON.parse(request.body) %>
    <% vids = playlist.each do |vid| %>
    <% if vid['id'] %>

        <% string = string + "" + vid['filename'] +"," %>

    <% end %>
    <% end %>

var videos="<%= string %>".split(",");
next=-1;
    function end(e)
    {
    var video = document.getElementById("video1");

    if (++next==videos.length)
        return;

    <% if browser.safari? or browser.ios? %>
    video.src = "http://IP:1935/"+videos[next]+"/playlist.m3u8";
    <% elsif browser.chrome? %>
    video.src = "http://IP:1935/"+videos[next]+"/manifest.mpd";
    <% end %>
    video.load();
    video.play();
    }
</script>

It works properly with m3u8 on Safari and iOS devices, and it works up until a point on Chrome, which uses Dash.js as the player:
               <video class="dashjs-player" preload="true" width="100%" height="auto" controls autoplay onended="end(event)" id="video1" src="http://IP:1935/vod/mp4:Sample.mp4/manifest.mpd" type="application/dash+xml" >

               </video>

The Javascript is supposed to advance to the next file in the list, which it does, but I receive this error in my console:
[video] start
dash.all.js:11 [audio] start
dash.all.js:11 Video Element Error: MEDIA_ERR_SRC_NOT_SUPPORTED
dash.all.js:11 [video] stop
dash.all.js:11 [audio] stop
dash.all.js:11 Video Element Error: MEDIA_ERR_SRC_NOT_SUPPORTED

with no other detail. From the Network tab in the console, I found that it was, indeed, connecting, and in player, the correct (resolvable, and valid) URL was set, but that, unlike the first manifest, it showed the type "media" rather than "xhr" and that the initiator was from my app, rather than Dash.js:

So, basically, my question is where do I start changing my request method to force dash.js to make the call and/or make my current request (from the Javascript in my page's head) do a proper XHR, which is presumably the chokepoint from what data I could collect?

A: I think the problem you're running into is that dash.js doesn't work by setting the src element of a video to the mpd file. Instead you have to initialize the dash.js player and point it at the Video element.
You can check out the Getting Started section of the dash.js Readme. Dash.js uses Media Source Extensions to play the video so that it can perform the necessary decryption and bit rate switching. This means that the video.src attribute gets set to a special blob URL which you won't know on the server side.
The tl;dr; version is that you need to run code like this:
(function(){
            var url = "http://dash.edgesuite.net/envivio/Envivio-dash2/manifest.mpd";
            var player = MediaPlayer().create();
            player.initialize(document.querySelector(".dashjs-player"), url, true);
        })();

You should also note that Dash.js should work on Safari for desktop.


text:
Q: MariaDB doesn't connect to galera cluster despite reading configuration file I'm trying to setup a galera cluster using MariaDB 10.6.11. It's something I've done several times without any problems, now I'm trying to automate the process and something weird happens.
I have a configuration file /etc/my.cnf.d/galera.cnf like this on every node:
[mysqld]
datadir=/var/lib/mysql

[galera]
# Mandatory settings
wsrep_on=ON
wsrep_provider="/usr/lib64/galera-4/libgalera_smm.so"
wsrep_provider_options="gcache.size=300M; gcache.page_size=200M"
wsrep_cluster_name="test"
wsrep_cluster_address="gcomm://192.168.1.176,192.168.1.61"
binlog_format=row
default_storage_engine=InnoDB
innodb_autoinc_lock_mode=2
wsrep_sst_method=mariabackup
wsrep_sst_auth="backup:[redacted]"

# Log Options
wsrep_log_conflicts=ON
wsrep_provider_options="cert.log_conflicts=ON"

# Optional setting
#wsrep_slave_threads=1
innodb_flush_log_at_trx_commit=0

# Node Specific
wsrep_node_name="node-1"
bind-address="192.168.1.61"

Of course, in the other nodes bind-address and wsrep_node_name are set accordingly.
Anyway, I start the first node with
galera_new_cluster

And the cluster is started correctly, with one synced node as expected.
When I execute systemctl start mariadb on other node instead, after the first node is online, the second node starts in standalone mode, completely ignoring the galera configuration.
If I execute mariadbd --print-defaults on the second node, I see all the variables correctly set
[root@localhost ~]# mariadbd --print-defaults
mariadbd would have been started with the following arguments:
--datadir=/var/lib/mysql --wsrep_on=ON
--wsrep_provider=/usr/lib64/galera-4/libgalera_smm.so --wsrep_provider_options=gcache.size=300M; gcache.page_size=200M
--wsrep_cluster_name=test --wsrep_cluster_address=gcomm://192.168.1.176,192.168.1.61 --binlog_format=row --default_storage_engine=InnoDB
--innodb_autoinc_lock_mode=2 --wsrep_sst_method=mariabackup
--wsrep_sst_auth=backup:[redacted] --wsrep_log_conflicts=ON --wsrep_provider_options=cert.log_conflicts=ON
--innodb_flush_log_at_trx_commit=0 --wsrep_node_name=node-2 --bind-address=192.168.1.176

No attempt to join the cluster is made, it just starts as a standalone node.
From journactl:
2022-11-29  9:15:46 0 [Note] /usr/sbin/mariadbd (server 10.6.11-MariaDB) starting as process 5411 ...
2022-11-29  9:15:46 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2022-11-29  9:15:46 0 [Note] InnoDB: Number of pools: 1
2022-11-29  9:15:46 0 [Note] InnoDB: Using crc32 + pclmulqdq instructions
2022-11-29  9:15:46 0 [Note] InnoDB: Using Linux native AIO
2022-11-29  9:15:46 0 [Note] InnoDB: Initializing buffer pool, total size = 134217728, chunk size = 134217728
2022-11-29  9:15:46 0 [Note] InnoDB: Completed initialization of buffer pool
2022-11-29  9:15:46 0 [Note] InnoDB: 128 rollback segments are active.
2022-11-29  9:15:46 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2022-11-29  9:15:46 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2022-11-29  9:15:46 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2022-11-29  9:15:46 0 [Note] InnoDB: 10.6.11 started; log sequence number 50748; transaction id 29
2022-11-29  9:15:46 0 [Note] Plugin 'FEEDBACK' is disabled.
2022-11-29  9:15:46 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2022-11-29  9:15:46 0 [Note] Server socket created on IP: '0.0.0.0'.
2022-11-29  9:15:46 0 [Note] Server socket created on IP: '::'.
2022-11-29  9:15:46 0 [Note] InnoDB: Buffer pool(s) load completed at 221129  9:15:46
2022-11-29  9:15:46 0 [Note] /usr/sbin/mariadbd: ready for connections.
Version: '10.6.11-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server
Started MariaDB 10.6.11 database server.

In /etc/my.cnf I have the line
!includedir /etc/my.cnf.d

so that's covered.
Communication between the two nodes is also ok, I opened every needed port. Also, if it were to be something about communication, I'd receive a timeout error or something.
Also, if I move the galera configuration to /etc/my.cnf.d/server.cnf, it works.
I'm confused. The variables are set correctly, what could it be?
One argument could be that in server.cnf there is an empty [galera] section, but I have it also on the first node and everything works there. Plus, again, the variables are set, so it's not like that empty section is overwriting my configuration.
Ideas?


text:
Q: How to apply code to all the files in a directly and convert xml files to txt files I'm trying to apply code in python to extract necessary information from each xml file and write them in txt files.
I successfully executed my code but the result shows only one file.
Also, my code doesn't look smart, I would be very glad if anyone can help me to solve the problem and give me some correction.
I'm afraid I'm very beginner so I might have many fundamental mistakes...
here is my code

from xml.etree import ElementTree as ET
import os

path = r'/Users/mo/Documents/annotations/xmls'
filenames = []

for filename in os.listdir(path):
    if not filename.endswith('.xml'):
        continue
    fullname = os.path.join(path,filename)
    filenames.append(fullname)

each_name = filename[:-4]

with open(each_name + '.txt', 'a') as f:

    for filename in filenames:
        tree = ET.parse(filename)
        root = tree.getroot()

        for object in root.findall('object'):
            categoryID = object.find('name').text

            for bnd_box in object.findall('bndbox'):
                Xcenter = (int(bnd_box.find('xmax').text) - int(bnd_box.find('xmin').text))/2
                Ycenter = (int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text))/2
                width = int(bnd_box.find('xmax').text)- int(bnd_box.find('xmin').text)
                height = int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text)
                Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'

    f.write(str(Detection_rows))

Thank you very much

A: Try this (did not test it)
from xml.etree import ElementTree as ET
import os

path = r'/Users/mo/Documents/annotations/xmls'

for filename in os.listdir(path):
    if not filename.endswith('.xml'):
        continue

    fullname = os.path.join(path, filename)

    with open(fullname[:-4] + '.txt', 'a') as f:

        tree = ET.parse(fullname)
        root = tree.getroot()

        for object in root.findall('object'):
            categoryID = object.find('name').text

            for bnd_box in object.findall('bndbox'):
                Xcenter = (int(bnd_box.find('xmax').text) - int(bnd_box.find('xmin').text))/2
                Ycenter = (int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text))/2
                width = int(bnd_box.find('xmax').text)- int(bnd_box.find('xmin').text)
                height = int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text)
                Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'

        f.write(str(Detection_rows))

Your for loop should be outside the open and you changed filenames for filename. Also, I removed one unnecessary for loop. Let me know if it solves the issue for you.


text:
Q: How do I seperate rows in list while using react-native-swipeout? I am using react-native-swipeout in order to implement a swiping functionality for each row in List & perform some actions. But the swiping get's applied to all row at once on swipe and not each row separately. Can anyone help me out how to separate the rows in a list and apply swipeout?
<Swipeout >
     <List
        dataSource=
        extraData={this.state.rowIndex}
          />
          )
</Swipeout>

A: You can use Map function
        {this.state.contactData.map((rowdata, i) => {
                        return (<Swipeout>
                          <View key={i}>
                            <Text>{rowdata.listname}</Text>
                          </View>
                        </Swipeout>);
                    })}


text:
Q: Using GitPython to: git reset --hard FETCH_HEAD --recurse-submodules Using GitPython, how can we run a rest on a repo that is the equivalent of running the following command in the terminal:
git fetch
git checkout foo
git reset --hard FETCH_HEAD --recurse-submodules

I think git fetch and git checkout foo is done by
repo = git.Repo(repo_path)
for remote in repo.remotes:
    remote.fetch()

repo.git.checkout('foo')

Should we only fetch from the remote origin, and how can we do git reset?


text:
Q: get default fieldset border width cross browser example http://jsfiddle.net/fuZ4L/
I am trying to get the border width of a fieldset using:
$("fieldset").css("borderWidth")

and it works fine in chrome and opera but ie and firefox return a blank string.
Is there another way to get the default border width of a fieldset or is this an error in jQuery?


text:
Q: How to use transactions with NestJs Repositories? Assuming I have this Service:
@Injectable()
export class MyService {
  constructor(
    @InjectRepository(A)
    private aRepository: Repository<A>,
    @InjectRepository(B)
    private bRepository: Repository<B>,
  ) {}

  doSomething() {
     // TX: begin()
    this.aRepository.save(...);
    this.bRepository.save(...);
    // TX: commit()
  }
}

How to start a transaction and commit it?

A: For transactions, it is not mandatory to use the injected repositories. You can do something like this:
@Injectable()
export class MyService {
  constructor(
    @InjectRepository(A)
    private aRepository: Repository<A>,
    @InjectRepository(B)
    private bRepository: Repository<B>,
  ) {}

  async doSomething() {
    await getManager().transaction(async (manager) => {
      // TX: begin()
      await manager.getRepository(A).save(...);
      await manager.getRepository(B).save(...);
      // TX: commit()
    });
  }
}

Look for more info in Typeorm Transactions


text:
Q: I need to compare the difference between arbitrary version of source side by side using toirtoisegit I have used perforce (P4V) before, which gives a cool versions history and any version of the source can be dragged and compared between each other. The differences shown or side by side and is evry easy to track. is there something similar that can be expected using tortoise for git ?

A: Well I have found it. This is  what i did =>  right click on the file (whose versions has to be compared) tortoiseGit>Showlog from the select the versions to be compared holding the ctr key from the revsion tree, and say compare.


text:
Q: magento2 how to set a loder widget on a page load event i Want to set loader on page load event
how can do this any idea about that?
Any help would be appreciated.
Thanks.

A: You can use by simply way using jQuery script :
<script>
    require([
        'jquery'
    ], function ($) {
        'use strict';
        $(window).on('load', function(){
            $('body').trigger('processStart');
            $('body').trigger('processStop');
        });
    });
</script>

You can stop by below code on base of your requirement :
$('body').trigger('processStop');

For UI Component :

require(['uiRegistry'], function (uiRegistry) {
    uiRegistry.get("customer_form.customer_form_data_source", function (element) {
        $('body').trigger('processStop'); // It will stop after ui component loaded
    })
})

Output :

A: You can try below code
<script type="text/javascript">
    require([
        'jquery',
        'loader'
    ], function ($) {
        'use strict';
        setTimeout(function(){
            $('body').trigger('processStart');
        }, 500);
        $(window).on('load', function(){
            console.log("page is loaded.");
            setTimeout(function(){
                $('body').trigger('processStop');
            }, 500);
            console.log("Stop the Loader.");
        });

    });
</script>

Hope it Helps.


text:
Q: Using Sagemaker predictor in a Spark UDF function I am trying to run inference on a Tensorflow model deployed on SageMaker from a Python Spark job.
I am running a (Databricks) notebook which has the following cell:
def call_predict():
        batch_size = 1
        data = [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2]]
        tensor_proto = tf.make_tensor_proto(values=np.asarray(data), shape=[batch_size, len(data[0])], dtype=tf.float32)
        prediction = predictor.predict(tensor_proto)
        print("Process time: {}".format((time.clock() - start)))
        return prediction

If I just call call_predict() it works fine:
call_predict()

and I get the output:
Process time: 65.261396
Out[61]: {'model_spec': {'name': u'generic_model',
  'signature_name': u'serving_default',
  'version': {'value': 1578909324L}},
 'outputs': {u'ages': {'dtype': 1,
   'float_val': [5.680944442749023],
   'tensor_shape': {'dim': [{'size': 1L}]}}}}

but when I try to call from a Spark context (in a UDF) I get a serialization error.
The code I'm trying to run is:
dataRange = range(1, 10001)
rangeRDD = sc.parallelize(dataRange, 8)
new_data = rangeRDD.map(lambda x : call_predict())
new_data.count()

and the error I get is:
---------------------------------------------------------------------------
PicklingError                             Traceback (most recent call last)
<command-2282434> in <module>()
      2 rangeRDD = sc.parallelize(dataRange, 8)
      3 new_data = rangeRDD.map(lambda x : call_predict())
----> 4 new_data.count()
      5

/databricks/spark/python/pyspark/rdd.pyc in count(self)
   1094         3
   1095         """
-> 1096         return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
   1097
   1098     def stats(self):

/databricks/spark/python/pyspark/rdd.pyc in sum(self)
   1085         6.0
   1086         """
-> 1087         return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
   1088
   1089     def count(self):

/databricks/spark/python/pyspark/rdd.pyc in fold(self, zeroValue, op)
    956         # zeroValue provided to each partition is unique from the one provided
    957         # to the final reduce call
--> 958         vals = self.mapPartitions(func).collect()
    959         return reduce(op, vals, zeroValue)
    960

/databricks/spark/python/pyspark/rdd.pyc in collect(self)
    829         # Default path used in OSS Spark / for non-credential passthrough clusters:
    830         with SCCallSiteSync(self.context) as css:
--> 831             sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
    832         return list(_load_from_socket(sock_info, self._jrdd_deserializer))
    833

/databricks/spark/python/pyspark/rdd.pyc in _jrdd(self)
   2573
   2574         wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer,
-> 2575                                       self._jrdd_deserializer, profiler)
   2576         python_rdd = self.ctx._jvm.PythonRDD(self._prev_jrdd.rdd(), wrapped_func,
   2577                                              self.preservesPartitioning, self.is_barrier)

/databricks/spark/python/pyspark/rdd.pyc in _wrap_function(sc, func, deserializer, serializer, profiler)
   2475     assert serializer, "serializer should not be empty"
   2476     command = (func, profiler, deserializer, serializer)
-> 2477     pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command)
   2478     return sc._jvm.PythonFunction(bytearray(pickled_command), env, includes, sc.pythonExec,
   2479                                   sc.pythonVer, broadcast_vars, sc._javaAccumulator)

/databricks/spark/python/pyspark/rdd.pyc in _prepare_for_python_RDD(sc, command)
   2461     # the serialized command will be compressed by broadcast
   2462     ser = CloudPickleSerializer()
-> 2463     pickled_command = ser.dumps(command)
   2464     if len(pickled_command) > sc._jvm.PythonUtils.getBroadcastThreshold(sc._jsc):  # Default 1M
   2465         # The broadcast will have same life cycle as created PythonRDD

/databricks/spark/python/pyspark/serializers.pyc in dumps(self, obj)
    709                 msg = "Could not serialize object: %s: %s" % (e.__class__.__name__, emsg)
    710             cloudpickle.print_exec(sys.stderr)
--> 711             raise pickle.PicklingError(msg)
    712
    713

PicklingError: Could not serialize object: TypeError: can't pickle _ssl._SSLSocket objects

Not sure what is this serialization error - does is complain about failing to deserialize the Predictor
My notebook has a cell which was called prior to the above cells with the following imports:
import sagemaker
import boto3
from sagemaker.tensorflow.model import TensorFlowPredictor
import tensorflow as tf
import numpy as np
import time

The Predictor was created with the following code:
sagemaker_client = boto3.client('sagemaker', aws_access_key_id=ACCESS_KEY,
                                aws_secret_access_key=SECRET_KEY, region_name='us-east-1')
sagemaker_runtime_client = boto3.client('sagemaker-runtime', aws_access_key_id=ACCESS_KEY,
                                        aws_secret_access_key=SECRET_KEY, region_name='us-east-1')

boto_session = boto3.Session(region_name='us-east-1')
sagemaker_session = sagemaker.Session(boto_session, sagemaker_client=sagemaker_client, sagemaker_runtime_client=sagemaker_runtime_client)

predictor = TensorFlowPredictor('endpoint-poc', sagemaker_session)

A: The udf function will be executed by multiple spark tasks in parallel. Those tasks run in completely isolated python processes and they are scheduled to physically different machines. Hence each data, those functions reference, must be on the same node. This is the case for everything created within the udf.
Whenever you reference any object outside of the udf from the function, this data structure needs to be serialised (pickled) to each executor. Some object state, like open connections to a socket, cannot be pickled.
You need to make sure, that connections are lazily opened each executor. It must happen only on the first function call on that executor. The connection pooling topic is covered in the docs, however only in the spark streaming guide (though it also applies for normal batch jobs).
Normally one can use the Singleton Pattern for this. But in python people use the Borgh pattern.
class Env:
    _shared_state = {
        "sagemaker_client": None
        "sagemaker_runtime_client": None
        "boto_session": None
        "sagemaker_session": None
        "predictor": None
    }
    def __init__(self):
        self.__dict__ = self._shared_state
        if not self.predictor:
            self.sagemaker_client = boto3.client('sagemaker', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name='us-east-1')
            self.sagemaker_runtime_client = boto3.client('sagemaker-runtime', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name='us-east-1')

            self.boto_session = boto3.Session(region_name='us-east-1')
            self.sagemaker_session = sagemaker.Session(self.boto_session, sagemaker_client=self.sagemaker_client, sagemaker_runtime_client=self.sagemaker_runtime_client)

            self.predictor = TensorFlowPredictor('endpoint-poc', self.sagemaker_session)

#....
def call_predict():
   env = Env()
   batch_size = 1
   data = [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2]]
   tensor_proto = tf.make_tensor_proto(values=np.asarray(data), shape=[batch_size, len(data[0])], dtype=tf.float32)
   prediction = env.predictor.predict(tensor_proto)

   print("Process time: {}".format((time.clock() - start)))
        return prediction

new_data = rangeRDD.map(lambda x : call_predict())

The Env class is defined on the master node. Its _shared_state has empty entries. When then Env object is instantiated first time, it shares the state with all further instances of Env on any subsequent call to the udf. On each separate parallel running process this will happen exactly one time. This way the sessions are shared and do not need to pickled.


text:
Q: What changes should I make to add marker on the map? This is what I implemented so far. I am unable to add a marker to the current location on the map. Although I am able to get the current location as well as coordinates using the function findCoordinates() But I am unable to display on the map. Please suggest me where I am wrong or what should I do?
Here is the code I am sharing with you. Please suggest me the better ways to do it.
Thanks in advance
export default class App extends React.Component {
  state = {
    mapRegion: null,
    hasLocationPermissions: false,
    locationResult: null,
    location: null,
  };

  componentDidMount() {
    this.getLocationAsync();
  }

  handleMapRegionChange = mapRegion => {
    this.setState({ mapRegion });
  };

  async getLocationAsync () {
    // permissions returns only for location permissions on iOS and under certain conditions, see Permissions.LOCATION
    const { status, permissions } = await Permissions.askAsync(
      Permissions.LOCATION
    );
    if (status === 'granted') {
      this.setState({ hasLocationPermissions: true });
      //  let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true });
      let location = await Location.getCurrentPositionAsync({});
      this.setState({ locationResult: JSON.stringify(location) });
      // Center the map on the location we just fetched.
      this.setState({
        mapRegion: {
          latitude: location.coords.latitude,
          longitude: location.coords.longitude,
          latitudeDelta: 0.04,
          longitudeDelta: 0.05,
        },
      });
    } else {
      alert('Location permission not granted');
    }
  };
    findCoordinates = () => {
        navigator.geolocation.getCurrentPosition(
            position => {
                const location = JSON.stringify(position);

                this.setState({ location });
            },
            error => Alert.alert(error.message),
            { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
        );
    };
  render() {
    return (
      <View style={styles.container}>
        <MapView

          style={styles.mapStyle}
          region={this.state.mapRegion}
          onRegionChange={this.handleMapRegionChange}

        />
        <Ionicons style = {{paddingLeft: 0}} name = "md-locate" size = {30} color = "red"
        onPress = {this.findCoordinates}

        />

          <TouchableOpacity onPress={this.findCoordinates}>
                    <Text style={styles.welcome}>My Location</Text>
                    <Text>Location: {this.state.location}</Text>
                </TouchableOpacity>
      </View>
    );
  }
}
App.navigationOptions = {
  title: 'Location',
  headerStyle: {
    backgroundColor: '#ff6666',
  },
  headerTintColor: '#fff',
  headerTitleStyle: {
    fontWeight: 'bold',
    fontSize:20
  },
};

A: You could try below
findCoordinates = () => {
  navigator.geolocation.getCurrentPosition(
    position => {
      this.setState({ location });
    },
    error => Alert.alert(error.message),
    { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
  );
};

render() {
  return (
    <View style={styles.container}>
      <MapView
        style={styles.mapStyle}
        region={this.state.mapRegion}
        onRegionChange={this.handleMapRegionChange}
      >
        {this.state.location && (
          <MapView.Marker
            coordinate={this.state.location.coords} // <-- Pass coordinate { latitude: number, longitude: number }
          />
        )}
      </MapView>
    </View>
  )
}

A:                import { Marker } from 'react-native-maps';

    //you need to set the initial latitude and longitude
value with deltas and use the marker component from react-native-maps
                        <MapView
                      style={styles.mapStyle}
                      region={this.state.mapRegion}
                      onRegionChange={this.handleMapRegionChange}>
                   <Marker
                      coordinate={this.state.location}
                      title={marker.title}
                      description={marker.description}
                    />

                </MapView>


text:
Q: JavaSimon 4.1.1 add time Are there any ways to add time to existing stopwatch, as it was available in <=3.0 ?
public Stopwatch addTime(long time) {}

I cannot find any similar methods in new Simon..

A: Answer has found:
addSplit(Split.create(time));


text:
Q: How to find the Array with the longest string length inside a multi dimensional array Hi guys !
I have an multi-dimension array like this :

$arr =
Array
(
    [0] => Array
        (
            ['id'] => 1
            ['title'] => one test
        )

    [1] => Array
        (
            ['id'] => 4
            ['title'] => two test xyz
        )

    [2] => Array
        (
            ['id'] => 2
            ['title'] => fdfdf dfdfdffdfdf
        )

    [3] => Array
        (
            ['id'] => 3
            ['title'] => fddddđ fffffffff ssss
        )

)

Is there any way let get longest string and its length in any $array['title'] element ?
I want to get "fddddđ fffffffff ssss" and its length.
Please tell me any way let : get longest string , get longest length string and both. Thanks .
I see a way : max(array_map('strlen', $ary));
<== but it use for single array ,
in this topic i want there is any way let just find in $arr['title']
Update :
but if i want to get :

*

*longest length string + longest string inside $arr['title']

*largest "id" value number inside $arr['id'] , largest "id" value number now is 4 inside $arr[1]['id']

<== and all them are assigned to a new array like :

    array(
         'id' => 4,
         'title' => 'fddddđ fffffffff ssss'
)

How to i do ?
Look carefully my update before you answer , thank

A: $max = '';
$maxlen = 0;

foreach ($arr as $elm) {
    $len = strlen($elm['title']);

    if ($len > $maxlen) {
        $maxlen = $len;
        $max = $elm['title'];
    }
}

echo "The longest string is \"$max\" and it is $maxlen chars long.\n";

A: This is a version that will iterate over a multidimensional array and return the array of longest string it finds. Adapted on Sean Bright's code to keep things simple.
 $arr = array(

    "0" => array(
            'id' => 1,
            'title' => "one test"
        ),

    "1" => array(
            'id' => 2,
            'title' => "two test xyz"
        ),

    "2" => array(
            'id' => 3,
            'title' => "fdfdf dfdfdffdfdf"
        ),

    "3" => array(
            'id' => 4,
            'title' => "fddddđ fffffffff ssss"
       )

);

function longest_string(&$arr, &$max='',&$maxlen=false){

    foreach ($arr as $elm=>$val) {
        $len = strlen($val);

       if ($len > $maxlen) {

            $maxlen = $len;
            $max = $arr;
        }

        if( is_array($val) ){
            longest_string($val, $max, $maxlen);
        }

    }

    return $max;
}

echo  var_dump(longest_string($arr1));

// array(2) { ["id"]=> int(4) ["title"]=> string(22) "fddddđ fffffffff ssss" }

A: $maxlen = 0;
$idxMax = null;

foreach($arr as $idx => $elem) {
  if(strlen($elem['title']) > $maxlen)
    $idxMax = $idx;
}

printf('Longest string: "%s" (%d), at index %d',
  $arr[$idxMax]['title'],
  strlen($arr[$idxMax]['title']),
  $idxMax);

To answer your updated question, use $arr[$idxMax]['id']. If you want the array containing the string and its index, simply assign it to a new variable:
$longestEntry = $arr[$idxMax];

To combine the highest ID with the longest string, use:
$maxlen = 0;
$maxId = $arr[0]['id']; // assuming array has at least one element
$idxMax = null;

foreach($arr as $idx => $elem) {
  if(strlen($elem['title']) > $maxlen)
    $idxMax = $idx;

  $maxId = max($elem['id'], $maxId);
}

$max = array(
  'id' => $maxId,
  'title' => $arr[$idxMax],
);

A:     $string="";
    foreach($arr as $list)
    {
      $string=strlen(list['title'])>strlen($string)?ist['title']:$string;

    }
    echo $string;
    echo strlen($string)

you can find largest string also string length try it


text:
Q: Can the execution of statements in Python be delayed? I want it to run the first line print 1 then wait 1 second to run the second command print 2, etc.
Pseudo-code:
print 1
wait(1 seconds)
print 2
wait(0.45 seconds)
print 3
wait(3 seconds)
print 4

A: import time

# ...

time.sleep(1)

A: time.sleep(seconds)
import time

print 1
time.sleep(1)
print 2
time.sleep(0.45)
print 3
time.sleep(3)
print 4

A: All the answers have assumed that you want or can manually insert time.sleep after each line, but may be you want a automated way to do that for a large number of lines of code e.g. consider this code
def func1():
    print "func1 1",time.time()
    print "func1 2",time.time()

def func2():
    print "func2 1",time.time()
    print "func2 2",time.time()

def main():
    print 1,time.time()
    print 2,time.time()
    func1()
    func2()

If you want to delay execution of each line, either you can manually insert time.sleep before each line which is cumbersome and error-prone, instead you can use sys.settrace to get you own function called before each line is executed and in that callback you can delay execution, so without manually inserting time.sleep at every place and littering code, you can do this instead
import sys
import time

def func1():
    print "func1 1",time.time()
    print "func1 2",time.time()

def func2():
    print "func2 1",time.time()
    print "func2 2",time.time()

def main():
    print 1,time.time()
    print 2,time.time()
    func1()
    func2()

def mytrace(frame, event, arg):
    if event == "line":
        time.sleep(1)
    return mytrace

sys.settrace(mytrace)
main()

Without trace output is:
1 1280032100.88
2 1280032100.88
func1 1 1280032100.88
func1 2 1280032100.88
func2 1 1280032100.88
func2 2 1280032100.88

With trace output is:
1 1280032131.27
2 1280032132.27
func1 1 1280032134.27
func1 2 1280032135.27
func2 1 1280032137.27
func2 2 1280032138.27

You can further tweak it according to your needs, may be checking line contents too and most importantly this is very easy to disable and will work with any code.


text:
Q: jQuery create and open URL with ampersand I'm trying to build an URL in jquery and then open it. The problem is that the URL should contain an ampersand and I can't figure out how to do that
        var url = 'print?month=' +  jQuery('#month').val() + '&year=' + jQuery('#year').val();
        var encodedUrl = encodeURIComponent(url);
        window.open(encodedUrl);

Essentially, what I'd like the URL to be is: print?month=1&year=2015

A: Yes, changing & a m p ; [without spaces] to & should work, if not you should probably do something like below:
var url = 'print?month=' +  encodeURIComponent(jQuery('#month').val()) + '&year=' + encodeURIComponent(jQuery('#year').val());
window.open(url);

A: Fully working plnkr is at:http://plnkr.co/edit/70h1E8SJDXMhtMJPnKMp?p=preview
Just enable popups on your browser for plnkr if you dont see the popup yet.
Basically just create a string with concatenating & charecters, its just a string, you dont need to URIEncode it, then do a window.open of the string. That should do it.


text:
Q: SpringDataJPA - What does '?1' in the where clause mean in the below query? @Query(value="select * from author a where a.last_name= ?1",nativeQuery = true)

What does ?1 mean in the above query?

A: This ?1 indicate a positional parameters is a different practice for define a query parameters to advoid some issue like SQL injection, for example:

*

*Named parameters:

    String statment = "SELECT * from Users WHERE name=:nameParam and role=:roleParam";

    //some code

    query.setString("nameParam", nameValue);

    query.setString("roleParam", roleValue);

*

*Positional parameters:

    String statment = "SELECT * from Users WHERE name=?1 and role=?2";

    //some code

    query.setString(1, nameValue);

    query.setString(2, roleValue);


text:
Q: under HTML table Autocomplete for HtmlEditor Control I have a Html table having multiple rows with one drop down and one textbox control.
I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
CODE:

                                ItemId
                                Item Name
                                UOM

                            @foreach (var Item in Model.Data_Wde_ItemGrid)
                            {

                                    @Item.Item_Id

                                    @Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { @class = "form-control" } })

                                    @Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { @class = "form-control", id = "UomId" })

                            }

Java Script :
 $('#Item_Item_Name').autocomplete({

    source: function (request, response) {
        debugger;
        var param = { ItemName: $('#Item_Item_Name').val() };
        $.ajax({
            url: "/WDE/GetAutoCompleteItemList",
            data: JSON.stringify(param),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                response($.map(data, function (item) {
                    return {
                        val: item.split('÷')[0],
                        label: item.split('÷')[1]

                    }
                }))
            },
            error: function (response) {
                alert(response.responseText);
            },
            failure: function (response) {
                alert(response.responseText);
            }
        });
    },
    change: function (e, i) {
        if (i.item) {

        }
        else {
            $('#Item_Item_Name').val('');
            $('#Item_Item_Id').val('');
        }
    },
    select: function (e, i) {
        debugger;
        $('#Item_Item_Name').val(i.item.label);
        $(this).closest("tr").find("td").eq(2).html(i.item.val);

    },
    minLength: 1
});

A: Your autocomplete() call works only on the elements that are in the dom the time you call it. So for dynamically added elements you'll need the call the function again (after the new row was added).
One more thing to notice is that any call using the element id ($('#Item_Item_Name')) will work only for the first element with that id, because ids are meant to be unique. So you'll need to change the selector to get the input from the new row.
Create a function that inits the autocomplete And after every row you add, call that function on the element you want.
function initAutoComplete(elem) {
    $(elem).autocomplete({ /* the same as you use now */ });
}
// after you addded the new row
initAutoComplete($(newRow).find('.autocopmlete-input'));


text:
Q: Save temporary data with CakePhp I am looking for a solution in CakePhp, to store and read temporary datas :
I read some XML from others websites in order to display some news in my website, but on each page load, it does a call to the other xml websites.
Is there a way (memcached like) to save temp. data in CakePhp in order to store data for 1 hour and read  temp. data to display them in my webpages ; then 1 hour after update them (with cron) ?
Thanks.

A: CakePHP Caching seems what you'd want.
WHICH cache you use (Redis, Memcache...etc) would be up to you though.  Set your cache to last an hour, and you're all set.  (read more about cache on the link above).
If you're on CakePHP 2.5+, you can use the remember method described here.
public function newest() {
    $model = $this;
    return Cache::remember('newest_posts', function() use ($model){
        // get your data from whatever source here, and return it
        return $model->getMyData();
    }, 'long');
}

Basically, this just checks to see if the cache key exists, and if not, runs some code in order to populate it again.
If you're below 2.5, you can do the same basic thing, but without the remember:
public function newest() {
    $result = Cache::read('newest_posts', 'long');
    if (!$result) {
        // get your data from whatever source here, and write it
        Cache::write('newest_posts', $this->getMyData(), 'long');
    }
    return $result;
}

If you don't have a cache engine installed or are aren't wanting to mess w/ your own server, there are companies that you can use for cache, and you can just set your cache settings to connect to them.  ObjectRocket (Redis) is the one I know offhand, but I'm sure there are plenty.
One of many awesome things about CakePHP, is that in this case, your code doesn't change regardless of Cache type/location/configuration you choose.


text:
Q: Dynamic ionic 2 tabs im trying to make dynamic tabs from an array in the .ts file.
I got this template as multi-tab component:
<ion-content class="myclass">
  <ion-tabs tabsPlacement="top">
    <ion-tab *ngFor="let tab of tabs" tabTitle="tab.title" [root]="tab.component"></ion-tab>
  </ion-tabs>
</ion-content>

This is my multitab.ts component:
@Component({
  selector: 'multi-tab',
  templateUrl: 'multitab.html'
})
export class multiTab {

  tabs : any = [];

  constructor() {
      this.tabs.push({title: 'Snacks',  component: Snacks});
      this.tabs.push({title: 'Drinks',  component: Drinks});
      this.tabs.push({title: 'Frozen',  component: Frozen});
  }
}

But my custom component its only showing the first one with all functionality like it was a single tab/list not an ion-tabs.
Im using 2.0.0 rc-2 version of ionic.

A: I found the answer, my tabbar its just under the header, thats why its seems like it doesn't appear. I post this if someone has this problem too.


text:
Q: Redirect output to a file while piping cat and perl I need to shuffle lines in a text file and store the result into a new text file.
This is the command I used. However, this prints the shuffled lines into the console not the outfile.
cat infile | perl -MList::Util=shuffle -e 'srand 123; print shuffle(<>);' "$@"; > outfile

A: the unprotected semicolon is the culprit
It just stops the current command and starts another empty one (creates an empty file).
note that the extra "$@"arguments of perl are useless here, and so is the use of cat. So to sum it all you could write:
perl -MList::Util=shuffle -e 'srand 123; print shuffle(<>);' infile > outfile

A: Removing the last ; makes it work.
cat infile | perl -MList::Util=shuffle -e 'srand 123; print shuffle(<>);' "$@" > outfile


text:
Q: Retrofit - Not sending network call when app is closed/background I am using Retrofit2 with OkHttp. Everything is working fine with it except the one thing - a network call when app is closed or in background.
Working
Whenever Firebase notification arrives, I make a network call to fetch data related to that notification and then show notification.
Scenario
Consider an Android app which is in the background or closed and notification arrived.
What's Happening
Notification arrives successfully, I can see it. But when I try to make a call, it is always giving an error Failed to connect to: ******* and I can't see any call coming on the server.
I have seen some similar type of issues, but none of them could help me.
Here's a list:

*

*https://github.com/square/okhttp/issues/1771

*https://github.com/square/okhttp/issues/3146

*https://github.com/square/okhttp/issues/1037

*https://github.com/square/okhttp/issues/1792
Some suggested to use connectionPool and some to use pingInterval. Nothing worked in my case. I am not sure if it's a bug of Retrofit or OkHttp.
Below is the piece of code I am using for the call. Remember that it's working perfectly fine when app is in foreground.
OkHttpClient.Builder builder = getHttpBuilder()
        .connectionSpecs(getSpecList());

retrofit = new Retrofit.Builder()
        .baseUrl(Session.getBaseUrl())
        .client(builder.build())
        .build();

Call<ResponseBody> call = retrofit
        .create(Webservice.class)
        .pullNotify(authToken, ivB64, digest, Session.getTimestamp());
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        listener.onNetworkCallSuccess(response);
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        listener.onNetworkCallFailure(t);
    }
});

It always returns SocketTimeoutException. Any help/guidance is appreciated.

A: I not sure, but you can test
var GLOBAL_CONNECTION_POOL = ConnectionPool(5, 1, TimeUnit.MINUTES)
private fun createClient(): OkHttpClient? {
        try {
            val trustAllManager = object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}

                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}

                override fun getAcceptedIssuers(): Array<X509Certificate> {
                    return arrayOf()
                }
            }
            val trustAllCerts = arrayOf<TrustManager>(trustAllManager)

            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())
            val sslSocketFactory = sslContext.socketFactory

            val builder = OkHttpClient.Builder()
            builder.followRedirects(false)
            builder.sslSocketFactory(sslSocketFactory, trustAllManager)
            builder.hostnameVerifier { hostname, session -> true }
            builder.readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
            builder.connectionPool(GLOBAL_CONNECTION_POOL)
            builder.addInterceptor(logging)

            return builder.build()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

and change:
retrofit = new Retrofit.Builder()
    .baseUrl(Session.getBaseUrl())
    .client(createClient())
    .build();

A: To activate some events in the background, you need to use services.
It can be done by using forground service or background service.
Forground service: https://robertohuertas.com/2019/06/29/android_foreground_services/
check: Work manager, Alarm manager also


text:
Q: Firebase Cloud Message iOS Swift not working I got two iOS Swift Apps. The first one already exists in the App Store, let's say it is called "ExistingStoreApp". The second App I created only to test Push-Notifications with Firebase Cloud Messaging (FCM), I call it "PushyTestApp".
What I do not understand: Sending Push-Notifications via Firebase-Console -> Notifications only works in PushyTestApp, but not with the ExistingStoreApp, although i did the same procedure on my ExistingStoreApp to make Firebase run.
I did the following:

*

*Create APNs AuthenticationKey in Apple Dev. Console (https://firebase.google.com/docs/cloud-messaging/ios/certs)

*Create App ID with explicit Bundle-ID (Difference between ExistingStoreApp and PushyTestApp here: ExistingStoreApp-App-ID already exists)

*Create Provisioning-Profile

*Create App (difference: ExistingStoreApp already exists)

*Add CocoaPods with pod 'Firebase/Core' & pod 'Firebase/Messaging' -> pod install (https://firebase.google.com/docs/cloud-messaging/ios/client)

*In Xcode App-Capabilities: Push Notifications turn ON, Remote Notifications under Background Modes turn ON

*Use Existing Firebase-Project (Android running and working) and add new iOS App

*Upload APN AuthKey to Firebase-Project-App

*Download GoogleService-Info.plist -> Add to XCODE-Source dir

*Fill AppDelegate.swift with example Code (https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExamapleSwift/AppDelegate.swift)

*Send Message via Firebase-Console with priority: high

result: PushyTestApp connected successful to Firebase, got FCM-Token, shows Message-content in XCODE-console. ExistingStoreApp connected successful to Firebase, got FCM-Token, no reaction when sending message with Firebase-Console.
I did not disable Method Sizzling. Which part did I miss? I thought it would be the Bundle-ID which is not conventional ("My-Company.My-Appname") but a similar Bundle-ID worked with PushyTestApp. Is it because the ExistingStoreApp is already a distributed App, an PushyTestApp is Development?

A: Ok, here comes the most strangest solution: Giving almost up the fight, I uploaded my App-Update to the App-Store with Firebase in code included. The AppStore told me to update my 1024pt App-Icon. I changed it, looked around in my Media.xcassets in XCode and spotted, that I had no icons for notifications defined. Added them, uploaded again to App-Store.
I tried one last time to send again a msg over Firebase-Console and bing: Message received on iPhone. speechless.
Hope somebody helps this before going berserk


text:
Q: I am getting an error when i was making a new react - native app Uncaught TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_4__.initializeApp is not a function
This is a error which is coming when I am making a new react - native app
CODE :
import { ActivityIndicator, StyleSheet, View } from 'react-native'
import React from 'react';
import * as firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/database';

class LoadingScreen extends React.Component {

    componentDidMount() {
        this.checkIfLoggedIn();
    };

    checkIfLoggedIn = () => {
        firebase.auth().onAuthStateChanged(user => {
            if (user) {
                this.props.navigation.navigate('DashboardScreen')
            } else {
                this.props.navigation.navigate('LoginScreen')
            };
        });
    };

    render() {
        return (
            <View style={styles.container}>
                <ActivityIndicator size="large" />
            </View>
        )
    }
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
});

export default LoadingScreen;

A: I see a few concerns/problems with the above code:

*

*use of compat is not encouraged ; Firebase explicitly stated that this is a stop-gap measure for people with large v8 code bases that need to move to v9 but want to stick with the v8 syntax -- and that the v8 syntax (and compat) are to be deprecated in the very near future

*though Class Components remain valid in React, as you build new code I recommend you consider moving to Function Components

*there does not seem to be any attempt in your code to shut off the onAuthStateChanged() listener ; this is a resource leak in your code

*it is hard to tell why that particular error is occurring ; you say that you initialize Firebase in a different file so we can't see how it is initialized

*the above code relies on the "default app" (your use of firebase.auth() without specifying the particular app) -- without knowing how you initialized Firebase we can't tell if that is "doing the right thing"

*I would encourage you to NOT rely on a "default app" but to explicitly specify the app you are invoking the Authentication service from

BTW: I have moved to using the Context API for initializing Firebase and sharing its services to the rest of my app.  You can see this pattern in the FirebaseProvider.js of the following starter project.  Feel free to use/copy as you see fit: https://github.com/gregfenton/react-and-user-profiles-with-firebase-auth-and-firestore


text:
Q: Try import java.util Cannot resolve symbol 'java' In IDEA IDE I met this problem. I tried to import java.util
compiler setting
my pom.xml:

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

A: I figure it out when I reboot my IDEA.
I think it is because I download new jdk jdk17.


text:
Q: Spaces in multi characters variable name in pandoc export to docx I'm writing a Haskell program to export some mathematics formula to docx and I have noted that variable names with multiple character are written with a blank white space between each letter and I don't understand why ?
My basic code is :
import Text.Pandoc
import Data.Map (fromList)
import qualified Data.ByteString.Lazy as B

main = do
  document <- writeDocx WriterOptions{ writerStandalone=False
                                     , writerReferenceDocx=Nothing
                                     , writerUserDataDir=Nothing
                                     , writerHighlight= False
                                     }  pandoc
  B.writeFile "document.docx" document

pandoc = Pandoc ( Meta {unMeta = fromList []})
                           [ Para  [Str "A small Math example"]
                           , Plain [Math InlineMath "A_e = var + 5"]
                           , HorizontalRule
                           ]

and the result is :

and I would like to get :

I tried to modify the string defining my equation  to
Math InlineMath "A_e = {var} + 5"

but It didn't change anything
I also tried :
Math InlineMath "A_e = \\{var\\} + 5"

But It gave :

Do you know how to remove these boring white spaces ?

A: It's actually texmath that takes care of the latex->omml conversion (OMML is the xml format that docx uses). So you should post a bug there.


text:
Q: Unpartitioned data has persisted in S3 after adding partition to delta table I have a delta table with a destination in S3 created as such:
(
    df
    .write
    .mode('append')
    .option('path', 's3://<s3_path')
    .saveAsTable(<table_name>)
)

The data was originally written unpartitioned and I sought to add a partition as such:
(
    spark
    .table(<table_name>)
    .write
    .mode('overwrite')
    .option('overwriteSchema', 'true')
    .option('path', 's3://<s3_path>')
    .partitionBy(<partition_column>)
    .saveAsTable(<table_name>)
)

The data now exists in s3_path in its unpartitioned form (all *.snappy.parquet files at the prefix) and in it's partitioned form partition_column=X,Y,Z. How can I go about cleaning up the unpartitioned "old" data without affecting the table? I don't feel like manually deleting those .parquet files is correct, and a VACUUM command isn't working.
I disabled the VACUUM retention duration check as such and ran a dry run vacuum retaining only latest 3 hours (it's been 2 hours since re-partition overwrite according to DESCRIBE HISTORY <table_name), but returned no files. I've also confirmed through table versions that the row count of all append operations is equal to the number of rows created in the overwrite with partitions.
SET spark.databricks.delta.retentionDurationCheck.enabled = false;
VACUUM <table_name> RETAIN 3 HOURS DRY RUN;


text:
Q: Quick Sort VBA by Columns (Horizontally) I'm trying to sort by columns with a 2D array containing N Rows * 15 Columns.
I saw the quicksort algorithm but it only works for sorting Rows (Vertically).
What I need is sort by Columns. Does anybody help me to get that?
Here is my attempt
Public Arr As Variant
Public Sub QuickSortHorizontally()
Dim i As Integer, j As Integer, k As Integer

Dim LbdArr As Integer, UbdArr As Integer, Pvt As Integer
LbdArr = 1
UbdArr = 15

For i = LBound(Mtz, 1) To UBound(arr, 1)
    For j = LBound(arr, 2) - 1 To UBound(arr, 2) - 1
        For k = LBound(arr, 2) To UBound(arr, 2)
            Pvt = arr(i, UBound(arr, 2))
            If arr(i, k) <= Pvt Then
                arr(i, k) = arr(k, i)
            End If
            Debug.Print arr(i, k) 'Just to see if it works
        Next k
    Next j
Next i
End Sub

A: I don't know if I really understand what you want, but try this:
Sub SortAllCols()
Dim ws As Worksheet
Dim cols, rows As Long

Set ws = ActiveSheet
cols = ws.UsedRange.Columns.Count
rows = ws.UsedRange.Rows.Count

For i = 1 To rows
    ws.Range(Cells(i, 1), Cells(i, cols)).Select
    ws.Sort.SortFields.Clear
    ws.Sort.SortFields.Add Key:=Range(Cells(i, 1), Cells(i, cols)), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ws.Sort
        .SetRange Range(Cells(i, 1), Cells(i, cols))
        .MatchCase = False
        .Orientation = xlLeftToRight
        .SortMethod = xlPinYin
        .Apply
    End With

Next i

End Sub


text:
Q: Reverse Sort a stream I want to reverse sort a stream such as below but getting compile time error as "The method sorted() in the type IntStream is not applicable for the arguments ((<no type> o1, <no type> o2) -> {})". Can anyone correct this
IntStream.range(1, 100)
         .filter(x -> x%2 != 0)
         .sorted((o1,o2) -> -o1.compareTo(o2))
         .forEach(System.out::println);

A: If that is your real code, then it may be more efficient to use IntStream.iterate and generate numbers from 99 to 0:
IntStream.iterate(99, i -> i - 1)
    .limit(100)
    .filter(x -> x % 2 != 0)
    .forEachOrdered(System.out::println);

A: How about simple util such as :
private IntStream reverseSort(int from, int to) {
    return IntStream.range(from, to)
                    .filter(x -> x % 2 != 0)
                    .sorted()
                    .map(i -> to - i + from - 1);
}

Credits: Stuart Marks for the reverse util.

A: Explanation
since you're working with an IntStream it only has one overload of the sorted method and it's the natural order (which makes sense).
instead, box the stream from IntStream to Stream<Integer> then it should suffice:
 IntStream.range(1, 100)
          .filter(x -> x % 2 != 0)
          .boxed()  // <--- boxed to Stream<Integer>
          .sorted((o1,o2) -> -o1.compareTo(o2)) // now we can call compareTo on Integer
          .forEach(System.out::println);

However, as mentioned by @Holger in the comments:

never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It
  is perfectly legal for a compareTo implementation to return
  Integer.MIN_VALUE, in which case negation will fail and produce
  inconsistent results. A valid reverse comparator would be (o1,o2) ->
  o2.compareTo(o1)

 Suggestions to improve your code. JDK8
A better approach would be:
IntStream.range(1, 100)
         .filter(x -> x % 2 != 0)
         .boxed()
         .sorted(Comparator.reverseOrder())
         .forEachOrdered(System.out::println);

why?

*

*There's already a built-in comparator to perform reverse order as shown above.

*if you want to guarantee that the elements are to be seen in the sorted order when printing then utilise forEachOrdered (big shout out to @Holger for always reminding me)

or as suggested by @Holger it can all be simplified to as little as this:
 IntStream.range(0, 50)
          .map(i -> 99-i*2)
          .forEachOrdered(System.out::println);

JDK9 variant
btw, in JDK9 starting from the code in your post, you can first simplify it via iterate to:
IntStream.iterate(1, i  -> i <= 99, i -> i + 2)
         .boxed()
         .sorted(Comparator.reverseOrder())
         .forEachOrdered(System.out::println);

With this approach, we can avoid the filter intermediate operation and increment in 2's.
and finally you could simplify it even further with:
IntStream.iterate(99, i  -> i > 0 , i -> i - 2)
         .forEachOrdered(System.out::println);

With this approach, we can avoid filter, boxed,sorted et al.


text:
Q: How do I change an image "B" by hovering over a linked image A without JavaScript only CSS I am trying to change a picture "B" when I hover over a linked picture "A"
Similar to this http://jsfiddle.net/davidThomas/JsX8x/1

but in this example I would like the first picture to also be linked to another page.
When I try to link this picture it breaks the picture change of image B
Any insight would be helpful
Clarification (from comment):
I would like to change one picture based on a variety of links.
the example page is here: http://mouco.com/testerre
I would like the super friends picture to change based on the link chosen.
Also having the link change too....
on the page the only link that has a rollover is the "history" link, but I would like all of them to change like this one, while changing the image on the side to a different image based on the link ...

A: Wrap the image in an "a" tag and change styles accordingly.
HTML

CSS
#a img.second,
#a a.first:hover ~ img.second {
    display: none;
}

#a a:hover ~ a.first {
    display: none;
}

#a a:hover ~ img.second {
    display: inline-block;
}

jsfiddle

A: Add a hypertext reference link around the image you'd like to use

    **