text:
Q: Reference request for Zermelo's construction of natural numbers I have heard that back in 1908 Zermelo proposed to use $\emptyset,\{\emptyset\},\{\{\emptyset\}\},\ldots$ as the natural numbers. However, later von Neumann proposed the alternative approach of defining natural numbers in the following way,
$$0=\emptyset\\1=\{0\}\\2=\{1,0\}\\\vdots$$My question is,

Where can I find the detailed construction of natural numbers in the way Zermelo proposed? It will also be very good if there be a comparative analysis of the von Neumann construction and the Zermelo construction.

I have searched internet for sometime but couldn't find anything relevant. Can anyone give me some reference regarding this?

A: The reason you are having difficulty finding such a reference is probably due to the fact that presentations of the natural numbers rarely deal with these construction directly. Instead we simply require an element $0 \in \mathbb{N}$ and a funciton $S : \mathbb{N} \to \mathbb{N}$ that gives the "successor" of each number. For the Zermelo naturals, $0 = \emptyset$ (as you mentioned) and $S(x) = \{ x \}$.
The typical construction proceeds by proving the Peano axioms for the given $\mathbb{N}$. The only part which will be significantly different in the case of Zermelo's naturals is proving that there exists a set $\mathbb{N}$ s.t. $\forall x \in \mathbb{N} \; S(x) \in \mathbb{N}$ (i.e. that there is a set which contains "all" the natural numbers). This requires invocation of the axiom of infinity. If you look at the definition of that axiom, you can see that the axiom in fact directly asserts that there exists a set which contains the von Neumann naturals, which is probably part of the reason presentations use this construction.
To prove the existence of such a set for Zermelo's naturals, the easiest way I can think of is establishing a bijection between the von Neumann naturals and Zermelo's, and then using the axiom schema of replacement.
The other interesting part of the Peano axioms is the induction axiom. The same proof that works for the von Neumann naturals (detailed here) will also work if we use the bijection between the Zermelo and von Neumann naturals again.


text:
Q: Unable to select an element via XPath in selenium Webdriver python I am trying to run a script in selenium webdriver python. Where I am trying to click on search field, but its always showing exception of "An element could not be located on the page using the given search parameters."
Here is script:
 from selenium import webdriver
    from selenium.webdriver.common.by import By
    class Exercise:
        def safari(self):
            class Exercise:
def safari(self):
    driver = webdriver.Safari()
    driver.maximize_window()
    url= "https://www.airbnb.com"
    driver.implicitly_wait(15)
    Title = driver.title
    driver.get(url)
    CurrentURL = driver.current_url
    print("Current URL is "+CurrentURL)
    SearchButton =driver.find_element(By.XPATH, "//*[@id='GeocompleteController-via-SearchBarV2-SearchBarV2']")
    SearchButton.click()

note= Exercise()
note.safari()

Please Tell me, where I am wrong?

A: There appears to be two matching cases:

The one that matches the search bar is actually the second one. So you'd edit your XPath as follows:
SearchButton = driver.find_element(By.XPATH, "(//*[@id='GeocompleteController-via-SearchBarV2-SearchBarV2'])[2]")

Or simply:
SearchButton = driver.find_element_by_xpath("(//*[@id='GeocompleteController-via-SearchBarV2-SearchBarV2'])[2]")

You can paste your XPath in Chrome's Inspector tool (as seen above) by loading the same website in Google Chrome and hitting F12 (or just right click anywhere and click "Inspect"). This gives you the matching elements. If you scroll to 2 of 2 it highlights the search bar. Therefore, we want the second result. XPath indices start at 1 unlike most languages (which usually have indices start at 0), so to get the second index, encapsulate the entire original XPath in parentheses and then add [2] next to it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Application has stopped-Android studio I've been searching forums, but it seems that I'm pretty much the only one with this problem.I've created a simple layout with a button in it using java file.However, when I run it, I get error "Application has stopped".When I create a button in xml file it's working fine.Everything's imported as I'm not getting any errors.Here's the code:
public class MainActivity extends AppCompatActivity {

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

        RelativeLayout r=new RelativeLayout(this);

        Button b=new Button(this);
        r.setBackgroundColor(Color.BLACK);
        b.setText("KEK");
        r.addView(b);

        setContentView(r);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

A: The problem is this
    RelativeLayout r=new RelativeLayout(this);

    Button b=new Button(this);
    r.setBackgroundColor(Color.BLACK);
    b.setText("KEK");
    r.addView(b);

You should declare a xml file to your setContentView() otherwise you won't be able to call findViewById()
EDIT
Let's say a few issues I found.
If you do this setContentView(r);
You should declare Id's for each view on your r
If you want to use r as a View you'll have to add the Toolbar since you are trying to findViewById() and in your r there are not a Toolbar and the same with FloatingActionButton.
Note: If you want to use your r view add all of the views that you want to use on it, otherwise it will always crash.

A: You can't use findViewById(R.id.something) if you doesn't have set a content view from an XML layout where these IDs are contained.
If you wouldn't use any XML layout, you must create all views by yourself like:
//with the right arguments passed at the constructor
Toolbar toolbar = new Toolbar();
FloatingActionButton fab = new FloatingActionButton();


text:
Q: How to get the associated data using the foreign key I am trying to write a function that look for the profile of a user or create one if it doesn't exists.
I have used getBy and selectFirst to get the profile of a given user, but I get this error:
Couldn't match type 'HandlerFor site0' with 'Key'
I am using the scaffolding site with postgres.
This is my model (user and profile have a one-to-one relationship)
User
    email Text
    password Text Maybe
    verkey Text Maybe
    verified Bool
    UniqueUser email
    deriving Typeable

Profile
    name Text
    userId UserId
    UniqueName name
    UniqueUserId userId
    deriving Typeable

The function is as follow:
getOrCreateProfile :: UserId -> ProfileId
getOrCreateProfile userId = do
    mProfile <- runDB $ getBy $ UniqueUserId userId
    case mProfile of
        Just (Entity pid _) -> return pid
        Nothing  -> undefined -- insert profile

The error I am getting is:
    • Couldn't match type 'HandlerFor site0' with 'Key'
      Expected type: Key (Maybe (Entity Profile))
        Actual type: HandlerFor site0 (Maybe (Entity Profile))
    • In a stmt of a 'do' block:
        mProfile <- runDB $ getBy $ UniqueUserId userId
      In the expression:
        do mProfile <- runDB $ getBy $ UniqueUserId userId
           case mProfile of
             Just (Entity pid _) -> pid
             Nothing -> undefined
      In an equation for 'getOrCreateProfile':
          getOrCreateProfile userId
            = do mProfile <- runDB $ getBy $ UniqueUserId userId
                 case mProfile of
                   Just (Entity pid _) -> pid
                   Nothing -> undefined
   |
45 |     mProfile <- runDB $ getBy $ UniqueUserId userId
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

What am I doing wrong? What's the proper way to do this query?

A: If you look at runDB's type signature:
runDB :: YesodDB site a -> HandlerFor site a

you'll see what the problem is.
Yesod requires you to do some rather elaborate stuff to actually use the query's results - it isn't simply a (Maybe result). You can find examples here; this part in particular:
people <- runDB $ selectList [] [Asc PersonAge]
defaultLayout
        [whamlet|

                $forall Entity personid person <- people

                        #{personFirstName person}
        |]

Hope this helps.

A: This is compiling
getOrCreateProfile :: UserId -> Handler ProfileId
getOrCreateProfile userId = runDB $ do
    mProfile <- getBy $ UniqueUserId userId
    case mProfile of
        Just (Entity pid _) -> return pid
        Nothing  -> insert $ Profile getTempProfile userId


text:
Q: Can the verb "underline" be used to emphasise a word? Example:

You will never do that again and I underline never!

Probably "and I mean it" is used this way.

A: As you surmise, the usage is metaphorical, suggesting that if it were written, it would be emphasized with an underline. Verbalizing punctuation or other mechanics is not uncommon in informal speech.

You will never do that again, period [full stop]!
You will capital-N never do that again!
You will never do that again, dot dot dot, never!

A: You are brilliant. Absolutely brilliant idiomatic usage of language. However, when writing it I would write it either as

You will never do that again and I underline never!

Or,

You will never do that again and I underline "never"!

When spoken, it would reinforce comprehension to do a brief Harlem shake when enunciating the word "never".
Or, provide a more executive feel, by doing the traditional quotation marks finger gestures for the word "never".
Or, say the sentence in a more stuffy way

You will never do that again and I underline quote-unquote never!


text:
Q: Using template driven form with dynamic input list (ngFor) I am new to web development and is working on a MEAN stack project using angular2.
I am trying to add template-driven form with dynamic list of input using ngFor - however I did observe an abnormal behavior with the way I implement it. I am wondering if I am doing it the right way...
Abnormal behavior: If I were to add 2 or more input field and remove the non-last-entries input, the next time i add the new entries, it resets all the entries below the one I just deleted. In addition, somehow the new entries are binding with the entries above?
demo of the issue
Here is my plunker:
http://plnkr.co/edit/FjLg8VDDo3E6fHVgS8ah?p=preview
Here is the way that I implement template driven form with dynamic input using ngFor. I was referring to another stackoverflow post:angular-2-template-driven-form-with-ngfor-inputs

            Name
            <input type="text" class="form-control" id="name"
                   required
                   [(ngModel)]="hero.name" name="name-{{i}}"
                   #name="ngModel" >

              Name is required

Any help is appreciated. Thanks!

A: I like questions with the demonstration on the Plunkr:)
I suppose that the problem is related with your name property. It should be unique name. Using index as unique value is wrong. It will be mixed after changing your array.
So i offer you to use id as unique name:
let uniqueId = 1;
...
addNewHero(){
  var hero: Hero  = new Hero(uniqueId++,'','');
  this.heroArray.push(hero);
}

and in html:
<input type="text" ... name="name-{{hero.id}}">

Here is the Plunker


text:
Q: Why would a custom SharePoint timer job work on only half the items in a list? We have a timer job that checks the SharePoint User Profile service for a users location and title, then updates the metadata for a page library of offices with the associated manager. We recently updated the logic, published and ran it in our QA environment and some pages do get updated, some don't. Roughly half are unchanged, despite having managers in the User Profile Service. Why would the same code to fail on half the pages?
The list has columns for Office, Manager, etc. The code cycles through each profile and if a user has the title "Manager" and the office "Seattle" in their profile, it searches the library and sets that user as the manager and publishes the page. All the pages are based on a common content type.
Tried clearing all the manager fields on all pages & half of them update. The users that fail do have user profiles and I can set the manager manually. What could cause it to fail on only some pages?
Here's the code. In the GetOfficeManagers method I loop through them twice, once to set Managers in Training, then to overwrite them with full managers if they exist (some only have managers in training). This is the change I made to the code.
//using statements snipped for brevity

namespace RC.SharePoint.Portal.TimerJobs
{
public class SyncOfficeLocationService: SPJobDefinition
{

    #region CONSTANTS

    public const string JOB_NAME = "World Office Location Synchronization Service";
    public const string TIMER_JOB_META_DATA = "TimerJobMetaData";
    private const string PAGES_LIBRARY = "Pages";
    private const string USER_PROFILE_FIELD_OFFICE = "Office";
    private const string USER_PROFILE_FIELD_TITLE = "Title";
    private const string USER_PROFILE_FIELD_DEPT = "Department";
    private const string USER_PROFILE_DEPT_REST_OP = "Office Operations";
    private const string Office_PROFILE_CONTENT_TYPE = "Office Profile";
    private const string Office_SITE_NAME = "rest";

    private struct Designations
    {
        public const string General_Manager = "General Manager";
        public const string General_Manager_In_Training = "General Manager in Training";
        public const string ManagingPartner = "Managing Partner";
        public const string ManagingPartner_In_Training = "Managing Partner in Training";
        public const string OperationsManager = "Operations Manager";
        public const string OperationsManager_In_Training = "Operations Manager in Training";
        public const string ShiftManager = "Shift Manager";
        public const string ShiftManager_In_Training = "Shift Manager in Training";
    }

    private struct Pages
    {
        public const string Title = "Title";
        public const string ContentType = "ContentType";
        public const string Name = "Name";
        public const string NameInt = "FileLeafRef";
        public const string GeneralManager = "General Manager";
        public const string GeneralManagerInt = "RC_RestProfile_GeneralManager";
        public const string ManagingPartner = "Managing Partner";
        public const string ManagingPartnerInt = "RC_RestProfile_ManagingPartner";
        public const string OperationsManager = "Operations Manager";
        public const string OperationsManagerInt = "RC_RestProfile_OperationsManager";
        public const string ShiftManager1 = "Shift Manager 1";
        public const string ShiftManager1Int = "RC_RestProfile_ShiftManager1";
        public const string ShiftManager2 = "Shift Manager 2";
        public const string ShiftManager2Int = "RC_RestProfile_ShiftManager2";
        //snipped for space
    }

    #endregion

    #region CONSTRUCTORS
    public SyncOfficeLocationService()
        : base()
    {
    }

    public SyncOfficeLocationService(string jobName, SPService service, SPServer server, SPJobLockType targetType)
        : base(jobName, service, server, targetType)
    {
    }

    public SyncOfficeLocationService(string jobName, SPWebApplication webApplication)
        : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
    {
        this.Title = jobName;
    }

    #endregion

    #region METHODS

    protected override bool HasAdditionalUpdateAccess()
    {
        return true;
    }

    public override void Execute(Guid targetInstanceId)
    {
        try
        {
            //Read settings from Hierarchical object store
            TimerJobMetaData settings = this.WebApplication.GetChild<TimerJobMetaData>(TIMER_JOB_META_DATA);

            using (SPSite site = new SPSite(settings.SiteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Medium, EventSeverity.Information), TraceSeverity.Medium, string.Format("Timer Service started for SharePoint portal: {0}", web.Url), "");

                    List<OfficeLocation> Offices = GetOfficeManagers(site);
                    SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Medium, EventSeverity.Information), TraceSeverity.Medium, "User profile service parsed successfully. " + Offices.Count.ToString() + " Offices found.", "");
                    SyncOfficeManagers(web.Webs[Office_SITE_NAME], Offices);

                    SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Medium, EventSeverity.Information), TraceSeverity.Medium, string.Format("Timer Service finished for SharePoint portal: {0}", web.Url), "");
                }
            }
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }
    }

    private Dictionary<string, string> GetUserProfiles(SPSite site)
    {
        Dictionary<string, string> users = new Dictionary<string, string>();
        try
        {
            SPServiceContext serverContext = SPServiceContext.GetContext(site);
            UserProfileManager profileManager = new UserProfileManager(serverContext);
            IEnumerator userProfiles = profileManager.GetEnumerator();
            while (userProfiles.MoveNext())
            {
                UserProfile userProfile = (UserProfile)userProfiles.Current;
                if (userProfile[USER_PROFILE_FIELD_TITLE] != null && userProfile[USER_PROFILE_FIELD_TITLE].Value != null && userProfile[USER_PROFILE_FIELD_TITLE].Value.ToString().Equals(Designations.General_Manager))
                {
                    if (userProfile[USER_PROFILE_FIELD_OFFICE] != null && userProfile[USER_PROFILE_FIELD_OFFICE].Value != null)
                    {
                        string key = string.Format("{0}.aspx", userProfile[USER_PROFILE_FIELD_OFFICE].Value.ToString().Replace("RC ", "C"));
                        if (!users.ContainsKey(key))
                            users.Add(key, userProfile.AccountName);
                    }
                }
            }
        }
        catch(Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }
        return users;
    }

    private void SyncOffices(SPWeb web, Dictionary<string, string> users)
    {
        try
        {
            SPDocumentLibrary pagesLib = web.Lists[PAGES_LIBRARY] as SPDocumentLibrary;
            SPClaimProviderManager cpm = SPClaimProviderManager.Local;
            SPWeb rootWeb = web.Site.RootWeb;

            var query = new SPQuery();
            query.Query = string.Format(@"<Where><Eq><FieldRef Name=""{0}"" /><Value Type=""Text"">{1}</Value></Eq></Where>", Pages.ContentType, Office_PROFILE_CONTENT_TYPE);
            query.ViewFields = string.Format(@"<FieldRef Name=""{0}"" /><FieldRef Name=""{1}"" /><FieldRef Name=""{2}"" /><FieldRef Name=""{3}"" />", Pages.ContentType, Pages.Title, Pages.NameInt, Pages.GeneralManagerInt);
            query.ViewAttributes = @"Scope=""Recursive""";
            query.RowLimit = 0;

            SPListItemCollection items = pagesLib.GetItems(query);
            foreach (SPListItem item in items)
            {
                string fileName = item[Pages.Name].ToString();
                if (users.ContainsKey(fileName))
                {
                    string mgr = string.Empty;
                    if (item[Pages.GeneralManager] != null)
                    {
                        mgr = new SPFieldUserValue(web, item[Pages.GeneralManager].ToString()).User.LoginName;
                    }

                    if (!mgr.EndsWith(users[fileName]))
                    {
                        SPFile file = item.File;
                        if (file.CheckOutType == SPFile.SPCheckOutType.None)
                            file.CheckOut();

                        SPClaim userClaim = cpm.ConvertIdentifierToClaim(users[fileName], SPIdentifierTypes.WindowsSamAccountName);
                        SPUser newMgr = rootWeb.EnsureUser(userClaim.ToEncodedString());
                        item[Pages.GeneralManager] = new SPFieldUserValue(web, newMgr.ID, newMgr.Name);
                        item.Update();
                        file.CheckIn("Automatically checked-in by SharePoint Synchronization Timer Job");
                        file.Publish("Automatically published by SharePoint Synchronization Timer Job");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }
    }

    private List<OfficeLocation> GetOfficeManagers(SPSite site)
    {
        List<OfficeLocation> Offices = new List<OfficeLocation>();
        try
        {
            SPServiceContext serverContext = SPServiceContext.GetContext(site);
            UserProfileManager profileManager = new UserProfileManager(serverContext);
            IEnumerator userProfiles = profileManager.GetEnumerator();
            while (userProfiles.MoveNext())
            {
                UserProfile userProfile = (UserProfile)userProfiles.Current;
                //Check for department name, it must be "Office Operations"
                if (userProfile[USER_PROFILE_FIELD_DEPT] != null && userProfile[USER_PROFILE_FIELD_DEPT].Value != null && userProfile[USER_PROFILE_FIELD_DEPT].Value.ToString().Equals(USER_PROFILE_DEPT_REST_OP))
                {
                    //Check for Office location, it must not be null or empty
                    if (userProfile[USER_PROFILE_FIELD_OFFICE] != null && userProfile[USER_PROFILE_FIELD_OFFICE].Value != null)
                    {
                        string location = userProfile[USER_PROFILE_FIELD_OFFICE].Value.ToString();
                        OfficeLocation Office = FindOffice(Offices, location);
                        if (Office == null)
                        {
                            Office = new OfficeLocation();
                            Office.Location = location;
                            Office.PageName = string.Format("{0}.aspx", location.Replace("RC ", "C"));
                            Offices.Add(Office);
                        }

                        if (userProfile[USER_PROFILE_FIELD_TITLE] != null && userProfile[USER_PROFILE_FIELD_TITLE].Value != null)
                        {
                            string designation = userProfile[USER_PROFILE_FIELD_TITLE].Value.ToString();
                            switch(designation)
                            {
                                case Designations.General_Manager_In_Training:
                                    Office.GeneralManager = userProfile.AccountName.ToLower();
                                    break;
                                case Designations.ManagingPartner_In_Training:
                                    Office.ManagingPartner = userProfile.AccountName.ToLower();
                                    break;
                                case Designations.OperationsManager_In_Training:
                                    Office.OperationsManager = userProfile.AccountName.ToLower();
                                    break;
                                case Designations.ShiftManager:
                                    Office.ShiftManagers.Add(userProfile.AccountName.ToLower());
                                    break;
                            }
                        }
                    }
                }
            }

            IEnumerator userProfiles2 = profileManager.GetEnumerator();
            while (userProfiles2.MoveNext())
            {
                UserProfile userProfile = (UserProfile)userProfiles2.Current;
                //Check for department name, it must be "Office Operations"
                if (userProfile[USER_PROFILE_FIELD_DEPT] != null && userProfile[USER_PROFILE_FIELD_DEPT].Value != null && userProfile[USER_PROFILE_FIELD_DEPT].Value.ToString().Equals(USER_PROFILE_DEPT_REST_OP))
                {
                    //Check for Office location, it must not be null or empty
                    if (userProfile[USER_PROFILE_FIELD_OFFICE] != null && userProfile[USER_PROFILE_FIELD_OFFICE].Value != null)
                    {
                        string location = userProfile[USER_PROFILE_FIELD_OFFICE].Value.ToString();
                        OfficeLocation Office = FindOffice(Offices, location);
                        if (Office == null)
                        {
                            Office = new OfficeLocation();
                            Office.Location = location;
                            Office.PageName = string.Format("{0}.aspx", location.Replace("RC ", "C"));
                            Offices.Add(Office);
                        }

                        if (userProfile[USER_PROFILE_FIELD_TITLE] != null && userProfile[USER_PROFILE_FIELD_TITLE].Value != null)
                        {
                            string designation = userProfile[USER_PROFILE_FIELD_TITLE].Value.ToString();
                            switch (designation)
                            {
                                case Designations.General_Manager:
                                    Office.GeneralManager = userProfile.AccountName.ToLower();
                                    break;
                                case Designations.ManagingPartner:
                                    Office.ManagingPartner = userProfile.AccountName.ToLower();
                                    break;
                                case Designations.OperationsManager:
                                    Office.OperationsManager = userProfile.AccountName.ToLower();
                                    break;
                                case Designations.ShiftManager_In_Training:
                                    Office.ShiftManagers.Add(userProfile.AccountName.ToLower());
                                    break;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }
        return Offices;
    }

    private void SyncOfficeManagers(SPWeb web, List<OfficeLocation> Offices)
    {
        try
        {
            SPDocumentLibrary pagesLib = web.Lists[PAGES_LIBRARY] as SPDocumentLibrary;
            SPClaimProviderManager cpm = SPClaimProviderManager.Local;
            SPWeb rootWeb = web.Site.RootWeb;
            SPClaim userClaim = null;
            SPUser newMgr = null;
            var query = new SPQuery();
            query.Query = string.Format(@"<Where><Eq><FieldRef Name=""{0}"" /><Value Type=""Text"">{1}</Value></Eq></Where>", Pages.ContentType, Office_PROFILE_CONTENT_TYPE);
            //query.ViewFields = string.Format(@"<FieldRef Name=""{0}"" /><FieldRef Name=""{1}"" /><FieldRef Name=""{2}"" /><FieldRef Name=""{3}"" />", Pages.ContentType, Pages.Title, Pages.NameInt, Pages.GeneralManagerInt);
            query.ViewAttributes = @"Scope=""Recursive""";
            query.RowLimit = 0;

            SPListItemCollection items = pagesLib.GetItems(query);
            foreach (SPListItem item in items)
            {
                string pageName = item[Pages.Name].ToString();
                OfficeLocation Office = FindOfficeByPageName(Offices, pageName);
                if (Office != null)
                {
                    bool updateItem = false;
                    string mgr = string.Empty;

                    #region General Manager
                    if (item[Pages.GeneralManager] != null)
                    {
                        mgr = new SPFieldUserValue(web, item[Pages.GeneralManager].ToString()).User.LoginName;
                    }

                    if (string.IsNullOrEmpty(Office.GeneralManager) && !string.IsNullOrEmpty(mgr))
                    {
                        item[Pages.GeneralManager] = null;
                        updateItem = true;
                    }
                    else if (!mgr.ToLower().EndsWith(Office.GeneralManager))
                    {
                        userClaim = cpm.ConvertIdentifierToClaim(Office.GeneralManager, SPIdentifierTypes.WindowsSamAccountName);
                        newMgr = rootWeb.EnsureUser(userClaim.ToEncodedString());
                        item[Pages.GeneralManager] = new SPFieldUserValue(web, newMgr.ID, newMgr.Name);
                        updateItem = true;
                    }
                    #endregion

                    #region Managing Partner
                    mgr = string.Empty;
                    if (item[Pages.ManagingPartner] != null)
                    {
                        mgr = new SPFieldUserValue(web, item[Pages.ManagingPartner].ToString()).User.LoginName;
                    }

                    if (string.IsNullOrEmpty(Office.ManagingPartner) && !string.IsNullOrEmpty(mgr))
                    {
                        item[Pages.ManagingPartner] = null;
                        updateItem = true;
                    }
                    else if (!mgr.ToLower().EndsWith(Office.ManagingPartner))
                    {
                        userClaim = cpm.ConvertIdentifierToClaim(Office.ManagingPartner, SPIdentifierTypes.WindowsSamAccountName);
                        newMgr = rootWeb.EnsureUser(userClaim.ToEncodedString());
                        item[Pages.ManagingPartner] = new SPFieldUserValue(web, newMgr.ID, newMgr.Name);
                        updateItem = true;
                    }
                    #endregion

                    #region Operations Manager
                    mgr = string.Empty;
                    if (item[Pages.OperationsManager] != null)
                    {
                        mgr = new SPFieldUserValue(web, item[Pages.OperationsManager].ToString()).User.LoginName;
                    }

                    if (string.IsNullOrEmpty(Office.OperationsManager) && !string.IsNullOrEmpty(mgr))
                    {
                        item[Pages.OperationsManager] = null;
                        updateItem = true;
                    }
                    else if (!mgr.ToLower().EndsWith(Office.OperationsManager))
                    {
                        userClaim = cpm.ConvertIdentifierToClaim(Office.OperationsManager, SPIdentifierTypes.WindowsSamAccountName);
                        newMgr = rootWeb.EnsureUser(userClaim.ToEncodedString());
                        item[Pages.OperationsManager] = new SPFieldUserValue(web, newMgr.ID, newMgr.Name);
                        updateItem = true;
                    }
                    #endregion

                    #region Shift Managers
                    for (int count = 0; count < 6; count++)
                    {
                        string shiftMgr = string.Empty;
                        if (Office.ShiftManagers.Count > count)
                            shiftMgr = Office.ShiftManagers[count];
                        string shiftMgrFieldName = GetShiftManagerFieldName(count + 1);
                        if (!string.IsNullOrEmpty(shiftMgrFieldName))
                        {
                            mgr = string.Empty;
                            if (item[shiftMgrFieldName] != null)
                            {
                                mgr = new SPFieldUserValue(web, item[shiftMgrFieldName].ToString()).User.LoginName;
                            }

                            if (string.IsNullOrEmpty(shiftMgr) && !string.IsNullOrEmpty(mgr))
                            {
                                item[shiftMgrFieldName] = null;
                                updateItem = true;
                            }
                            else if (!mgr.ToLower().EndsWith(shiftMgr))
                            {
                                userClaim = cpm.ConvertIdentifierToClaim(shiftMgr, SPIdentifierTypes.WindowsSamAccountName);
                                newMgr = rootWeb.EnsureUser(userClaim.ToEncodedString());
                                item[shiftMgrFieldName] = new SPFieldUserValue(web, newMgr.ID, newMgr.Name);
                                updateItem = true;
                            }
                        }
                    }
                    #endregion

                    if (updateItem)
                    {
                        SPFile file = item.File;
                        if (file.CheckOutType == SPFile.SPCheckOutType.None)
                            file.CheckOut();

                        item.Update();
                        file.CheckIn("Automatically checked-in by SharePoint Synchronization Timer Job");
                        file.Publish("Automatically published by SharePoint Synchronization Timer Job");
                        SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Medium, EventSeverity.Information), TraceSeverity.Medium, string.Format("Page {0} updated.", pageName), "");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("SharePoint Synchronization Timer Job", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }
    }

    private string GetShiftManagerFieldName(int count)
    {
        switch(count)
        {
            case 1:
                return Pages.ShiftManager1;
            case 2:
                return Pages.ShiftManager2;
            //snipped for brevity - goes to 6
        }

        return string.Empty;
    }

    private static OfficeLocation FindOffice(List<OfficeLocation> Offices, string location)
    {
        OfficeLocation Office = Offices.Find(
                              delegate(OfficeLocation r)
                              {
                                  return r.Location.Equals(location);
                              }
                          );

        return Office;
    }

    private static OfficeLocation FindOfficeByPageName(List<OfficeLocation> Offices, string pageName)
    {
        OfficeLocation Office = Offices.Find(
                              delegate(OfficeLocation r)
                              {
                                  return r.PageName.Equals(pageName);
                              }
                          );

        //Handle pages with name "C01.aspx"
        if (Office == null)
        {
            if (pageName.IndexOf("0") != 1)
            {
                pageName = pageName.Insert(1, "0");
                Office = Offices.Find(
                              delegate(OfficeLocation r)
                              {
                                  return r.PageName.Equals(pageName);
                              }
                          );
            }
        }

        //Handle pages with name "C1.aspx"
        if (Office == null)
        {
            if (pageName.IndexOf("0") != 2)
            {
                pageName = pageName.Insert(1, "0");
                Office = Offices.Find(
                              delegate(OfficeLocation r)
                              {
                                  return r.PageName.Equals(pageName);
                              }
                          );
            }
        }

        return Office;
    }

    #endregion

}

public class OfficeLocation
{
    public OfficeLocation()
    {
        Location = string.Empty;
        PageName = string.Empty;
        GeneralManager = string.Empty;
        ManagingPartner = string.Empty;
        OperationsManager = string.Empty;
        ShiftManagers = new StringCollection();
    }
    public string Location { get; set; }
    public string PageName { get; set; }
    public string GeneralManager { get; set; }
    public string ManagingPartner { get; set; }
    public string OperationsManager { get; set; }
    public StringCollection ShiftManagers { get; set; }
}

public class TimerJobMetaData : SPPersistedObject
{

    [Persisted]
    public string SiteUrl;

    public TimerJobMetaData() { }
    public TimerJobMetaData(string name, SPPersistedObject parent, Guid Id)
        : base(name, parent, Id)
    { }
}
}


text:
Q: Make different applications to use different connections
Possible Duplicate:
bind software to different network interfaces

Is it possible to get an application like transmission to use the mobile broadband connection and say chrome to use the wifi connection?
Is there a way to set some rules for this?


text:
Q: Initialize django Point in queryset annotate I have a model with latitude and longitude as DecimalFields. I am trying them to Point instance of postgisand then transform to reqd CRS. I have written the queryset for that but I am getting the following error:
TypeError: Invalid parameters given for Point initialization.

Queryset
list(Geo.objects.filter()
.values("latitude", "longitude")
.annotate(
    float_long=ExpressionWrapper(F('longitude'), output_field=FloatField()),
    float_lat=ExpressionWrapper(F('latitude'), output_field=FloatField())
)
.annotate(
    wgs_84=Transform(
        Point(
            F('float_long'), F('float_lat'), srid=srid
        ),
        4236
    )
))

Here I am trying to add a value wgs_84 which will be the transformed value in wgs84 system.
The error I am getting is related to passing F('float_long'), F('float_lat') as params to Point.
How can I rectify this error?
Note: Edited
Below is the sql query that I wrote to solve my issue:
SELECT
    "id", "altitude", "longitude", "latitude", "<other fields>",
    ST_X(ST_Transform(
        ST_SetSrid(
            ST_MakePoint(
                "longitude", "latitude", "altitude"
            ),
            (select srid from spatial_ref_sys where srid={srid})
        ),
        4326
    )) AS wgs_longitude,
    ST_Y(ST_Transform(
        ST_SetSrid(
            ST_MakePoint(
                "longitude", "latitude", "altitude"
            ),
            (select srid from spatial_ref_sys where srid={srid})
        ),
        4326
    )) AS wgs_latitude
FROM "My_Table"
WHERE (<conditions to filter>)

Now even though this works, I am looking for a way to get ST_X, ST_Y values from transformed point to a different CRS.
Also even though I can use values_list to get a list of values and then loop through it and get the transformed point values for each item, it is slow. So I am looking for a way to get it directly through django orm.


text:
Q: What type to be declared So there is a class like this
class Base<T extends BaseClass> extends StatefulWidget

and I want to use that class without directly give an Object that extends BaseClass but instead something pass through the constructor.
class Something extends StatelessWidget {
  final /*what type I am supposed to give here*/ test;

  const Something({Key key, this.test}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Base<test>();
  }
}

The error warning I get is
'dynamic' doesn't extend 'BaseClass'.
Try using a type that is or is a subclass of 'BaseClass'.dart(type_argument_not_matching_bounds)

The name 'test' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'test'.dart(non_type_as_type_argument)

A: You can declared by "Type", but cannot create an instance of a class from a Type object representing the class.
class Something<T extends BaseClass> extends StatelessWidget {
  // final Type test;

  // const Something({Key key, this.test}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Base<T>();
  }
}

Create Something widget:
class NewClass extends BaseClass {}

Widget x = Something<NewClass>();


text:
Q: How to count breakpoint hits using IntelliJ during debugging I need to count the number of times a given line of code is hit during execution. I want to use it via debugging tool on my IDE and not a code or performance tool solution.
I am already using YourKit to profile the project, and do not want number of line calls via this tool.
I also do not want to count hits using code (with System.out.print and a variable) because I will be checking the procedure at different branches.
I already checked IntelliJ IDEA help.
Also checked both this posts:
Debugging and counting breakpoint hits
Counting breakpoint hits
But none of them replies to what I am looking for.
I am currently using IntelliJ's breakpoint options: Log to console .

The way I am using the breakpoint option in IntelliJ I get a log message every time the breakpoint is hit, and then I have to count the number of messages.

I would like to get an actual number of hits so I do not have to count messages.
If anyone knows a simple direct solution to achieving this via IntelliJ I really appreciate. Thanks in advance.

A: The Overhead tab in the Debugger view has a "Hits" column. You don't even have to have Suspend or Log to Console being enabled for the breakpoint to be counted. See the help page Monitor debugger overhead.

A:

Scroll to the end, and watch the line number

A: The approach of DaSqy Stc is good, but it doesn't work when there are other log messages are printed or if you want to track multiple breakpoints individually.
Solution is to keep the option "log to console" on and click inside the console, press [Ctrl]+[F] and search after "Breakpoint reached at RemoveFromList.remove(RemoveFromList.java:38)" and it says 1/6. The right number is the one you want.


text:
Q: How to sort GKTurnBasedMatch by most recently active? I am creating a simple word game with a menu screen in which I am displaying all of the user's active matches.  I would like to sort this array of matches in order from most recently to least recently active, but the only timestamp property associated with players taking turns is a property of GKTurnBasedParticipant...GKTurnBasedMatch has no useful sorting property.
GKTurnBasedMatch has an array of GKTurnBasedParticipant objects as a property, so I would certainly be able to come up with some sort of solution, but I can't think of anything that wouldn't be really messy and inefficient.  Is there any way something simple like NSPredicate could be used in a case like this to drill down into each array of participants, look at the latest timestamp and sort all the matches in one go?

A: I don't have an NSPredicate-based solution, or probably anything as elegant as you had hoped, but I ran into the same issue and wrote my own solution and it wasn't actually that bad.
My solution is for a game that can only have two participants, so modify accordingly, but here is the code I ended up using:
[myGamesArray sortUsingComparator:^NSComparisonResult(CHGame *game1,
                                                      CHGame *game2) {

    if (YES == [game1 localPlayersTurn] && NO == [game2 localPlayersTurn]) {
        return NSOrderedAscending;
    } else if (NO == [game1 localPlayersTurn] && YES == [game2 localPlayersTurn]) {
        return NSOrderedDescending;
    }

    NSDate *lm1 = [game1.match lastMove];
    NSDate *lm2 = [game2.match lastMove];
    if (lm1 != nil && lm2 != nil) {
        return [lm1 compare:lm2];
    }

    return NSOrderedSame;

}];

where CHGame is a custom class I built for my games (which have a GKTurnBasedMatch match property), and the instance method localPlayersTurn returns a BOOL indicating whether or not it is the local participant's turn or not.
And then I wrote a lastMove method in a category on GKTurnBasedMatch:
- (NSDate *)lastMove {
    GKTurnBasedParticipant *localParticipant, *otherParticipant;
    NSDate *lastMove;

    for (GKTurnBasedParticipant *participant in self.participants) {
        if (YES == [participant.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID]) {
            localParticipant = participant;
        } else {
            otherParticipant = participant;
        }
    }

    if (localParticipant == self.currentParticipant) {
        lastMove = otherParticipant.lastTurnDate;
    } else {
        lastMove = localParticipant.lastTurnDate;
    }

    return lastMove;
}

Again, this only works for two total participants, but would be easy to modify for any number of them.
Hope this helps even though it's not exactly what you asked for.

A: Sort turn-based matches by last turn of current participant
[GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error)
 {
     NSString *descriptorKey = @"currentParticipant.lastTurnDate";

     NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:descriptorKey
                                                                      ascending:NO];

     NSArray *sortedMatches = [matches sortedArrayUsingDescriptors:@[sortDescriptor]];
 }];

Sort turn-based matches by date created
[GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error)
 {
     NSString *descriptorKey = @"creationDate";

     NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:descriptorKey
                                                                      ascending:NO];

     NSArray *sortedMatches = [matches sortedArrayUsingDescriptors:@[sortDescriptor]];
 }];


text:
Q: python: merge two csv files I have a problem while I'm doing my assignment with python.
I'm new to python so I am a complete beginner.
Question: How can I merge two files below?
s555555,7
s333333,10
s666666,9
s111111,10
s999999,9

and
s111111,,,,,
s222222,,,,,
s333333,,,,,
s444444,,,,,
s555555,,,,,
s666666,,,,,
s777777,,,,,

After merging, it should look something like:
s111111,10,,,,
s222222,,,,,
s333333,10,,,,
s444444,,,,,
s555555,7,,,,
s666666,9,,,,
s777777,,,,,
s999999,9,,,,

Thanks for reading and any helps would be appreciated!!!

A: Here are the steps you can follow for one approach to the problem. In this I'll be using FileA, FileB and Result as the various filenames.
One way to approach the problem is to give each position in the file (each ,) a number to reference it by, then you read the lines from FileA, then you know that after the first , you need to put the first line from FileB to build your result that you will write out to Result.

*

*Open FileA. Ideally you should use the with statement because it will automatically close the file when its done. Or you can use the normal open() call, but make sure you close the file after you are done.

*Loop through each line of FileA and add it to a list. (Hint: you should use split()). Why a list? It makes it easier to refer to items by index as that's our plan.

*Repeat steps 1 and 2 for FileB, but store it in a different list variable.
Now the next part is to loop through the list of lines from FileA, match them with the list from FileB, to create a new line that you will write to the Result file. You can do this many ways, but a simple way is:

*

*First create an empty list that will store your results (final_lines = [])

*Loop through the list that has the lines for FileA in a for loop.

You should also keep in mind that not every line from FileA will have a corresponding line in FileB. For every first "bit" in FileA's list, find the corresponding line in FileB's list, and then get the next item by using the index().  If you are keen you would have realized that the first item is always 0 and the next one is always 1, so why not simply hard code the values? If you look at the assignment; there are multiple ,s so it could be that at some point you have a fourth or fifth "column" that needs to be added. Teachers love to check for this stuff.

*

*Use append() to add the items in the right order to final_lines.

Now that you have the list of lines ready, the last part is simple:

*

*Open a new file (use with or open)

*Loop through final_lines

*Write each line out to the file (make sure you don't forget the end of line character).

*Close the file.

If you have any specific questions - please ask.

A: Not relating to python, but on linux:
sort -k1 c1.csv > sorted1
sort -k1 c2.csv > sorted2
join -t , -11 -21 -a 1 -a 2 sorted1 sorted2

Result:
s111111,10,,,,,
s222222,,,,,
s333333,10,,,,,
s444444,,,,,
s555555,7,,,,,
s666666,9,,,,,
s777777,,,,,
s999999,9

A: Make a dict using the first element as a primary key, and then merge the rows?
Something like this:
f1 = csv.reader(open('file1.csv', 'rb'))
f2 = csv.reader(open('file2.csv', 'rb'))

mydict = {}
for row in f1:
    mydict[row[0]] = row[1:]

for row in f2:
    mydict[row[0]] = mydict[row[0]].extend(row[1:])

fout = csv.write(open('out.txt','w'))
for k,v in mydict:
    fout.write([k]+v)


text:
Q: How export CSV with SQLCMD in UTF-16? I am trying to export the data from different queries by SQLCMD, my files must be exported in UTF-16, currently they do it in UTF8 BOM and I have been able to even in UTF8, but I cannot get it to export in UTF16.
Reviewing the Encoding of the file in Notepad++ this is the format in which it should be exported (UTF16 LE BOM), in the list selection it appears with the name UCS-2 Little Endian
Encoding to export
Encoding in options
SET @cmd= 'sqlcmd -s"-" -f i:1252 -Q "SELECT * FROM Machines" -f o:65001 -o "C:\CSV\report_machines.csv"'

EXEC master..xp_cmdshell @cmd

Check the page (https://www.example-code.com/sql/load_text_file_using_code_page.asp) and tried code 1200, however SQL Server returns the following message:
Sqlcmd: The code page <1200> specified in option -f is invalid or not installed on this system.
I want to avoid using another program, if anyone knows how to solve this problem I would greatly appreciate it.


text:
Q: Tableau .. can you retain hyperlinks upon exporting to PDF? Potentially dumb question, but I have a series of web links that I include as part of my enterprise wide PDF distribution, and I was wondering if there was a way to make these links retain the fact that they are clickable upon export of the PDF.
Has anyone figured out a workaround or method to make this reality?
The links work when publishing dashboards in tableau server, but again, this is PDF-specific.


text:
Q: How to check if libfftw3_threads.so.3.2.4 shared library was compiled for pthreads or for OpenMP? There is FFTW library installed by an administrator system-wide, in /usr/lib64, and it includes /usr/lib64/libfftw3_threads.so.3.2.4.
When I compiled this library myself, before it was installed by sysadmin, I have noticed that you have to choose between OpenMP and pthreads version:

*

*--enable-openmp: Like --enable-threads, but using OpenMP compiler directives in order to induce parallelism rather than spawning its own threads directly. Useful especially for programs already employing such directives, in order to minimize conflicts between different parallelization mechanisms. Use either --enable-openmp or --enable-threads, not both; in either case the multi-threaded FFTW interface/library (see Multi-threaded FFTW) is compiled (with different back ends).

The distribution is Gentoo, so theoretically either is possible.
How to check if said library was compiled with OpenMP support (which would be best), or with pthreads?

A: You can call ldd on it to see if -fopenmp was used:
$ cat x.c
int foo()
{ return 0 ; }

$ gcc -shared -fopenmp x.c -o x.so
$  ldd x.so
    linux-vdso.so.1 =>  (0x00007fff293d6000)
    libgomp.so.1 => /usr/lib/libgomp.so.1 (0x00007fa942998000)
    libpthread.so.0 => /lib/libpthread.so.0 (0x00007fa94277b000)
    libc.so.6 => /lib/libc.so.6 (0x00007fa9423f7000)
    librt.so.1 => /lib/librt.so.1 (0x00007fa9421ef000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fa942dc7000)

Meaning it is both linked against libpthread and libgomp.
$ gcc -shared x.c -o x.so
$ ldd x.so
    linux-vdso.so.1 =>  (0x00007fff5fbff000)
    libc.so.6 => /lib/libc.so.6 (0x00007f5340a9b000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f534103f000)

Meaning it does not include openmp support.
In general it is not that easy to see what compiler flags were used since they are not recorded in the binary by default.
Perhaps you can look into some Gentoo log file that was created during package install (I mean package compile time).
Of course with binary package based distribution (like e.g. Debian) you don't have that problem - you can look up to what package the .so file belongs to, and look into the package description and/or the source package, where the  compiler switches are specified.

A: You can check whether the library is linked against pthread at least by using ldd. On Debian squeeze, my version is linked against pthread.
$ ii  libfftw3-3      3.2.2-1      library for computing Fast Fourier Transforms

$ ldd /usr/lib/libfftw3_threads.so.3.2.4
linux-gate.so.1 =>  (0xb77be000)
libm.so.6 => /lib/i686/cmov/libm.so.6 (0xb776c000)
libpthread.so.0 => /lib/i686/cmov/libpthread.so.0 (0xb7753000)   <---
libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb760c000)
/lib/ld-linux.so.2 (0xb77bf000)

Based on a quick net search, it looks like the program would have to link against the GCC OpenMP support library (GOMP) for OpenMP support, so you could use ldd to check for something with "libgomp" in it as well.


text:
Q: Creating an XML with multiple root elements I'm trying to create an XML with multiple root elements. I can't change that because that is the way I'm supposed to send the XML to the server. This is the error I get when I try to run the code:

System.InvalidOperationException: This operation would create an incorrectly structured document.

Is there a way to overwrite this error and have it so that it ignores this?
Alright so let me explain this better:
Here is what I have
XmlDocument doc = new XmlDocument();
doc.LoadXml(_application_data);

Now that creates the XML document and I can add a fake root element to it so that it works. However, I need to get rid of that and convert it into a DocumentElement object.
How would I go about doing that?

A: Specify Fragment when creating XmlWriter as shown here
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.CloseOutput = false;

// Create the XmlWriter object and write some content.
MemoryStream strm = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(strm, settings))
{
    writer.WriteElementString("orderID", "1-456-ab");
    writer.WriteElementString("orderID", "2-36-00a");
    writer.Flush();
}

A: If it has multiple root elements, it's not XML. If it resembles XML in other ways, you could place everything under a root element, then when you send the string to the server, you just combine the serialized child elements of this root element, or as @Austin points out, use an inner XML method if available.

A: just create an XML with single root then get it's content as XML text.
you are talking about XML fragment anyways, since good xml has only one root.
this is sample to help you started:
var xml = new XmlDocument();
var root = xml.CreateElement("root");
root.AppendChild(xml.CreateElement("a"));
root.AppendChild(xml.CreateElement("b"));
Console.WriteLine(root.InnerXml); // outputs "<a /><b />"


text:
Q: Hovering over keywords causes glowing on certain words in a sentence/paragraph I want to have a sentence/paragraph like "I like to ride my bicycle every day." etc. and above the paragraph there should be categories: "Nouns", "Verbs" etc. When the user hovers over "Nouns", it should cause "bicycle" and "day" to glow and hovering over "Verbs" it should be "like" and "ride". I think maybe this could be done with span tags around the particular words setting the class to either "noun" or "verb" and some kind of CSS and/or JS. Can anyone help?
Just to be clear, this is what I'm talking about.
Nouns - Verbs

I like to ride my bicycle every day.

A: Try the following code. I hope it helps to get the base idea

function selectWords(name) {
    let words = document.getElementById("words").children;
    for (let i = 0; i < words.length; i++) {
        if (words[i].className === name) {
            words[i].classList.add("selected");
        } else {
            words[i].classList.remove("selected");
        }
    }
}

let selects = document.getElementsByClassName("select");

for (let i = 0; i < selects.length; i++) {
    selects[i].addEventListener("mouseenter", function() {
        selectWords(this.dataset.words);
    });
    selects[i].addEventListener("mouseleave", function() {
        selectWords("empty");
    });
}
.selected {text-shadow: 1px 1px 1px red}

I like to ride my bicycle every day

Nouns

Verbs

A: I'm pretty confused why everyone else was making this so hard. It makes me wonder if I've misunderstood you as well, but I'm pretty sure I haven't.
I used mouseenter and mouseleave, with a system of ids and divs to accomplish what you're looking for.
I used jQuery to accomplish this, so make sure you include the jQuery library.

$(document).ready(function(){
/* Beginning of Verbs */
    $("#verb").mouseenter(function(){
        $(".verb").css("text-shadow", "1px 1px 1px blue");
    });
    $("#verb").mouseleave(function(){
        $(".verb").css("text-shadow", "");
    });
  /* Ending of Verbs */

  /* Beginning of Nouns */
    $("#noun").mouseenter(function(){
        $(".noun").css("text-shadow", "1px 1px 1px red");
    });
    $("#noun").mouseleave(function(){
        $(".noun").css("text-shadow", "");
    });
    /* Ending of Nouns */
});
#verb {

}

.verb {
text-shadow: none;
display: inline;
}
#noun {

}

.noun {
text-shadow: none;
display: inline;
}

Nouns - Verbs

I
 like to
ride

my
 bicycle every day.

A: You can wrap each word in a tag, for example,  and use CSS :before or :after pseudo element to render the generated content.

onload = function () {

  var confirmation = document.querySelector(".confirm_selection");

  var grammar = {
    "I": "noun",
    "like": "adverb",
    "to": "preposition",
    "ride": "verb",
    "my": "noun",
    "bicycle": "noun",
    "every": "adjective",
    "day": "noun"
  };

  Object.entries(grammar).forEach(function([word, key]) {
    var span = document.createElement("span");
    span.textContent = word;
    span.className = key;
    confirmation.appendChild(span);
  })

}
.confirm_selection {
  -webkit-transition: text-shadow 0.2s linear;
  -moz-transition: text-shadow 0.2s linear;
  -ms-transition: text-shadow 0.2s linear;
  -o-transition: text-shadow 0.2s linear;
  transition: text-shadow 0.2s linear;
  top: 50px;
  display: block;
  height: 100px;
  position: relative;
}

.confirm_selection:hover {
  text-shadow: 0 0 10px red;
}

.confirm_selection [class]:hover:before {
  content: attr(class);
  position: absolute;
  display: inline-block;
  top: -24px;
  background: #000;
  color: gold;
  z-Index: 2;
  max-width: 78px;
  overflow: hidden;
  margin-bottom: 12px;
}

.confirm_selection span {
  display:inline-block;
  position: relative;
  margin: 2px;
}

[ Confirm Selection ]

A: <div class="context"
  verb not a verb
  another verb

var verbs = document.querySelectorAll('.verb');
var bindEvent = function (el) {
  el.addEventListener('mouseenter', function () {
    for (var i = 0; i < verbs.length; i++) {
      verbs[i].style.backgroundColor = 'red';
    }
  })
  el.addEventListener('mouseleave', function () {
    for (var i = 0; i < verbs.length; i++) {
      verbs[i].style.backgroundColor = '';
    }
  })
}
for (var i = 0; i < verbs.length; i++) {
  bindEvent(verbs[i]);
}

i think this codes may help you?


text:
Q: How to declare symbols (such as @) in strings in arff file? I have a question that I am really confused about and I am sorry if that is so stupid.
I have been using so far only numeric data to achieve sentiment analysis in Java that I obtain by using only Python libraries but now I realize that I am forced to use Java to preprocess my data as a text from the beginning.
I want to use the StringToWord of Weka to tokenize my data and then apply pre-processings plus tfidf.
My question is, how do I need to handle with symbols in string in an arff file ? Because when I just define the attributes as below I get the "nominal value not declared in header, read Token[@Microsoft].." for the first line in my data.
@relation corpus
@attribute id numeric
@attribute text string
@attribute label {positive,neutral,negative}
@attribute label2 {neutral,non-neutral}
@data
628949369883000000  dear @Microsoft the...  negative    non-neutral

I also tried representing my data as follow with commas. I get the same error.
628949369883000000,dear @Microsoft the...,negative,non-neutral

So how should I declare then this string which includes symbols ?
Thanks a lot.

A: Okay so I just had to give my string in quotes.
@relation file
@attribute id numeric
@attribute tweet string
@attribute label {positive,neutral,negative}
@attribute label2 {neutral,non-neutral}

@data
628949369883000000,"dear@ Microsoft .... C'mon.",negative,non-neutral


text:
Q: CPU cycles in cloud I am basic learner of cloud computing. How the CPU cycles are allocated in cloud computing load balancing technique.how load balancing is done in cloud computing

A: Not very much sure but basically load balancing works on the basis of roundrobin technique so the distribution should be almost equal .
Main reasons load balancing-

*

*Web server is not able to handle the traffic

*intolerance to an outage if one web server fails

Jelastic helped me for load balancing .
please follow the following links , this might help you to understand-

http://jelastic.com/docs/http-load-balancing
http://jelastic.com/docs/tcp-load-balancing


text:
Q: Android не могу получить id новой заметки пытаюсь учиться программированию, нигде не могу найти ответа на вопрос.
Пишу приложение заметки. Базу данных использую Room. Когда создаю новую заметку и нажимаю сохранить, она сохраняется, но присвоенный ей id недоступен. Если выйти из заметки и открыть ее из списка сохраненных, то все в порядке. Возможно ли как-то получить id последней созданной заметки, не выходя из нее? Ну или на программном уровне выполнить выход и открытие созданной заметки?
Возможно необходимо прикрепить какой-то код? Весь код думаю загадит вопрос.

A: Метод, помеченный как @Insert в DAO, может возвращать id вставленной записи - добавьте long как возвращаемый тип. Или массив/коллекцию long, если вставляется сразу несколько записей.
https://developer.android.com/training/data-storage/room/accessing-data#convenience-insert


text:
Q: Proving center of group is the identity subgroup
Prove that the center of $S_n$ is the identity subgroup for $n>2$.

Would I have to use the definition of center of a group first or do I have to make sure it satisfies the axioms to be a subgroup? I am not too sure what the proof wants me to show. I am not sure how to go about solving it.

A: We need to show that the center of a group, $$\operatorname{C}(G) = \left\{x \in G \mid axa^{-1} = x\;\;\forall a \in G\right\}\,,$$ contain the identity element, and only the identity element. It's easy to show that the identity element is in ${\operatorname{C}(G).}$
Now suppose (for the sake of contradiction) that we have a non-identity element $\sigma {\in \operatorname{C}(G).}$ To keep things simple for now,  suppose $\sigma$ is a cycle $(x_1\;\dotsb\;x_m)$. Recall that (or you should prove that) $$\pi(x_1\;\dotsb\;x_m)\pi^{-1} = (\pi(x_1)\;\dotsb\;\pi(x_m))\,.$$
Knowing this, for any given $\sigma$ do you think you can find a $\pi$ that won't fix $\sigma$ under conjugation? Then can you see how this argument extends to elements of $S_n$ that are not cycles?

 If there is a element $i \in \{1,\dotsc,n\}$ such that $x_i$ is not moved by the permutation $\sigma$, then let $\pi = (x_i,x_1)$. Otherwise $(x_1\;\dotsb\;x_m)$ permutes at least three elements, and you may let $\pi = (x_1,x_m)$. Since every permutation of $S_n$ can be written as a product of disjoint cycles, this argument on a single cycle $\sigma$ extends to any permutation in $S_n$.


text:
Q: Width and height different in CSS and HTML Say I have a div. If I give it a height and width of 500*500px in HTML code, like this:
test
 it will not have dimensions of 500*500px unless it's filled with enough code/text to push it to those dimensions. However, if I set the exact same width and height with CSS (either inline CSS or external document) like this:
test
 the dimensions are always what I set.
Why is there a difference?

A: A div tag does not have the attributes width and height.

A: Doing this isn't valid syntax. You cant add width & height attributes to a DIV the same as you can to a table or an image tag.

test

This is valid syntax:

test


text:
Q: What is the limit of this specific series? Anyone can give me the path for this, could not figure out which theory/method to use for this...
$$\lim_{n\to\infty}\left(\frac{1}{1\cdot4}+\frac{1}{4\cdot7} + \frac{1}{7\cdot10}+.....+ \frac {1}{(3n-2)\cdot(3n+1)}\right)=?$$

A: If you break the terms in this way $$\frac{1}{(3n-2)(3n+1)}=\frac{1/3}{3n-2}-\frac{1/3}{3n+1}$$
many will cancel.

A: Hint: $\displaystyle\frac1{1\times4}=\frac13\left(1-\frac14\right)$, $\displaystyle\frac1{4\times7}=\frac13\left(\frac14-\frac17\right)$, $\displaystyle\frac1{7\times10}=\frac13\left(\frac17-\frac1{10}\right)$, …

A: HINT: It is
$$
\lim_{n\to\infty}\frac13\left(
\frac11-\frac14+\frac14-\frac17+\frac17-\frac1{10}\ldots+\frac1{3n-2}-\frac1{3n+1}
\right)
$$


text:
Q: How does a user submit an article on a website? I am working on this travel blog Trippindian.com . I want to build a page where a user can login via facebook and then write an article and submit it to us. Its just like I am posting a question on stackoverflow.
just FYI I am a noobie coder.
I want to understand the logic and functionality behind this.
Thanks

A: First, you need a database where you can store all these posts.
And then, you would need to create a page with a form element (HTML).
You would also need a php code that connects to the database and adds the value or values contained in the form.
That's pretty much what you need.
You could find other solutions, but I think it's the simplest one.


text:
Q: Google Drive API - Find out uploader's IP address I am writing a C# program for my son's class (that will be used by several students from different computers and external IPs). The app basically uploads an assignment the students wrote to their own personal Google Drive account.
I am trying to get the external IP of their PC, without using any 3rd party services such as whatismyip.com etc.
I have done research about this for a few hours, and I know that 'Google Apps Unlimited' basically allows paying customers (aka not me) and organizations to pay 10$/month and find out who uploaded each file to the google drive account.
My question is how, using the API, I can view the IP address of the PC that uploaded the file?
Thanks.

A: Since uploading files still uses either the create API or update API (which both returns a File resource), it doesn't indicate that there's a way to know the IP address using the API.
You may have to check it using a 3rd party library (I believe whatsmyip has a C# library as indicated in this question; which you might have been referring to from the start).


text:
Q: A PHP Error was encountered Severity: Notice Message: Undefined property: stdClass::$comment_count Filename: blog/index.php Line Number: 35 My line number 35 of view/blog/index.php is as:
<a href="<?php echo base_url().'post/'.$post->entry_id.'#comments';?>" class="comments">Comments (<?php echo $post->comment_count;?>)

I have made a column in table comment as comment_id still its not working
and in my model/blog_model.php it is a function as:
$count = array(
        'comment_count' => $total_count,
    );

Thanks in advance

A: You are mixing up your notations. Question isnt very clear but if you have set an array index like...
$count = array(
    'comment_count' => $total_count,
);

And I assume passing $count as $post into your view and trying to access like this...
$post->comment_count

It wont work as this is not array notation. Correct would be..
$post['comment_count']

If $post and $count are different objects then you need to do..
$count['comment_count']


text:
Q: What's wrong in this simple android Program, I get 'Force Close' What is wrong in this program, My eclipse IDE doesn't show any errors....when I execute this simple program the emulator shows force close....Anybody please clarify
import android.app.Activity;
import android.view.View.OnClickListener;
import android.view.View;
import android.os.Bundle;
import android.widget.*;

public class HelloWorld extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    View Et1,Bt1,TxtDisp;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.name_getter);
        Bt1=(Button)findViewById(R.id.Btn1);
        Et1=(EditText)findViewById(R.id.UserInput);
        TxtDisp=(TextView)findViewById(R.id.TextDisp);
        Bt1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String userInput=((EditText) Et1).getText().toString();
        ((TextView)TxtDisp).setText(userInput);
    }
}

A: Do you know how to enable logcat?
please enable logcat and show us the exact exception it is throwing.
in eclipse, it is: Window>Show View>Other>Android>Logcat

A: Without an error this is really hard,

*

*Have you declared your activity in the manifest?

*Does that contentview "name_getter" contain the ids Btn1, UserInput and TextDisp?

*Are those id's indeed respectively a Button, an EditText and a Textview?

Does the error start after clicking the button? Could it be that your getText returns null?
If you really can't get the logcat to work, at least add a bunch of try-catches to your code. If it executes you're getting an error in this file, and not somewhere else. You coudl also try to debug with debugmessages using a Toast.
(something like this, just guessing, you should look it up)
Toast t = Toast.maketext(this, "your error", Toast.LOOKTHISUP);
t.show();

A: Something similar happened to me once.
Are you sure that
R.id.Btn1 is Button
R.id.UserInput is EditText
R.id.TextDisp is TextView

A: Can you post your main.xml here. Something must have gone wrong there. Check whether you have assigned correct names for each view under android:id in  your layout
My guess is there should be a null pointer thrown at this line
Bt1.setOnClickListener(this);

Can you check whether Bt1 is null? if yes your object has not been initialized properly.

A: try to do this:
public void onClick(View V)
{
switch(v.getId(){
case R.id.Bt1:
// do here what you want to do
break;
}
}


text:
Q: Error accessing jLabel I´m coding a simple program in Eclipse using WindowBuilder.
I´ve coded 2 windows, a JFrame and a JDialog. The Jdialog contains a some Jlabels, and I want to show an image in one of them. I´ve read It can be done creating an ImageIcon and setting it to a label using setIcon(). The problem is that I can´t access the label from anywhere.
It is in the last line of the method cargarImagen()
Here is the code:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.pcastelbon.dao.ContactoJDBCImpl;
import com.pcastelbon.entity.Contacto;
import com.jgoodies.forms.layout.FormSpecs;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;

public class ContactoMantenimiento extends JDialog {

/**
 *
 */
private static final long serialVersionUID = 6291928431785031824L;
ContactoJDBCImpl cc= new ContactoJDBCImpl();
private Contacto c;
private final JPanel contentPanel = new JPanel();
private JTextField txId;
private JTextField txNombre;
private JTextField txApellido1;
private JTextField txApellido2;
private JTextField txTelefono;
private JTextField txDireccion;
private JTextField txCp;
private JTextField txCiudad;
private JTextField txEmail;
private JTextField txFoto;
private JTextField txFecha;

/**
 * Launch the application.
 */
/**public static void main(String[] args) {
    try {
        ContactoMantenimiento dialog = new ContactoMantenimiento();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}**/

/**
 * Create the dialog.
 */
public ContactoMantenimiento() {
    setModal(true);

    setBounds(100, 100, 588, 300);
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    contentPanel.setLayout(new BorderLayout(0, 0));
    {
        JPanel panel = new JPanel();
        contentPanel.add(panel, BorderLayout.CENTER);
        panel.setLayout(new FormLayout(new ColumnSpec[] {
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                ColumnSpec.decode("default:grow"),
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                ColumnSpec.decode("default:grow"),
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.BUTTON_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,},
            new RowSpec[] {
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                FormSpecs.RELATED_GAP_ROWSPEC,
                FormSpecs.DEFAULT_ROWSPEC,}));
        {
            JLabel lblId = new JLabel("Id");
            panel.add(lblId, "4, 4, right, default");
        }
        {
            txId = new JTextField();
            txId.setEditable(false);
            panel.add(txId, "6, 4, fill, default");
            txId.setColumns(10);
        }
        {
            JLabel lblDireccin = new JLabel("Dirección");
            panel.add(lblDireccin, "8, 4, right, default");
        }
        {
            txDireccion = new JTextField();
            panel.add(txDireccion, "10, 4, fill, default");
            txDireccion.setColumns(10);
        }
        {
            JLabel lblImagen = new JLabel("New label");
            panel.add(lblImagen, "14, 4, 1, 7");
        }
        {
            JLabel lblNombre = new JLabel("Nombre");
            panel.add(lblNombre, "4, 6, right, default");
        }
        {
            txNombre = new JTextField();
            panel.add(txNombre, "6, 6, fill, default");
            txNombre.setColumns(10);
        }
        {
            JLabel lblCdigoPostal = new JLabel("Código postal");
            panel.add(lblCdigoPostal, "8, 6, right, default");
        }
        {
            txCp = new JTextField();
            panel.add(txCp, "10, 6, fill, default");
            txCp.setColumns(10);
        }
        {
            JLabel lblPrimerApellido = new JLabel("Primer apellido");
            panel.add(lblPrimerApellido, "4, 8, right, default");
        }
        {
            txApellido1 = new JTextField();
            panel.add(txApellido1, "6, 8, fill, default");
            txApellido1.setColumns(10);
        }
        {
            JLabel lblCiudad = new JLabel("Ciudad");
            panel.add(lblCiudad, "8, 8, right, default");
        }
        {
            txCiudad = new JTextField();
            panel.add(txCiudad, "10, 8, fill, default");
            txCiudad.setColumns(10);
        }
        {
            JLabel lblSegundoApellido = new JLabel("Segundo apellido");
            panel.add(lblSegundoApellido, "4, 10, right, default");
        }
        {
            txApellido2 = new JTextField();
            panel.add(txApellido2, "6, 10, fill, default");
            txApellido2.setColumns(10);
        }
        {
            JLabel lblTelfono = new JLabel("Teléfono");
            panel.add(lblTelfono, "8, 10, right, default");
        }
        {
            txTelefono = new JTextField();
            panel.add(txTelefono, "10, 10, fill, default");
            txTelefono.setColumns(10);
        }
        {
            JLabel lblFechaNacimiento = new JLabel("Fecha nacimiento");
            panel.add(lblFechaNacimiento, "4, 12, right, default");
        }
        {
            txFecha = new JTextField();
            panel.add(txFecha, "6, 12, fill, top");
            txFecha.setColumns(10);
        }
        {
            JLabel lblEmail = new JLabel("Email");
            panel.add(lblEmail, "8, 12, right, default");

        }
        {
            txEmail = new JTextField();
            panel.add(txEmail, "10, 12, fill, default");
            txEmail.setColumns(10);
        }
        {
            JButton btnCambiar = new JButton("Cambiar imagen");
            btnCambiar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    cargarImagen();

                }
            });
            panel.add(btnCambiar, "14, 12");
        }
        {
            txFoto = new JTextField();
            panel.add(txFoto, "14, 14, fill, default");
            txFoto.setColumns(10);
        }
    }
    {
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            JButton btAceptar = new JButton("Aceptar");
            btAceptar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {

                    Boolean correcto = false;
                    String id= txId.getText();
                    Contacto c = new Contacto();
                    Date fecha=null;
                    fecha = parseFecha (txFecha.getText());

                    if (txId.getText().length()>0){
                        c.setIdContacto(Integer.parseInt(txId.getText()));
                    }
                    c.setNombre(txNombre.getText());
                    c.setApellido1(txApellido1.getText());
                    c.setApellido2(txApellido2.getText());
                    c.setDireccion(txDireccion.getText());
                    c.setCp(txCp.getText());
                    c.setCiudad(txCiudad.getText());
                    c.setEmail(txEmail.getText());
                    c.setFechaNacimiento(fecha);
                    c.setTelefono(txTelefono.getText());
                    c.setFoto(txFoto.getText());

                    if(id.equalsIgnoreCase("")){

                        correcto = cc.insertarContacto(c);

                    }else{

                        correcto = cc.actualizarContacto(c);

                    }
                    if (!correcto){

                        JOptionPane.showMessageDialog(getParent(), "Error al actualizar la base de datos" );

                    }else{

                        JOptionPane.showMessageDialog(getParent(), "Base de datos actualizada" );
                    }
                    dispose();

                }
            });
            btAceptar.setActionCommand("OK");
            buttonPane.add(btAceptar);
            getRootPane().setDefaultButton(btAceptar);
        }
        {
            JButton btCancelar = new JButton("Cancelar");
            btCancelar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                }
            });
            btCancelar.setActionCommand("Cancel");
            buttonPane.add(btCancelar);
        }
    }

}

public Contacto getContacto(){

    return this.c;

}

public void setContacto (Contacto c){

    this.c= c;

}
/*
 *
 * Método que convierte un string en una fecha con el formato requerido
 */
public Date parseFecha(String fecha){

    Date fechaDate = null;
    SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");

    try {
        fechaDate = formato.parse(fecha);

    }
    catch (ParseException ex)
    {
        System.out.println(ex);
    }
    return fechaDate;
}
/**
 * Método que carga los datos al inicio
 */
public  void cargarDatos(Contacto cs){

    //Rellenamos los datos del formulario

    txId.setText(Integer.toString(cs.getIdContacto()));
    txNombre.setText(cs.getNombre());
    txApellido1.setText(cs.getApellido1());
    txApellido2.setText(cs.getApellido2());
    txTelefono.setText(cs.getTelefono());
    txDireccion.setText(cs.getDireccion());
    txCp.setText(cs.getCp());
    txCiudad.setText(cs.getCiudad());
    txEmail.setText(cs.getEmail());
    txFecha.setText(formatearFecha(cs.getFechaNacimiento()));

}

String formatearFecha (Date fecha){
    String ff;
    SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
    ff=sdf.format(fecha);

    return ff;
}

public void cargarImagen(){

    JFileChooser jfc = new JFileChooser();
    FileNameExtensionFilter filtroImagen=new FileNameExtensionFilter("JPG, PNG & GIF","jpg","png","gif");
    jfc.setFileFilter(filtroImagen);
    int opcion = jfc.showOpenDialog(getParent());

    //Si pulsamos en aceptar
    if (opcion==jfc.APPROVE_OPTION){

        File imagen = jfc.getSelectedFile();
        String path = imagen.getAbsolutePath();
        txFoto.setText(path);
        ImageIcon ii = new ImageIcon(path);

        lblImagen.setIcon(ii);

    }
}

I can access any JTextField but no Jlabels. On the other Jframe I can access JLabels without problem.

A: You should make the label 'lblImagen' a field of your class (like the various text fields).
Currently it is only locally available where you create it.


text:
Q: Making text messages accessible to screen reader I am building a chat bot and currently working on some accessibility features. I am wondering what is the best way to allow users to read through old messages. In an earlier build I solved this by making the message logs tab-able, but I don't think this is an appropriate solution (as far as I know only buttons/links should be tab-able). Is there a preferred way of doing this, perhaps with hot keys? For reference I am using Voice Over to test accessibility.

A: Generally screenreader users rely on the arrow keys (or swiping, on a touch device) to reach text content which isn't interactive. You're correct that only links and form elements should be tabbable. In this case, assuming your old messages appear as text, I don't think you will need to take any specific action to make them accessible. Test it without any additional markup to confirm this.


text:
Q: Powershell shell to other application with parameters I'm struggling with powershell trying to get an external command to run
$im_convert_exe = "convert.exe"
$srcname = "C:\Scan\input\Test_*.tiff"
$destname = "C:\Scan\merged\ScansMerge.tiff"

$cmdline =  $im_convert_exe + " `"" + $srcname + "`"" + " `"" + $destname + "`""
echo $cmdline
invoke-expression -command $cmdline

I'm trying to use imagemagiks's convert tool to convert a folder of tiff files into one multipage tiff, but i keep getting an invalid parameter error. I cant see what i'm doing wrong, but i'm sure its to do with quotes or something being in the wrong place

A: You may just use ordinar invoke operator:
& $im_convert_exe $srcname $destname

PowerShell will even add double quotes itself when calling the program.
NOTE: By the way, your error may be connected with your use of the asterisk character *. I think Imagemagick expect your shell to expand asterisk and will not expand it on it's own. So you maybe really want to do this:
$im_convert_exe = "convert.exe"
$srcnames = ls "C:\Scan\input\Test_*.tiff"
$destname = "C:\Scan\merged\ScansMerge.tiff"

& $im_convert_exe $srcnames $destname

A: Try this:
$im_convert_exe = "convert.exe"
$srcname = "C:\Scan\input\Test_*.tiff"
$destname = "C:\Scan\merged\ScansMerge.tiff"

$cmdline = [scriptblock]::Create($im_convert_exe + " `"" + $srcname + "`"" + " `"" + $destname + "`"")
Invoke-Command -ScriptBlock $cmdline

It is also a good idea to specify a full path to the executable.


text:
Q: I can feel the electricity on my pc case I have a pc that is connected to a UPS and connected to the outlet. When I turn on the UPS while holding the pc case I can feel a small electric shock, also when the UPS is on charging mode I can feel the electricity all over the case. I know it's not normal to feel the electricity on the case, do I have a faulty PSU, a faulty UPS or its normal?

A: If your computer is not connected to a grounded walloutlet, it is very normal to feel the electricity, given that ground cannot be leaked into ground.
In many houses, the computer is not put into a grounded wall-outlet. It will not kill your pc, but if you put it in a grounded wall-outlet, a pc will usually run slightly more stable. It is recommended, but not a requirement.
If your UPS is connected to a grounded wall-outlet, and that outlet is also working properly (the ground pin is connected to the ground powerline that runs in the house), then the UPS or one of its cables is likely faulty, as that shouldn't happen.


text:
Q: Is there a maximum of emails that can be received for Gmail account? And what is it? Is there a maximum of emails that can be received per day for a Gmail account? And if there is - what is it? Is something like 500 000 or more incoming emails possible?

A: 86,400 max limit
Here are best practices to avoid reaching the storage limit:
Send message logs and automated emails to Google Groups. Using Groups, you can use a web interface to read very large or frequently mailed announcements that quickly hit the receiving limits of your email account.
Avoid using a single account for multiple users, and use Google Groups for sharing mail. Map 10 or fewer email aliases per account. Use groups to create shared mailboxes or to allow many people to send and receive mail with a single address.
Subscribe to the daily digest forms of heavily trafficked email lists.
Avoid using catch-all accounts. Spammers often try to guess email addresses in your domain. When they guess incorrectly, the spam is delivered to the catch-all address. The high mail volume can quickly exceed the Gmail receiving limits.


text:
Q: Do you need Excel for the Xceed DataGrid ExcelExporter? In using the ExcelExporter in Xceed DataGrid, do we need to have a MS Office Excel installed in order for it to work? I am still planning on creating an application but the target PC does not have MS Office installed. But I would like to create a file that can be openned by MS Excel.
Cheers,

A: No, you do not need Excel (or anything else) installed in order to use the ExcelExporter.


text:
Q: java.io.InvalidClassException: org.apache.flink.api.common.operators.ResourceSpec; incompatible types for field cpuCores I am using Beam version 1.24 with Flink Session cluster version 1.11 with beam-runners-flink-1.9. When I run the job with remote FlinkRunner in streaming mode, I get the following error. Any insights will be appreciated. I couldn't put all the stack trace as StackOverflows wouldn't let me post with the entire stack trace.
Thanks,
Rao.
Caused by: java.io.InvalidClassException: org.apache.flink.api.common.operators.ResourceSpec; incompatible types for field cpuCores

A: This was due to Flink and Beam version incompatibility; using the Maven artifact that matched the service version solved the issue. Here is the Maven snippet:
<dependency>
        <groupId>org.apache.beam</groupId>
        <artifactId>beam-runners-flink-1.11</artifactId>
        <version>2.25.0</version>
</dependency>


text:
Q: Find email address that are part of a domain exclusion data extension I'm looking to find all email addresses in our database where the email address domain is included in one of our domain exclusion data extension.
I thought of using something like the below, but it isn't feasible given we have over 3k domains that are part of our domain exclusion data extension.
SELECT * FROM [mytable]
  WHERE Email_Address LIKE 'domain1'
  OR Email_Address LIKE 'domain2'
  OR Email_Address LIKE 'domain3'

Is this even possible in SFMC and if so, what supporting documentation exists?

A: You could accomplish something like this by joining the _subscribers data view with the domain exclusions table on the users email address domain in order to find matches between the two.
To identify a user's domain with SQL, you can use this snippet:
RIGHT(EmailAddress, LEN(EmailAddress) - CHARINDEX('@', EmailAddress))

The rest of the query should be as simple as an inner join.


text:
Q: an odd sentence structure from the NYT
Most important, it turns us against the very entity that holds the capacity to address society's most pressing problems and on which democracy and freedom depend, our own government.

I need a help. Is there someone who could analyse the sentence grammatically?

A: Just take the [rather overblown] comparison out of the middle to make it easier...

Most important, it turns us against the very entity that holds the capacity to address society's most pressing problems and on which democracy and freedom depend, our own government.

Breaks into...
a statement

Most important, it turns us against our own government.

& a descriptor

[our own government is] the very entity that holds the capacity to address society's most pressing problems and on which democracy and freedom depend,

A: First read this this answer for the grammatical reference:  Why is the subject placed in the end of this sentence?

Then try to follow along with your own sentence: B -> A (reverse)
[conjunction] Most important,
[adjunct B] it turns us against
[subject A] the very entity that holds the capacity to address society's most pressing problems and on which democracy and freedom depend, our own government.

Compare with this simple sentence:
A --> B (ordinary)
His bad manners threw [subject A]
me off immediately. [adjunct B]
B --> A (reverse)
There was something in his behaviour that threw me off immediately, [ adjunct B]
his bad manners. [subject A]
*Notice the subject of something in the first part of the sentence.
It does the same job as the word entity in your example.

In English grammar, a delayed subject is a subject that appears at (or
  near) the end of a sentence, after the main verb. In such cases, the
  vacant subject position at the beginning is usually filled with a
  dummy word, such as it, there, or here.

It comes from this article: What Are Delayed Subjects in English Grammar? You can see if that's of any use to you.


text:
Q: Terraform data "azurerm_key_vault_secret" "version" attribute gives Error: "version": this field cannot be set I use data "azurerm_key_vault_secret" in Terraform to pull data from Azure Vault
Now I want to pull secret of specific version, I tried: version = "719f0d55d1a04c6b862430e00d61b9ae"
but it fails with Error: "version": this field cannot be set:

A: According to the resource's documentation, version is an exported attribute not an argument. The difference is that attributes are used as resource outputs in other terraform code, e.g. azurerm_key_vault_secret.var2.version, whereas arguments are values that you're allowed to specify as inputs to the resource.


text:
Q: Accessing IIS Localhost from Selenium docker container I have a .net application running on my windows machine on local host. I have also set up a selenium docker container using this command:
docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome

I can access the container fine by pointing the remote webdriver to localhost:4444
However when I run a test and tell the webdriver to navigate to "http://docker.for.win.localhost:51749" I get a connection refused error in the screenshot.
I've looked at similar questions but they were using different technologies and those solutions didn't work for me so I figured my problem might be slightly different as my website is running in IIS express in visual studio.
I have tried to SSH to the container and do a WGET on the same address and that ends up yielding a 400 error as shown below.
seluser@832dfa5515d6:/$ wget docker.for.win.localhost:51749
--2019-05-24 12:45:45--  http://docker.for.win.localhost:51749/
Resolving docker.for.win.localhost (docker.for.win.localhost)... 192.168.65.2
Connecting to docker.for.win.localhost (docker.for.win.localhost)|192.168.65.2|:51749... connected.
HTTP request sent, awaiting response... 400 Bad Request
2019-05-24 12:45:45 ERROR 400: Bad Request.

What could be the cause of this issue?
I am using Docker Desktop with engine 18.09.2 which is running on windows (although I believe the inside of the container is linux)
UPDATE
I just tried:
 curl -i -X GET -H "Host: localhost:51749" docker.for.win.localhost:51749

This ends up returning the HTML of the site. So it seems the container can actually see it... just selenium cant.


text:
Q: Java GC: top object classes promoted (by size)? Please let me know what is the best way to determine composition of young generation memory promoted to old generation, after each young GC event?
Ideally I would like to know class names which are responsible say, for 80% of heap in each "young gen -> old gen" promotion chunk;
Example: I have 600M young gen, each tenure promotes 6M; I want to know which objects compose this 6M.
Thank you.

A: There is no easy way to do this, however, I have recently been analyzing memory performance of large java apps, and can share some experience.
Here is how I found what objects are being promoted to old gen:
First you need to identify what objects are in "old/tenured" space. This is basically you standard java heap analysis. For this I recommend jmap. It is part of the sun jvm.
run:
jmap -dump:file=heap.hprof PID
to get a heap dump. This will pause the jvm during the dump (~for 30 secs on a 2GB heap)
Now load the .prof file in Memory analyser (the best tool for this, hands down)
I would spend a day playing with Memory analyzer to understand it, watch the screencam (needs a login, but worth it).
Now you will know what objects are in your heap.
Here is the trick: In the overview screen of Memory analyser, there is a link to: "Unreachable objects histogram". Now these objects are all to be collected during the next GC. But some are probably in eden, some in survivor and some in old.
Now, get some profiler with memory profiling capability, I prefer yourKit.
Run your app with yourkit and record object allocation.
Run it and record object creation. Once you have a list of objects created use all three lists to get a picture of what is going on. Do what humans do best, see patterns.

*

*What objects are created and are reachable. (Memory analyser)

*Objects unreachable in heap (Memory analyser)

*Objects created during a run (Profiler)

Another way to approach is YourKit generations view. You can take snapshots of your heap and compare what objects are still alive between snapshots. If you use this with visualgc you can determine how long an object must be alive to be promoted to old gen, and take snapshots at these intervals to see what objects are still alive.
Well, good luck.
/JT


text:
Q: JS clientWidth returning 0 sometimes but working other times I'm writing a program to change the positions of some subtitles. The user uploads a video, gets a thumbnail from the video, and then the editor shows up. A lot of the time, the clientWidth or clientHeight for the thumbnail just doesn't work and it breaks the range sliders. If you refresh though, it sometimes starts working again. I have no idea what the problem is, some help would be much appreciated.
    example.style.left = width.value;
thumbWidth = thumb.clientWidth - example.clientWidth;
thumbHeight = thumb.clientHeight - example.clientHeight;
width.setAttribute('max', thumbWidth);
console.log(thumb.clientWidth);
width.setAttribute('value', thumbWidth / 2);
subWidth();
height.setAttribute('max', thumbHeight);
height.setAttribute('value', thumbHeight / 2);
subHeight();
width.style.width = thumb.clientWidth + 'px';
console.log(thumb.clientWidth);
height.style.width = thumb.clientHeight + 'px';
editor.style.width = thumb.clientWidth = 'px';
editor.style.height = thumb.clientHeight + 'px';

Here is the fiddle.
Btw, I am aware the vertical slider is very hardcoded, but I will fix it later.