text:
Q: Teams tab does not update its content even though it has been changed I am creating a teams tab addon. I just created the project using yeoman, teams creator. Now the problem I have is that after I execute the command gulp serve, the project is served and is openable, but it does not render new content even after changing it. It is always in the state of a project at its starting point.
Here is my Tab component (as you can see there is an empty div in the return method):
import * as React from "react";
import {
  Provider,
  Flex,
  Text,
  Button,
  Header,
} from "@fluentui/react-northstar";
import { useState, useEffect } from "react";
import { useTeams } from "msteams-react-base-component";
import * as microsoftTeams from "@microsoft/teams-js";
import jwtDecode from "jwt-decode";
import axios from "axios";
import { HttpClient } from "../httpClient";

/**
 * Implementation of the Teams Demo Tab content page
 */
export const TeamsDemoTab = () => {
  const [{ inTeams, theme, context }] = useTeams();
  const [entityId, setEntityId] = useState<string | undefined>();
  const [name, setName] = useState<string>();
  const [error, setError] = useState<string>();

  useEffect(() => {
    const httpClient = new HttpClient();

    if (inTeams === true) {
      microsoftTeams.authentication.getAuthToken({
        successCallback: (token: string) => {
          const decoded: { [key: string]: any } = jwtDecode(token) as {
            [key: string]: any;
          };
          setName(decoded!.name);

          const serviceRequest: any = {
           [hidden for privacy]
          };

          httpClient.ExchangeForOBOToken(serviceRequest).then((res) => {
            console.log("baba");
            console.log(res.access_token);

            const config = {
              headers: { Authorization: `Bearer ${res.access_token}` },
            };

            axios
              .get("https://graph.microsoft.com/v1.0/me", config)
              .then(console.log)
              .catch(console.log);
          });
          microsoftTeams.appInitialization.notifySuccess();
        },
        failureCallback: (message: string) => {
          setError(message);
          microsoftTeams.appInitialization.notifyFailure({
            reason: microsoftTeams.appInitialization.FailedReason.AuthFailed,
            message,
          });
        },
        resources: [process.env.TAB_APP_URI as string],
      });
    } else {
      setEntityId("Not in Microsoft Teams");
    }
  }, [inTeams]);

  useEffect(() => {
    if (context) {
      setEntityId(context.entityId);
    }
  }, [context]);

  /**
   * The render() method to create the UI of the tab
   */
  return (

  );
};

but it always is this:
image url
Here is my manifest.json file:
{
  "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.11/MicrosoftTeams.schema.json",
  "manifestVersion": "1.11",
  "id": "{{APPLICATION_ID}}",
  "version": "{{VERSION}}",
  "packageName": "{{PACKAGE_NAME}}",
  "developer": {
    "name": "Vizibit",
    "websiteUrl": "https://{{PUBLIC_HOSTNAME}}",
    "privacyUrl": "https://{{PUBLIC_HOSTNAME}}/privacy.html",
    "termsOfUseUrl": "https://{{PUBLIC_HOSTNAME}}/tou.html"
  },
  "name": {
    "short": "Teams Demo",
    "full": "Teams Demo"
  },
  "description": {
    "short": "TODO: add short description here",
    "full": "TODO: add full description here"
  },
  "icons": {
    "outline": "icon-outline.png",
    "color": "icon-color.png"
  },
  "accentColor": "#D85028",
  "configurableTabs": [
    {
      "configurationUrl": "https://{{PUBLIC_HOSTNAME}}/teamsDemoTab/config.html?name={loginHint}&tenant={tid}&group={groupId}&theme={theme}",
      "canUpdateConfiguration": true,
      "scopes": [
        "team"
      ],
      "sharePointPreviewImage": "https://{{PUBLIC_HOSTNAME}}/assets/teamsDemoTab-preview.png",
      "supportedSharePointHosts": [
        "sharePointFullPage",
        "sharePointWebPart"
      ]
    }
  ],
  "staticTabs": [],
  "bots": [],
  "connectors": [],
  "composeExtensions": [],
  "permissions": [
    "identity",
    "messageTeamMembers"
  ],
  "validDomains": [
    "{{PUBLIC_HOSTNAME}}"
  ],
  "showLoadingIndicator": true,
  "webApplicationInfo": {
    "id": "{{TAB_APP_ID}}",
    "resource": "{{TAB_APP_URI}}"
  }
}

In the browser I get this:
browser error image


text:
Q: How to show the $f. (g .h)$ is a reparametrization of $(f .g). h ?$ Now days Im reading Allen Hatcher book
I have some confusion in Allen Hatcher book
My confusion is given below in red line

Author didn't explain in detail
My doubt :How to show the $f. (g .h)$ is a reparametrization
of $(f .g). h ?$

A: You just have to write the explicit definitions of the two compositions of paths and $\varphi$:
$(f\cdot (g\cdot h))(t)$ is:
$f(2t)$ if $t\in[0,\frac{1}{2}]$
$g(4t-2)$ if $t\in[\frac{1}{2},\frac{3}{4}]$
$h(4t-3)$ if $t\in[\frac{3}{4},1]$.
$((f\cdot g)\cdot h)(t)$ is:
$f(4t)$ if $t\in[0,\frac{1}{4}]$
$g(4t-1)$ if $t\in[\frac{1}{4},\frac{1}{2}]$
$h(2t-1)$ if $t\in[\frac{1}{2},1]$.
$\varphi(t)$ is:
$\frac{t}{2}$ if $t\in[0,\frac{1}{2}]$
$t-\frac{1}{4}$ if $t\in[\frac{1}{2},\frac{3}{4}]$
$2t-1$ if $t\in[\frac{3}{4},1]$.
Now, using the explicit definitions, you just have to check case by case (3 cases: $t\in[0,\frac{1}{2}]$,$t\in[\frac{1}{2},\frac{3}{4}]$ and $t\in[\frac{3}{4},1]$ ) that $((f\cdot g)\cdot h)(\varphi(t))=(f\cdot (g\cdot h))(t)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find out what killed my desktop environment (and possibly X Server)? I ran into a problem this morning. I have a computer that is used for machine learning and nothing else. I use python to run tensorflow to train some models that I made.
The problem is that I couldn't log into the machine over VNC this morning. Upon investigating I found out that the gnome shell had restarted and I had to login again. Unfortunately my whole session was gone. I figured that it might have been the oom killer - these machine learning programs tend to consume a lot of memory (the uptime is still over two months so it was not a complete restart). However, upon looking at the dmesg the last Out of memory message was logged two months ago.
From my machine learning session I know that the crash must have happened about one hour after midnight since this is the last time that something was written into the directory where the model is periodically saved.
I just cannot find any more logs about what has caused the crash.
When looking at /var/log/kern.log there is a  rfkill: input handler enabled message at around the same time as the crash happened. As far as I know this machine doesn't even have any wireless devices. The last message before that was some apparmor stuff four days ago.
I tried to use journalctl to look at the logs for the gdm.service and, despite claimining that the logs begin at the end of July, there is an entry at around the same time when the crash happened saying that a session opened for user gdm by (uid=0).
My question is: how can I find out what really happened and what killed the process?
[edit]
I just looked at the directory containing the machine learning code. I had a terminal with vim where all the python code was opened so I could quickly edit the code when I needed to. However, looking at the directory there are no swap files. Normally when a crash occurs the swap files just stay and you have to manually recover your vim session but this is not the case. Could the crash actually have been a more or less graceful restart of the display manager? If so are there any logs anywhere about that?


text:
Q: How to find a TFS alert not set up by you Someone has 'helpfully' set up a TFS 2008 Alert for a build on my behalf.  I want to turn it off but no one will own up and I can't find it.  Reading the docs suggests only the creator can see it.  Is there anyway to find it?

A: There's a codeplex tool that I've used in the past to subscribe and unsubscribe outside of the UI:
http://tfseventsubscription.codeplex.com/
You could also do it through the commandline using the BisSubscribe.exe tool that is installed on the TFS server.


text:
Q: jquery and google maps on page show event I have been using this code to show google maps in jquery mobile page show event but its not working..
$('#page3').live('pageshow', function(event, ui) {
    $('#googleMap').gmap().bind('init', function(ev, map) {
       $('#googleMap').gmap('addMarker', {'position': '57.7973333,12.0502107', 'bounds':
true}).click(function() {
               $('#googleMap').gmap('openInfoWindow', {'content': 'Hello World!'}, this);
                    });
           });
  });

A: I think this solution solve your problem:
Your map.html
<!DOCTYPE html>

<meta charset="utf-8">
<title>Map</title>

Your button to open map.html

    Close

See more info on jQuery Mobile - Popup iframes


text:
Q: Stack overflow error. using winforms I am getting a stack over flow error in my program. I have a class with functions and properties that I need my partial class with the winform textboxes,checkboxes, etc to be able to access. When i build it is fine but I get a run time error. It points to the default constructor I have and am using in the winform, as to where Visual Studio claims the stack overflowed.
code:
public class TeamCreator:Form
    {
        //fields
        public string[] players=new string[12];
        public int[] points=new int[12];
        public int currentPlayerScore=0;
        public TeamCreator()//default constructor
        {
            for (int i = 0; i < 11; i++)
            {
                this.players[i] = "";
                this.points[i] = 0;
            }

        }
        public TeamCreator(string[] teammates,int[] scores)//construct Team object with user input
        {
            this.players = teammates;
            this.points = scores;

        }
        public void setTeammates(string player,int index)//set players array
        {
            this.players[index] = player;
        }
        public void setPoints(int[] scoreList)//set points array
        {

                this.points = scoreList;
        }
        public void setPlayerScore(int playerScore,int playerNum)//sets a specific player's score
        {
            this.points[playerNum] = playerScore;

        }
        public int[] getPoints()//obtain array of points
        {
            int[] listOfPoints=new int[12];
            int i;
            for(i=0;i<11;i++)
            {
                listOfPoints[i]=this.points[i];
            }
            return listOfPoints;
        }
        public int totalPoints()//gets total points
        {
            int total=0;
            for(int i=0;i<11;i++)
            {
                total = this.points[i] + total;
            }
            return total;
        }
        public double meanPoints()//returns mean or average of total points
        {
            int total = this.totalPoints();
            int mean = total / 11;
            return mean;
        }
    }
}

              //winform code
              namespace TeamClass
{
    public partial class TeamClass:TeamCreator
    {
        public int indexOn = 0;
        public int current = 0;
        public TeamCreator newTeam = new TeamCreator();
        public TeamClass()
        {
            InitializeComponent();
        }

        private void playerInput_MouseLeave(object sender, EventArgs e)//adds players to players array and to list
        {
            string playerName = playerInput.Text;
            newTeam.setTeammates(playerName,this.indexOn);
            playerList.Items.Add(playerName);
            indexOn++;
        }
        TeamClass reopen = new TeamClass();
        private void restart_CheckedChanged(object sender, EventArgs e)//allows user to restart program and make a new team
        {
            this.Visible = false;
            reopen.Show();

        }

        private void playerScoreDisplay_CheckedChanged(object sender, EventArgs e)//displays currently selected player when checked
        {
            string currentPlayerSelected = newTeam.players[current];
            MessageBox.Show("The current player selected is " + currentPlayerSelected + ".", "Current Player", MessageBoxButtons.OK);
        }

        private void playerList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.current = playerList.SelectedIndex;

        }

        private void scoreInput_MouseLeave(object sender, EventArgs e)//gets player score
        {
            int currentScore;

            if (!Int32.TryParse(scoreInput.Text, out currentScore))
            {
                //tell user we can't parse the amount
                if (MessageBox.Show("Text did not parse to an integer, please try again", "Invalid Argument", MessageBoxButtons.RetryCancel) == System.Windows.Forms.DialogResult.Cancel)
                {
                    // leave method if they don't want to try again
                    return;
                }
                else
                {
                    //set the focus on the control so user can fix error
                    scoreInput.Focus();
                    //As a convenience select all text
                    scoreInput.SelectAll();
                    //exit method
                    return;
                }
            }

                newTeam.setPlayerScore(currentScore, current);

        }

        private void scoreInput_KeyPress(object sender, KeyPressEventArgs e)//makes sure numbers are being entered correctly for score
        {
            //only accept negative sign in first position
            if ((e.KeyChar == '-') && ((sender as TextBox).Text.Length == 0))
            {
                if ((sender as TextBox).Text.Contains("-"))
                    e.Handled = true;
            }
            //Only accept numbers, one decimal, one negative sign (-) and the backspace
            else if (!char.IsDigit(e.KeyChar) && !char.IsPunctuation(e.KeyChar) && !(e.KeyChar == 0x08))
            {
                e.Handled = true;
            }
        }

        private void totalPointsDisplay_CheckedChanged(object sender, EventArgs e)//displays total points when checked
        {
            int total=newTeam.totalPoints();
            MessageBox.Show("The total points for the team is " + total + ".", "Total Points", MessageBoxButtons.OK);
        }

        private void MeanPointsDisplay_CheckedChanged(object sender, EventArgs e)//displays mean points when checked
        {
            double avg=newTeam.meanPoints();
            MessageBox.Show("The mean points for the team is " + avg + ".", "Mean Points", MessageBoxButtons.OK);

        }

    }
  }

Any help as to why I am getting this error and how to fix it would be much appreciated. I am kinda new to C# so am unsure of what the issue is.

A: Unfortunately, you may not be able to tell much from the exception. Instead of a helpful stack trace, you'll see a message like:

Cannot evaluate expression because the current thread is in a stack overflow state

There are some ways around this if you do a search for "stackoverflow exception stack trace".
The root issue is almost always recursion, though, so look for something calling itself, or two or three methods calling one another in a loop.
After quickly scanning your code, I found one almost immediately (there may be others too). Every time you instantiate a TeamClass, you're creating another instance, which creates another instance, and on and on.
public partial class TeamClass:TeamCreator
{
    ...
    TeamClass reopen = new TeamClass();
    ...

A: Any reason you use the first 11 element in the array in all your code?
You define an array with 12 element but you always loop to the 11th element
 public string[] players=new string[12];
        public int[] points=new int[12];
        public int currentPlayerScore=0;
        public TeamCreator()//default constructor
        {
            here why you loop to 11 it suppose to be 12 or the array.Length
            for (int i = 0; i < 11; i++)
            {
                this.players[i] = "";
                this.points[i] = 0;
            }


text:
Q: Printing through PrintQueue job in ASP.NET MVC fails with 0 byte size printed file I tried this example from MSDN in an ASP.NET MVC project:
public void Print(string printQueueName, string printData)
    {
        PrintQueue printerQueue = new LocalPrintServer().GetPrintQueue(printQueueName);

        // Call AddJob
        PrintSystemJobInfo myPrintJob = printerQueue.AddJob();

        // Write a Byte buffer to the JobStream and close the stream
        Stream myStream = myPrintJob.JobStream;
        Byte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes(printData);
        myStream.Write(myByteBuffer, 0, myByteBuffer.Length);
        myStream.Close();
    }

I tried to print to PDF, XPS and OneNote virtual printers. After confirming printing dialog, printing job appears in printer queue then disappears, and the printed file is created, but with 0 byte size!!!
I don't know where is my fault, and hope to find help here.
Thanks in advance.

A: The example here which is close to MSDN does not work on my printer either.  It's irrelevant because this example is not sufficient to print PDF or XPS as one cannot simply output a byte stream of these types as a stream to the printer.  You have at least a few options:

*

*Use PrintDocument.  Convert the PDF/TIFF/Possibly onenote files to Images (E.G. tiff files) and you can print with this class using the event PrintDocument.PrintPage and  Graphics.DrawImage.

*Use/Buy 3rd party print API's for PDF.  You can get away with direct XPS printing, but it's got some issues (see details below).  OneNote I don't know.

*Print the files via the command line using Process

*Write your own print drivers

Further Details
I'm not familiar with OneNote printing.  XPS printing can be quite tricky.  The margins need to be calculated in code because they depend on the printer settings which can be found in the PrintTicket.  Using WPF (which is closely tied to XPS) there's a bug I discovered somewhere in the XPS serialization process. XpsDocument does not preserve the calculated printable area.  Documents will print with default printable areas which can result in cut off.  I confirmed this bug on Microsoft Connect.  See their response below.
Finally, if you just happen to be running SSRS then you can easily change the output type from PDF/XPS to image.
Feedback for XPS bug on Microsoft Connect (link is private):

Title: XpsDocument does not preserve the calculated arrangement for WPF's >FixedPage.Arrange()
The WPF team has recently reviewed this issue and will not be
addressing this issue as at this time the team is focusing on the bugs
impacting the highest number of WPF developers. If you believe that
this was resolved in error, please reactivate this bug with any
necessary supporting details.
We appreciate the feedback. However, this issue will not be addressed
in the next version of WPF. Thank you. –WPF Team

.


text:
Q: Capybara: How do I test that a table has 3 rows using Capybara? How do I test that a table has 3 rows using Capybara?

A: page.should have_selector('table tr', :count => 3)

you can also do minimum or maximum
page.should have_selector('table tr', :minimum => 3)


text:
Q: Share MS Access 2010 database over the internet Is it possible to access MS Access 2010 database over the internet without using Sharepoint or similar services? I have a server where I want to put the back end and email the front end to various people. As I understand this is easy if all the users are on the local network. But how do I share my database over the internet? Thanks.

A: MS Access 2010 is a file-based database.  Thus the only way to share it with a separate front-end / back-end database (linked tables) setup is if you expose the file share on the Internet.  This is most definitely NOT a good idea.
Even if you use a VPN to add security you will probably find performance unacceptable.  The only realistic solution is to use a SQL Server back-end and link to that from the MS Access front-end databases.

A: Host the app on Windows Terminal Server.


text:
Q: SortedList vs. SortedDictionary vs. Sort() This is a continuation of questions like this one.
Are there any guidelines for tweaking the performance? I don't mean gains in big-O, just saving some linear time.
For example, how much does pre-sorting save on either SortedList or SortedDictionary?
Say I have a person-class with 3 properties to sort on, one of them is age in years. Should I bucket the objects on age first?
Should I first sort on one property, then use the resulting list/dictionary to sort on two properties and so on?
Any other optimizations that spring to mind?

A: Well, it's an easy win on SortedList.  Inserting an item requires a binary search (O(log(n)) to find the insertion point, then a List.Insert (O(n)) to insert the item.  The Insert() dominates, populating the list requires O(n^2).  If the input items are already sorted then the Insert collapses to O(1) but doesn't affect the search.  Populating is now O(nlog(n)).  You don't worry how big the Oh is, sorting first is always more efficient.  Assuming you can afford the doubled storage requirement.
SortedDictionary is different, it uses a red-black tree.  Finding the insertion point requires O(log(n)).  Rebalancing the tree might be required afterwards, that also takes O(log(n)).  Populating the dictionary thus takes O(nlog(n)).  Using sorted input does not change the effort to find the insertion point or rebalancing, it is still O(nlog(n)).  Now the Oh matters though, inserting sorted input requires the tree to constant rebalance itself.  It works better if the input is random, you don't want sorted input.
So populating SortedList with sorted input and populating SortedDictionary with unsorted input is both O(nlog(n)).  Ignoring the cost of providing sorted input, the Oh of SortedList is smaller than the Oh of SortedDictionary.  That's an implementation detail due to the way List allocates memory.  It only has to do so O(log(n)) times, a red-black tree has to allocate O(n) times.  Very small Oh btw.
Notable is that neither one compares favorably over simply populating a List, then calling Sort().  That's also O(nlog(n)).  In fact, if input is already accidentally sorted you can bypass the Sort() call, this collapses to O(n).  The cost analysis now needs to move to the effort it takes to get the input sorted.  It is hard to bypass the fundamental complexity of Sort(), O(nlog(n)).  It might not be readily visible, you might get the input sorted by, say, a SQL query. It will just take longer to complete.
The point of using either SortedList or SortedDictonary is to keep the collection sorted after inserts.  If you only worry about populating but not mutating then you shouldn't use those collections.


text:
Q: Coldfusion query weird characters Problem
My (windows) server is showing an odd error when I use a query. However locally the query works just fine. The server adds  everywhere in the query.
The Error

Error Executing Database Query.
You have an error in your SQL syntax;
  check the manual that corresponds to
  your MySQL server version for the
  right syntax to use near '.product
  = ao_products.id where ao_ranks.target = '1' order by
  ao_ranks.rank as' at line 1
<cfset start = (page*perpage)-perpage>
  <cfquery name="get">
    select category,ao_products.id,model,name,rank,rating

from ao_ranks inner join  ao_products
  on ao_ranks.product =ÂÂ
  ao_products.id where ao_ranks.target =
  '#target#' order by ao_ranks.rank asc
  limit #start#,#perpage#

VENDORERRORCODE     1064
SQLSTATE    42000
SQL      select
  category,ao_products.id,model,name,rank,rating
  from ao_ranks inner join ao_products
  on ao_ranks.product = ao_products.id
  where ao_ranks.target = '1' order by
  ao_ranks.rank asc limit 0,16

The Code (utf-8 encoded file)
<cfelse>
<cfset start = (page*perpage)-perpage>
  <cfquery name="get">
    select category,ao_products.id,model,name,rank,rating from ao_ranks inner join ao_products on ao_ranks.product = ao_products.id where ao_ranks.target = '#target#' order by ao_ranks.rank asc  limit #start#,#perpage#
  </cfquery>
</cfif>

A: I solved this by capitalizing "on" in the query. I have no clue how this helped. But it did.


text:
Q: Unboxing for dynamic type Consider the following code:
public class Foo1
{
    public dynamic dowork()
    {
        return 10;
    }
}

And in my Main , I call like:
int i = new Foo1().dowork();

The return value is 10. My question is why no Unboxing is required here?But in watch I've verified the Return Type of dowork is System.Object.

A: It is unboxing - but it's doing it implicitly. There's an implicit conversion from any dynamic expression to any type. The exact conversion performed will depend on the execution-time type of the value.
From section 6.1.8 of the C# 5 specification:

An implicit dynamic conversion exists from an expression of type dynamic to any type T. The conversion is dynamically bound (§7.2.2), which means that an implicit conversion will be sought at run-time from the run-time type of the expression to T. If no conversion is found, a run-time exception is thrown.

(There's a slight nuance here in that it's a conversion from any expression of type dynamic rather than a conversion from the dynamic type itself. That avoids some conversion loops which would cause issues elsewhere in the spec.)


text:
Q: php mysql sort result by value of field using position of substring I have field name "codehead" whose values are like
"53/066/10"
"54/066/05"
"56/066/09"
"52/069/15"
"53/069/02"
"67/069/02"
"00/020/80"
"00/020/98"

I want the results to be in following order
"00/020/80"
"00/020/98"
"53/066/05"
"53/066/10"
"54/066/09"
"52/069/15"
"53/069/02"
"67/069/02"

I have tried query like
$data= mysql_query("select codehead,sign, SUM(amt) as amt from pm where month='$pmmonth' and rc='R' GROUP BY substr(codehead,4,3) ASC,substr(codehead,7,2) ASC,  sign ")

but could not get complete result.

A: This expression:
substr(codehead,7,2)

Is returning a forward slash and a digit. Looks like you wanted to start at position 8.
But that won't satisfy the order shown, the fifth row has 09, and that would come before 10 on the preceding row. The desired result shown makes it look like the result is also ordered on LEFT(codehead,2)
 GROUP BY codehead, `sign`
 ORDER BY substr(codehead,4,3)  ASC
        , LEFT(codehead,2)      ASC
        , substr(codehead,8,2)  ASC

NOTE: In some future release of MySQL, the non-Standard MysQL extension of the GROUP BY to imply an ORDER BY may be removed.
I'm very suspicious of the GROUP BY on just the substrings. That's valid SQL to do that, I just question how you want to handle codehead values that match on the substrings, but is different in some other place... especially given that you're returning codehead in the SELECT list.
The normative pattern is to GROUP BY expressions in the SELECT list.

A: You can do something like this:
SELECT codehead,
  substring(codehead,1,2) as 'one',
  substring(codehead,4,3) as 'two',
  substring(codehead,8,2) as 'three'
FROM foo
ORDER BY `two`, `one`, `three` ASC

SQLfiddle
and it will work, but it's going to have subpar performance because it's impossible to use indexes for that sort.
To address this you could add a new field to the table, eg sortkey, and insert a string in the format $two.$one.$three for each row. Then you can index and sort on that. Better yet, split all three values into their own fields and then you can index and sort however you want.


text:
Q: iOS NotificationServiceExtension is not working I have enabled NotificationServiceExtension in my app. And done the following

*

*Added .apppex under Frameworks, Libraries and Embedded contents

*Confirmed both deployment target version is 12.0

*Sending mutable-content": 1 in my apns notification payload

*Following is my NotificationService's didReceiveNotificationRequest method
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {

self.bestAttemptContent = [request.content mutableCopy];

self.bestAttemptContent.badge = @20;
self.contentHandler(self.bestAttemptContent);

}
Don't know what I am missing here. Searched and followed so many documents. Nothing seems to be working.
I am using XCode 11.2.1 and  real device with ios version 13.


text:
Q: How to update time in DateTime() in access in increasing order with regular time interval? How to update time in DateTime() to access in an increasing order with regular time interval?
I want to update time with difference of 4 min, for particular set of records. for example time
03-06-2015 11:45:37 AM.

Now I want to update 20 records with time difference of 4 min i.e.
03-06-2015 11:45:37 AM,
03-06-2015 11:49:37 AM,
03-06-2015 11:53:37 AM,
03-06-2015 11:57:37 AM,
03-06-2015 12:01:37 PM,
03-06-2015 12:05:37 PM

A: Open a recordset holding the 20 records and read time (StartTime) from the first record.
Then loop through the recordset doing an Edit and Update for each record where you set:
rs.Edit
    StartTime = DateAdd("n", 4, StartTime)
    rs!YourTimeField.Value = StartTime
rs.Update
rs.MoveNext

A query can look like this:
SELECT DISTINCT
    10 * Abs([Deca].[id] Mod 10) + Abs([Uno].[id] Mod 10) AS Id,
    DateAdd("n",[Id] * 4, [StartTime]) AS NextTime
FROM
    msysobjects AS Uno,
    msysobjects AS Deca
WHERE
    (10*Abs([Deca].[id] Mod 10) + Abs([Uno].[id] Mod 10)) < 20;

Result:
Id  NextTime
0   03-06-2015 11:45:37
1   03-06-2015 11:49:37
2   03-06-2015 11:53:37
3   03-06-2015 11:57:37
4   03-06-2015 12:01:37
5   03-06-2015 12:05:37
6   03-06-2015 12:09:37
7   03-06-2015 12:13:37
8   03-06-2015 12:17:37
9   03-06-2015 12:21:37
10  03-06-2015 12:25:37
11  03-06-2015 12:29:37
12  03-06-2015 12:33:37
13  03-06-2015 12:37:37
14  03-06-2015 12:41:37
15  03-06-2015 12:45:37
16  03-06-2015 12:49:37
17  03-06-2015 12:53:37
18  03-06-2015 12:57:37
19  03-06-2015 13:01:37


text:
Q: "What a beautiful are your works" vs "How beautiful are your works" What is the difference in the meaning in the two following sentences?
a) "What a beautiful are your works!"
b) "How beautiful are your works!"
The context: I see my friend in his exposition of his paintings and I want to compliment him.

A: Sentence (a) isn't grammatically correct because "beautiful" is not a noun. Compare that to "What a piece of work is man" or "What fools these mortals be." In this type of construction, "What a" must be followed by a singular noun with or without modifiers (or you can use "what" with no "a" followed by a plural noun). This is the adjective sense of "what". Here's the definition from Webster's Third New International Dictionary, Unabridged:

how remarkable for good or bad qualities :  how surprising :  how
  great :  how small — used especially in exclamatory utterances and in
  dependent clauses of like nature

Sentence (b) is fine. It says that his works are beautiful, and beautiful is intensified by the use of the construction "how beautiful."
You could also say "Your paintings are beautiful" or "Your paintings are so beautiful." Those are simpler ways of saying the same thing.

A: Exclamations are sentences spoken with emphasis. How and what are often used to form them.
Compare these patterns :

How beautiful are your works? (A question )
How beautiful your works are! (An exclamation )

Another pattern uses what

What beautiful pictures (works of art)!

Or just Lovely!
Aren't they beautiful!

A:
What is the difference in the meaning in the two following sentences?

The words order isn't quite correct but both are saying the same thing.
If want to use the "what" pronoun for emphasis, as much as you could say:

"What big ears you have, Grandma," said Little Red Riding Hood.
"What a great dinner you've made, John!"
What a long trip!
What interesting news!
What interesting questions you've asked!
What little time she has she doesn't spend on shopping!

You could say:

What beautiful your works are!"

Same with the "how" adverb.

How difficult these questions are!
How small she is!
How beautifully he dances!
How big his ayes are!
I can't believe how fast they got here!

You could say:

How beautiful your works are!

That said, probably neither of those sentences sound quite natural for the context you present. Maybe something like:

Wow! Your work is really beautiful!

Note that there's no need for pluralising the work.


text:
Q: TortoiseHg with word diffs and LaTeX I am having a hard time figuring out how to configure TortoiseHg to do colored word diffs for my TeX and LaTeX documents. I found the following two threads

*

*How to use Mercurial for version control of text documents?

*Good strategy for line breaks with paragraphs of LaTeX source
but they don't go in detail how to to set this up on TortoiseHg. I was wondering if anybody in the TeX/LaTeX community has figured this out already?


text:
Q: How to populate multiple sqlite tables from a single xml file? I've been able to successfully bring in data to a single table, but need to bring data for several tables.  Is it possible to do this from a single xml file?
    //Open xml file
    XmlResourceParser _xml = res.getXml(R.xml.animals_records);
    try
    {
        //Check for end of document
        int eventType = _xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            //Search for record tags
            if ((eventType == XmlPullParser.START_TAG) &&(_xml.getName().equals("record"))){
                //Record tag found, now get values and insert record
                String _Title = _xml.getAttributeValue(null, TITLE);
                String _Color = _xml.getAttributeValue(null, COLOR, 0);
                _Values.put(TITLE, _Title);
                _Values.put(COLOR, _Color);
                db.insert(TABLENAME1, null, _Values);
            }
            if ((eventType == XmlPullParser.START_TAG) &&(_xml.getName().equals("trees"))){
                //Record tag found, now get values and insert record
                String _Title = _xml.getAttributeValue(null, FAMILY);
                String _Color = _xml.getAttributeValue(null, SPECIES, 0);
                _Values.put(FAMILY, _Title);
                _Values.put(SPECIES, _Color);
                db.insert(TABLENAME2, null, _Values);
            }
            eventType = _xml.next();
        }
    }

With an XML that looks something like this:
    <animals>
        <record title="Dog" color="Brown" />
        <record title="Cat" color="Gray" />
        <record title="Rabbit" color="White" />
        <record title="Spider" color="Black" />
        <trees family="Hardwood" species="Oak" />
        <trees family="Soft" color="Pine" />
     </animals>

Any ideas?  Obvious faults?


text:
Q: get object value by unknown key name in javascript var json ={
    "my_location": {
        "city": "city",
        "title": "my title",
        "complete_address": "my complete address",
        "geo": {
            "lat": 1.11111111,
            "lng": 1.22222222
        }
    }
}

I want to get by a string key name like this
var key_name="my_location.geo.lat"

please help me how i can get the value by usig this key_name in javascript

A: const getPropValue = (object, path = '') =>
path.split('.')
    .reduce((o, x) => o == undefined ? o : o[x]
    , object)

test with:
getPropValue(json, "my_location.geo.lat")


text:
Q: Parsing csv data into object with different column length I am new to Java and practicing parsing csv file into the object. I've tried but cannot figure it out.
The file looks like this:
  [0],    [1], [2],    [3]  ,    [4]    ,   [5]   ,  [6] ,   [7]  ,  [8] , [9]
class, gender, age, bodyType, profession, pregnant, isYou ,species, isPet, role
scenario:green,   ,         ,           ,         ,        ,      ,      ,
person, female, 24, average ,           , FALSE   ,        ,      ,      , passenger
animal, male  ,  4,         ,           , FALSE   ,        , dog  , TRUE , pedestrian
scenario:red
person, male  , 16, athletic, boxer     , FALSE   ,  TRUE  ,      ,      , passenger
person, female, 25, athletic, doctor    , TRUE    ,  FALSE ,      ,      , pedestrian

I need to parse it by any number of passengers and pedestrians with any scenarios. Finally, add these scenarios into an ArrayList for analyzing.
What I think is to:

*

*loop through each line, stops when reaches to the next scenario:red, adds the passengers and the pedestrians to the Character ArrayList. (I've done adding, but don't how to stop).

*Create a scenario using constructor scenario(ArrayList<Character> passenger, ArrayList<Character> pedestrians, boolean redOrGreen);

*The ArrayList scenarios add the created scenarios.

What I've done is put everything together instead of separate them. Any help or hint is highly appreciated.
Thanks for this community who helped me, here is what I've got so far.
    public void loadCsv() throws IOException {

    String csvFile = "config.csv";
    String line = "";
    String csvSplit = "\\s*,\\s*";

    Scenario scenario = new Scenario();
    Person person = new Person();
    Animal animal = new Animal();

    ArrayList<Scenario> scenaios = new ArrayList<Scenario>();
    ArrayList<String> csvContents = new ArrayList<String>();

    ArrayList<Character> passengers = new ArrayList<Character>();
    ArrayList<Character> pedestrians = new ArrayList<Character>();

    try (BufferedReader csvReader = new BufferedReader(new FileReader(csvFile));) {
        String headerLine = csvReader.readLine(); //get rid of the header
        //add each line to the arrayList
        while ((line = csvReader.readLine()) != null) {
            csvContents.add(line);
        }

        for(String csvLine : csvContents) {
            String[] data = csvLine.split(csvSplit); // split by comma and remove redundant spaces

            if (data.length == NO_OF_FIELD) { //check and avoid indexOutOfBoundException

                String clazz = data[0].toLowerCase();// cannot use word "class" as a variable

                if (clazz.startsWith("scenario") && data.length == 1) {
                    scenario = new Scenario();
                    scenario.setLegalCrossing(clazz.endsWith("green"));
                    continue;
                }

                else if ("person".equals(clazz) && data.length ==10) {

                    person = loadCsvPerson(data);
                    addCharacter(person, data);

                }

                else if ("animal".equals(clazz) && data.length ==10) {

                    animal = loadCsvAnimal(data);
                    addCharacter(animal, data);

                    }
                }
            }
        }
        //passenger and pedestrians are in position
        System.out.println("passengers: " + passengers);
        System.out.println("pedestrians: " + pedestrians);

        if (null != scenario) {
            scenario.setPassengers(passengers);
            scenario.setPedestrians(pedestrians);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

A: If it is possible to change the csv file format, I would add scenario type column (and scenario id or name if required), so you can work with csv file as a result set from database when you join tables (scenario + passenger + pedestrian) and return plain rows.
With this approach you will be able to delegate parsing to any csv library and do your logic (group by scenario id/name/type) separately. With surrogate rows you have (scenario:green...) you have to write your custom parser.
For example, you can use univocity to simply parse file into your model (even using annotations) and iteratively group it and handle.

A: Or if you need to work with existing file format do something like that:
if (clazz.startsWith("scenario") && data.length == 1) {
    // collect existing scenario before starting processing new one
    if (scenario != null) {
        scenario.setPassengers(passengers);
        scenario.setPedestrians(pedestrians);

        passengers = new ArrayList();
        pedestrians = new ArrayList();

        scenarios.add(scenario);
    }

    // now start new group (scenario)
    scenario = new Scenario();
    scenario.setLegalCrossing(clazz.endsWith("green"));
    continue;
}

A: Following things need to be addressed in your code:

*

*Strive to avoid using the name of a class which is already used by the standard library (and especially when it is in the default package, java.lang) e.g. there is already a class Character in Java library and therefore you should use a different name for your custom class.

*Use continue to skip the line, scenario:red
for(String csvLine : csvContents) {
    if(csvLine.equals("scenario:red")){
        continue;
    }
    String[] data = csvLine.split(csvSplit); // split by comma and remove redundant spaces

    if (data.length == NO_OF_FIELD) {
        //..
    }
    //..
}

*If you have already defined final int NO_OF_FIELD = 10, you can use the same instead of using the value 10 directly i.e. you should use NO_OF_FIELD instead of 10 in the following code:
if (data.length == NO_OF_FIELD) { //check and avoid indexOutOfBoundException

    String clazz = data[0].toLowerCase();// cannot use word "class" as a variable

    //...

    else if ("person".equals(clazz) && data.length ==10) {

However, you also need to understand that && data.length ==10 is unnecessary here as you have already checked data.length == NO_OF_FIELD in the enclosing if condition.
I couldn't understand the rest of your points. If you clarify them, I'll be able to help you further.

A: I need to add the previous scenario in the second round.
Since the last set of data won't be captured, I need to set another new scenario to add it in. Thanks for the art sir.
Character character = null;
    try (BufferedReader csvReader = new BufferedReader(new FileReader(csvFile));) {
        String headerLine = csvReader.readLine(); //get rid of the header
        //add each line to the arrayList
        while ((line = csvReader.readLine()) != null) {
            csvContents.add(line);
        }
        final int NO_OF_FIELDS = 10;

        for(String csvLine : csvContents) {
            String[] data = csvLine.split(csvSplit); // split by comma and remove redundant spaces
            String clazz = data[0].toLowerCase();// cannot use word "class" as a variable

            if (clazz.startsWith("scenario") && data.length == 1) {
                // adding scenario after one set of data
                // i.e second round adding the first round data
                if (passengers.size() != 0 && pedestrians.size() != 0) {
                    Scenario scenario = new Scenario();
                    scenario.setPassengers(passengers);
                    scenario.setPedestrians(pedestrians);
                    scenarios.add(scenario);
                }

                passengers = new ArrayList<Character>();
                pedestrians = new ArrayList<Character>();

                if (clazz.endsWith("green")) {
                    scenario.setLegalCrossing(true);
                    System.out.println("green light");
                }

                else if (clazz.endsWith("red")){
                    scenario.setLegalCrossing(false);
                    System.out.println("red light");
                }

                continue;
            }
        //...
            Scenario scenario = new Scenario();
            scenario.setPassengers(passengers);
            scenario.setPedestrians(pedestrians);
            scenarios.add(scenario);

            scenario.setPassengers(passengers);
            scenario.setPedestrians(pedestrians);

            Audit audit = new Audit();
            audit.setScenario(scenarios);


text:
Q: Preflight OPTIONS request by AngularJS not working with Chrome? I have developed a simple application using AngularJS hosted here. I am consuming an API I developed myself in Laravel hosted here. When I try to log into the application using Firefox, it works fine. My API accepts the pre-flight OPTIONS request and responds with a 200 OK. Finally the POST request generates a token and the user is logged in.
On the other hand, when Chrome sends the pre-flight OPTIONS request, it receives an 403 back and it gives me this error in the console:
XMLHttpRequest cannot load http://angulairapi.rohanchhabra.in/auth. Invalid HTTP status code 403

I have tried sending the OPTIONS request on /auth via Postman REST client also, and it gives back a 200 OK as expected. Why is Chrome behaving like this? What am I missing?

A: In first you have to send those Headers (wildcard works incorrect sometimes):
Access-Control-Allow-Headers: X-Requested-With, content-type
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS

In second (and important) remove header from AngularJs service $httpProvider in config:
myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

A: in filters.php (Laravel 4.2)
add below
App::before(function($request)
{
    // Enable CORS
    // In production, replace * with http://yourdomain.com
    header("Access-Control-Allow-Origin: *");
    //header('Access-Control-Allow-Credentials: true'); optional

    if (Request::getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        $headers = [
            'Access-Control-Allow-Methods'=> '*',
            'Access-Control-Allow-Headers'=> '*'
        ];
        return Response::make('You are connected to the API', 200, $headers);
    }
});

you can change the values of Access-Control-* to suite your need

A: The Access Control is a server responsibility, you need config this in Laravel.
Use this package: Laravel Cors this helps very much.

A: Problem in "Access-Control-Request-Headers: accept".
You need to add "accept" to your "Access-Control-Allow-Headers".
Compare this two request:

*

*Chrome: 403 Forbidden
curl 'http://angulairapi.rohanchhabra.in/auth' -X OPTIONS -H 'Access-Control-Request-Method: POST' /angulair.rohanchhabra.in' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' -H 'Accept: /' -H 'Referer: http://angulair.rohanchhabra.in/' -H 'Connection: keep-alive' -H 'Access-Control-Request-Headers: accept, content-type' -v

*Firefox: 200 OK
curl 'http://angulairapi.rohanchhabra.in/auth' -X OPTIONS -H 'Access-Control-Request-Method: POST' -H 'Origin: http://angulair.rohanchhabra.in' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' -H 'Accept: /' -H 'Referer: http://angulair.rohanchhabra.in/' -H 'Connection: keep-alive' -H 'Access-Control-Request-Headers: content-type' -v

A: In Laravel, try to set : 'Access-Control-Allow-Methods' & 'Access-Control-Allow-Headers' to '*'
public function handle($request, Closure $next)
 {

   header("Access-Control-Allow-Origin: *");

  // ALLOW OPTIONS METHOD
  $headers = [
         'Access-Control-Allow-Methods'=> '*',
         'Access-Control-Allow-Headers'=> '*'
     ];
  if($request->getMethod() == "OPTIONS") {
         // The client-side application can set only headers allowed in Access-Control-Allow-Headers
         return Response::make('OK', 200, $headers);
     }

     $response = $next($request);
     foreach($headers as $key => $value)
      $response->header($key, $value);
  return $response;
 }


text:
Q: Core-Plot region as part of View? The dilemma below seems like a very easy problem to overcome, yet I can't find anything about how to tackle it.  I've checked various tutorials, as well as all the sample code bundled with Core-Plot.
I've recently set up a new iPhone view-based application. However, I don't want the graph to take up the whole screen/view.

A: You can put a UIView inside your main UIView. Then change the type of that inner view to the UIView subclass that you need, such as CPGraphHostingView.


text:
Q: Problem with tikz : alignment of figure when using bracket in xlabel When I put bracket in a xlabel, the alignement of my figure change. It's just a little move, but it's uggly because i put two sub figures side by side.
Do you know how to solve this ?
Thanks in advance,
Thomas
PS : I think Here : TikZ graph not aligning is the same problem, but unresolved.

\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{subcaption}

\begin{document}

\begin{figure}
\centering
\begin{subfigure}[b]{0.45 \textwidth}
\caption{sub-figure 1}
\begin{tikzpicture}
\tikzstyle{every node}=[font=\small]
\begin{axis}[height=\textwidth,width=\textwidth,
axis lines=left, enlarge x limits=true, enlarge y limits=true,
xlabel={x},
scaled x ticks = false,
ylabel={y},
x tick label style={/pgf/number format/fixed, /pgf/number format/1000 sep = \thinspace},
]
\addplot[ybar,ybar interval=0] coordinates{
(0,8) (500,87) (1000,127) (1500,93) (2000,68) (2500,51) (3000,40) (3500,17) (4000,19) (4500,14) (5000,11)                   (5500,2) (6000,1) (6500,1) (7000,0)};
\end{axis}
\end{tikzpicture}
\end{subfigure}
~
\begin{subfigure}[b]{0.45 \textwidth}
\caption{sub-figure 2}
\begin{tikzpicture}
\tikzstyle{every node}=[font=\small]
\begin{axis}[height=\textwidth,width=\textwidth,
axis lines=left, enlarge x limits=true, enlarge y limits=true,
xlabel={x {(test)}},
scaled x ticks = false,
ylabel={x},
x tick label style={/pgf/number format/fixed, /pgf/number format/1000 sep = \thinspace},
]
\addplot[ybar,ybar interval=0] coordinates{
(0,8) (500,87) (1000,127) (1500,93) (2000,68) (2500,51) (3000,40) (3500,17) (4000,19) (4500,14) (5000,11)                   (5500,2) (6000,1) (6500,1) (7000,0)};
\end{axis}
\end{tikzpicture}
\end{subfigure}
\end{figure}
\vfill
\end{document}

A: There are several ways to fix this:

*

*As per Zarko's comment you can add a xlabel={$x$ \vphantom{(test)}}. The reason is the initial mismatch was the additional height of the (. Adding a \vphantom ensures that the both labels are of the same height. You actually on need a \vphantom{(}, but in other cases you may need the full text of the other label.

*Add a strut as in xlabel={$x$\strut}.  The \strut should be added to both of the labels.

*Specify a style for the xlabel which positions the label correctly (as in the MWE below).

Notes:

*

*Axis labels should probably be in math mode as per the MWE below.

Code:
\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{subcaption}

\pgfplotsset{compat=1.11}

\begin{document}

\begin{figure}
\centering
\begin{subfigure}[b]{0.45 \textwidth}
\caption{sub-figure 1}
\begin{tikzpicture}
\tikzstyle{every node}=[font=\small]
\begin{axis}[height=\textwidth,width=\textwidth,
axis lines=left, enlarge x limits=true, enlarge y limits=true,
xlabel={$x$},
scaled x ticks = false,
ylabel={$y$},
x tick label style={/pgf/number format/fixed, /pgf/number format/1000 sep = \thinspace},
xlabel style={at={(0.5,0)}, below,yshift=-25pt, anchor=base, inner sep=0pt, minimum height=2.0ex}
]
\addplot[ybar,ybar interval=0] coordinates{
(0,8) (500,87) (1000,127) (1500,93) (2000,68) (2500,51) (3000,40) (3500,17) (4000,19) (4500,14) (5000,11)                   (5500,2) (6000,1) (6500,1) (7000,0)};
\end{axis}
\end{tikzpicture}
\end{subfigure}
~
\begin{subfigure}[b]{0.45 \textwidth}
\caption{sub-figure 2}
\begin{tikzpicture}
\tikzstyle{every node}=[font=\small]
\begin{axis}[height=\textwidth,width=\textwidth,
axis lines=left, enlarge x limits=true, enlarge y limits=true,
xlabel={$x$ (test)},
scaled x ticks = false,
ylabel={$x$},
x tick label style={/pgf/number format/fixed, /pgf/number format/1000 sep = \thinspace},
xlabel style={at={(0.5,0)}, below,yshift=-25pt, anchor=base, inner sep=0pt, minimum height=2.0ex}
]
\addplot[ybar,ybar interval=0] coordinates{
(0,8) (500,87) (1000,127) (1500,93) (2000,68) (2500,51) (3000,40) (3500,17) (4000,19) (4500,14) (5000,11)                   (5500,2) (6000,1) (6500,1) (7000,0)};
\end{axis}
\end{tikzpicture}
\end{subfigure}
\end{figure}
\vfill
\end{document}

A: A label generally fit on one line. So you can set the height and depth of the text for all axis labels:
\pgfplotsset{
  compat=1.11,
  label style={text height=.8em,text depth=.15em},
}

With this style, your figures are correctly aligned (horizontally and vertically) and labels use the same baseline.
Your MWE, completed:
\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{subcaption}

\pgfplotsset{
  compat=1.11,
  label style={text height=.8em,text depth=.15em},
}

\begin{document}
\begin{figure}
  \centering
  \begin{subfigure}[b]{0.45 \textwidth}
    \caption{sub-figure 1}
    \begin{tikzpicture}
      \tikzstyle{every node}=[font=\small]
      \begin{axis}[height=\textwidth,width=\textwidth,
        axis lines=left, enlarge x limits=true, enlarge y limits=true,
        xlabel={x},
        scaled x ticks = false,
        ylabel={y},
        x tick label style={/pgf/number format/fixed, /pgf/number format/1000 sep = \thinspace},
        ]
        \addplot[ybar,ybar interval=0] coordinates{
          (0,8) (500,87) (1000,127) (1500,93) (2000,68) (2500,51) (3000,40) (3500,17) (4000,19) (4500,14) (5000,11)                   (5500,2) (6000,1) (6500,1) (7000,0)};
      \end{axis}
    \end{tikzpicture}
  \end{subfigure}
  ~
  \begin{subfigure}[b]{0.45 \textwidth}
    \caption{sub-figure 2}
    \begin{tikzpicture}
      \tikzstyle{every node}=[font=\small]
      \begin{axis}[height=\textwidth,width=\textwidth,
        axis lines=left, enlarge x limits=true, enlarge y limits=true,
        xlabel={x {(test)}},
        scaled x ticks = false,
        ylabel={x},
        x tick label style={/pgf/number format/fixed, /pgf/number format/1000 sep = \thinspace},
        ]
        \addplot[ybar,ybar interval=0] coordinates{
          (0,8) (500,87) (1000,127) (1500,93) (2000,68) (2500,51) (3000,40) (3500,17) (4000,19) (4500,14) (5000,11)                   (5500,2) (6000,1) (6500,1) (7000,0)};
      \end{axis}
    \end{tikzpicture}
  \end{subfigure}
\end{figure}
\vfill
\end{document}


text:
Q: Django - translate clause "WHERE identity IN (SELECT identity ... GROUP BY identity)" to django orm I have such a schema: http://sqlfiddle.com/#!17/88c6a
It is simple variation on versioning model, where all versions of single entity have the same identity.
I have to find all records which used to have category = 2 in their history.
How can I reproduce such query in Django? (Or any alternative queries)
SELECT *
FROM some_table a
WHERE identity IN (SELECT identity
                   FROM some_table
                   WHERE category = 2
                   GROUP BY identity
) AND is_latest = true;

I tried to retrieve these identities in application
class SomeTableQueryset(QuerySet):
    def had_category_2(self):
        with connection.cursor() as cursor:
            cursor.execute("""
SELECT identity
FROM some_table
WHERE category = 2
GROUP BY identity;
            """)
        valid_identities = [i[0] for i in cursor.fetchall()]

and filter queryset by
        qs = qs.filter(identity__in=valid_identities)

But such approach has several cons:

*

*it's not lazy, so query will be executed as soon as had_category_2 is
called

*it's very slow for obvious reasons

So, what can I do?

A: I think this can help you:
qs
.filter(
    identity__in=Subquery(
        qs
        .filter(category=2)
        .distinct('identity')
        .values('identity')
    )
)


text: Q: Is there a platform agnostic HTML5 map service? I have a Blazor combined client/server side app that uses HTML5 geolocation to return the user device latitude/longitude. I'd like to be able to provide the general "area" the user is in - a bit of a confirmation to the user the thing is working; and someday potentially enable the user to get lat/long for other locations as well. I have not been able to find a native HTML5 map service to go along with its geolocation capabilities, and in fact nearly every search leads to how to connect to Google Maps. I'm using Blazor, though, because I want the app to run and function on essentially every browser, so want to avoid Google Maps or Apple Maps, etc. I also checked quick on GitHub for potential API solutions but didn't see any. Ideas? Thanks!


text:
Q: Помогите пожалуйста, нужно перевернуть число _asm
    {
        mov k, 32
        xor ecx, ecx
    m1:
        mov eax, x
        mov s, 0
        mov ebx, 1
        cmp ecx, k
        je ex1
    v1:
        cmp s, ecx
        je vex1
        shl ebx, 1
        inc s
        jmp v1
    vex1:
//      shl ebx, ecx
        and eax, ebx
        cmp eax, 1
        jnz a1
        mov edx, 32
        sub edx, ecx
        dec edx
        mov s, 0
        mov eax, 1
    v2 :
        cmp s, edx
        je vex2
        shl eax, 1
        inc s
        jmp v2
    vex2 :
//      shl 1, 32 - ecx - 1
        or z, eax
    a1:
        inc ecx
        jmp m1
    ex1:
    }

// Необходимо перевернуть число x со всеми его нулями. Получить число в z.

A: Если без изысков и оптимизаций:
var
  u: DWord;
begin
  u := $80050001;

  asm
    push ebx
    mov edx, u
    mov eax, edx
    mov ecx, 31
  @@cycle:
    shl eax, 1
    shr edx, 1
    mov ebx, edx
    and ebx, 1
    or eax, ebx
    loop @@cycle
    mov u, eax
    pop ebx
  end;

  memo1.lines.Add(u.ToHexString); //  8000A001

end;

A: mov eax, X
mov ecx, 32
@@: shr eax, 1
rcl Z, 1
loop @b


text:
Q: Add Space in the XSLT V 1.0 I have two selects statements in the XSLT file.  What I'm trying to accomplish is to add a space in the output of the select statement.
For example, the following code:
<xsl:value-of select="translate(CAudioFile/CRI/PrivateData/PrivateData/DictionaryEntry[Key='CD1']/Value, ',',';')" />

returns this output:

9702195481; 31201(CCC AGENT)

I want to add a space right before the opening parenthesis.  So the output would be:

9702195481; 31201 (CCC AGENT)

I tried to use the "translate" function but it only allows two inputs.
The second select statement:
<xsl:for-each select="/CAudioFile/Agent/GroupsList/int"><xsl:value-of select="@name"/></xsl:for-each>

returns

53115(ABCDE City IIM)

I would like to add a space before the first parenthesis.  So the output is:

53115 (ABCDE City IIM)

Any suggestions?
Thank you
EDIT:
When I use the following code, it works 99% of the time and it gives me the output I want:
<xsl:variable name="cd1"    select="CAudioFile/CRI/PrivateData/PrivateData/DictionaryEntry[Key='CD1']/Value" />
<xsl:value-of select="translate(substring-before($cd1, '('), ',', ';')"/>
<xsl:text> (</xsl:text>
<xsl:value-of select="substring-after($cd1, '(')"/>
<xsl:text>, </xsl:text>

The output is:

9702195481; 31201 (CCC AGENT)

However, there're times that the code will return a slightly different output:

9286136438; 31172 (GCG Agent), 18887113613

I want this code to replace EVERY comma with semicolon, the output from this string looks like this:

9286136438; 31172 (GCG Agent); 18887113613

This way I can keep them under one column.
Thank you so much for your help.

A: You can't use translate to replace one character with two. Try it this way:
<xsl:variable name="value" select="CAudioFile/CRI/PrivateData/PrivateData/DictionaryEntry[Key='CD1']/Value" />

<xsl:value-of select="translate(substring-before($value, '('), ',', ';')"/>
<xsl:text> (</xsl:text>
<xsl:value-of select="substring-after($value, '(')"/>

or, if you prefer:
<xsl:value-of select="concat(translate(substring-before($value, '('), ',', ';'), ' (', substring-after($value, '('))"/>

A: Placing your value in a variable so it will be easier to reuse:
<xsl:variable name="string"
              select="translate(CAudioFile/CRI/PrivateData/PrivateData/DictionaryEntry[Key='CD1']/Value, ',',';')" />

You can use concat() and substring() functions:
concat( substring-before($string, '('), ' (', substring-after($string, '(') )

The ( can be used as a delimiter for the substring functions if it appears not more than once. This works in XSLT 1.0 or +.


text:
Q: Calculate the number of working days between two dates by exiling the weekends and specific holidays with python I have a holidays' list stored in an excel file. I would like to calculate the number of working days between two dates (date_1 and date_2) by ignoring the holidays stored in my excel file.
I tried np.busday_count but I do not know how to include my holiday file. This is my code:
claim=pd.read_excel("claim.xlsx")
Holydays=pd.read_excel("Holidays.xlsx")
claim.columns

claim["Resolved"] = pd.to_datetime(claim["Resolved"]).dt.strftime('%Y-%m-%d')
claim["Received_date"] = pd.to_datetime(claim["Received_date"]).dt.strftime('%Y-%m-%d')

#Je définie mes dates
date_1=claim["Received_date"]
date_2=claim["Resolved"]

#Calcul du nombre de jours entre la date et la date de résolution du dossier
claim["nb_jours"] = np.busday_count(date_1, date_2)

A: This should do the trick:
import numpy as np

maskcal=np.busdaycalendar(
    holidays=[
         '2019-12-24',
         '2020-01-01',
         '2020-01-06',
         '2020-01-10'
                     ])

diff_days=np.busday_count(
      '2019-12-20', '2020-01-20',
         busdaycal=maskcal
)

Output:
17

The np.busdaycalendar is comprehensive to weekends (i.e. Saturday-Sunday). You just need to read your excel file, and format it into list of dates of datetime-readable format.


text:
Q: Remove duplicate array elements using pointer arithmetic This is algorithm for removing duplicate elements from array:
#include <stdio.h>
int main() {
  int i, n = 5, j, k, arr[5] = {1, 2, 1, 2, 4};
  for (i = 0; i < n; i++) {
    for (j = i + 1; j < n; j++) {
      if (arr[i] == arr[j]) {
        for (k = j; k < n - 1; k++) {
          arr[k] = arr[k + 1];
        }
        n--;
        j--;
      }
    }
  }
  for (i = 0; i < n; i++)
    printf("%d ", arr[i]);
  return 0;
}

How could this be written with pointer arithmetic?
I need something like this:
int *p=arr;
while(p<arr+n){
    p++;
}

A: this is a very expensive way to do things. A much cheaper way would be to use a linked list or binary tree structure instead of arrays, but if you insist on using arrays, your question is answered on this link:
https://engineeringstudentshub.wordpress.com/c-programs-for-u/array_programs/4-remove-duplicate-elements-in-an-array-using-c-program/
I hope that helps


text:
Q: Where can I find my java installation when where java gives nothing? It's definitely installed, I can run Minecraft. But I'm trying to run a .jar file and Windows 11 is asking "How do you want to open the file?" And java compiler doesn't show up. btw I've treid where java, it said java didn't exist on the computer
UPDATE: I solved the problem but not the issue, there were some mods that were incompatible with eachother

A: You could try to find it out via printing your PATH.
On Windows: Open the command line via
Start -> CMD
Paste in
echo %PATH%

There you should be able to find the java path. Otherwise try to search for JRE.
By the way it is not always 100% sure that you have the java runtime and java compiler installed.
JRE = Java Runtime Environment for executing .jar
JDK = Java Development Kit for compiling java files and creating .jar files


text:
Q: Google App Script Sidebar Turns Blank from onclick Code.gs
function showSidebar() {
  var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setTitle('Procard Tracking');
  SpreadsheetApp.getUi().showSidebar(ui);
}

Sidebar.html

Instructions

Fill out the spreadsheet receipt information before filling out this section.

<form class="form-style-7">

    Statement Date
    <input id ="statementdate" type="date" name="statment_date">

    CardHolder
    <select id="cardholders" name="cardholders">

    </select>

    Prepared By
    <input id="prepared_by"type="text" name="prepared_by" maxlength="100">
    If different from CardHolder

    Total Activity
    <input id="totalactivity" type="text" name="total_activity" maxlength="100">

    <input id="submit_button" type="submit" value="Submit" onclick="submitForm()">
    <progress id="progress_bar" style="display: none; margin: auto;"></progress>

Ready to Print

Go to File -> Print

(In the top left corner)

</form>

This all used to work perfectly a weeek ago and I didn't touch it until these appeared. The input type date showed a dropdown calendar, and submit button worked and hide and showed html elements fine. This was without having to set the sandboxmode. However now the statement_date input which is of type date does not show a dropdown calendar anymore. Unless I set the sandboxmode of the sidebar to IFRAME. Which is fine but then when the submit button is clicked the whole sidebar goes blank and has no html what so ever inside of it what so ever. However the javascript still gets runs fine just the sidebar becomes blank.

A: You're submitting to an empty page, that's why it's getting all blank, disable submit button with the code below and have you're own code handle the submit:
$('form button').on("click",function(e){
    e.preventDefault;
});

And use the IFRAME, it's much better (unless you want to send files to the server).


text:
Q: Selected Content is not displaying in the textbox Using VB.Net
Windows application
Form (Gridview and Textbox)
GridView1
ID Name

001 Rajan
002 Sajan
103 Prathev
104 vijayan
....

Conditon
When i clicked the up and down arrow (keyboard) in the Gridview1 (id or name row), then selected cell should display in the textbox and also when i enter some numbers means, that entered number should appear in the textbox and
also entered related ID or name should display in the gridview1
For Example
If i press 0, that 0 should display in the textbox, and gridview display like
ID Name

001 Rajan
002 Sajan

If i press 1, that 1 should display in the textbox, and gridview display like
ID Name

103 Prathev
104 vijayan

Tried Code for displyaing in the girdview
Dim conObjects As New ConnectionObjects
        conObjects.OpenConnection()
        Dim cmd As SqlCommand
        Dim ds As DataSet
        Dim ada As SqlDataAdapter
        cmd = New SqlCommand("Select ID, Name from employee where id like '%" & textbox1.Text & "%' ", conObjects.myConnection)
        ada = New SqlDataAdapter(cmd)
        ds = New DataSet
        ada.Fill(ds, "employee")
        gridview1.DataSource = ds.Tables(0)

Expected answer
-> In which gridview event i have to write a code
-> If i press up or down arrow, then selected cell should display in the textbox
-> If i enter some number or characters, that numbers or character should display in the textbox and selected related values should display in the gridview

How to do this.
Need help or vb.net code.

A: You can bind your dataSource to dataGridview and TextBoxes.
Here is sample code (Add dataGridView1, TextBox1,TextBox2):
 Private Sub YourForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim dt As New DataTable
        dt.Columns.Add("No")
        dt.Columns.Add("Name")

        dt.Rows.Add(1, "A")
        dt.Rows.Add(2, "B")

        DataGridView1.DataSource = dt

        TextBox1.DataBindings.Add("Text", dt, "No")
        TextBox2.DataBindings.Add("Text", dt, "Name")
    End Sub


text:
Q: Soap Request with XML Schema Parameter can you help me out? I'm new to SOAP, and I don't know what to send as parameter here <xsd:schema>schema</xsd:schema>xml
<SendOrder xmlns="http://wMobSrv/wMobService">
      <dsOrder>
        <xsd:schema>schema</xsd:schema>xml</dsOrder>
      <dsArticles>
        <xsd:schema>schema</xsd:schema>xml</dsArticles>
      <dsResult>
        <xsd:schema>schema</xsd:schema>xml</dsResult>
      <Database>string</Database>
</SendOrder>

Response:
["xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd": "http://www.w3.org/2001/XMLSchema", "xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/"]

["xmlns": "http://wMobSrv/wMobService"]

["xmlns:msdata": "urn:schemas-microsoft-com:xml-msdata", "id": "NewDataSet", "xmlns": "", "xmlns:xs": "http://www.w3.org/2001/XMLSchema"]
["msdata:IsDataSet": "true", "name": "NewDataSet", "msdata:UseCurrentLocale": "true"]
[:]
["minOccurs": "0", "maxOccurs": "unbounded"]
["name": "Doc"]

["minOccurs": "0", "name": "Code_OE", "type": "xs:string"]
["minOccurs": "0", "name": "Code_Doc", "type": "xs:string"]
["minOccurs": "0", "name": "Num_Doc", "type": "xs:string"]
["minOccurs": "0", "name": "Status", "type": "xs:string"]
["minOccurs": "0", "name": "Description", "type": "xs:string"]
["xmlns:msdata": "urn:schemas-microsoft-com:xml-msdata", "xmlns:diffgr": "urn:schemas-microsoft-com:xml-diffgram-v1"]
["xmlns": ""]
["msdata:rowOrder": "0", "diffgr:id": "Doc1", "diffgr:hasChanges": "inserted"]

A: I had the same problem. You need to look with Google to SOAP with Datasets. The schema is one part in the parameter and the actual data goes in a diffgram.


text:
Q: how to hide and unhinde the textview on scolling up and down I am making an app in which I am using the Coordinator layout, inside that I am using two textviews and two floatingactionbuttons. When I scrolls upside then when one floatingactionbutton goes out of view both the buttons hides but the textview will not hide.
Sample Images shown below about that I have explained above.
View when the floating action button is inside the view
View when both textivew and floatingactionbuttons are out of view
Here is mycode for the Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.trueblueoperator.samplescrolling.ScrollingActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="192dp"
            android:scaleType="centerCrop"
            android:src="@drawable/image"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_scrolling" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/dislike"
    app:layout_anchor="@id/app_bar"
    app:layout_anchorGravity="right|center_vertical" />

<TextView
    android:id="@+id/dislikes"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="5dp"
    android:paddingBottom="5dp"
    android:paddingTop="5dp"
    android:paddingRight="70dp"
    android:textSize="20dp"
    android:background="@drawable/rounded_corner"
    android:text="10"
    android:focusable="true"
    app:layout_anchor="@id/app_bar"
    app:layout_anchorGravity="right|center_vertical"
    />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/like"
    app:layout_anchor="@id/app_bar"
    app:layout_anchorGravity="right|bottom" />

<TextView
    android:id="@+id/likes"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="5dp"
    android:paddingBottom="5dp"
    android:paddingTop="5dp"
    android:paddingRight="70dp"
    android:textSize="20dp"
    android:focusable="true"
    android:background="@drawable/rounded_corner"
    android:text="100"
    app:layout_anchor="@id/app_bar"
    app:layout_anchorGravity="right|bottom"
    />

</android.support.design.widget.CoordinatorLayout>

A: Add Offset Changed Listener on you AppBarLayout
mAppBarLayout.addOnOffsetChangedListener(this);

Override the method enter code here
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i) {

    if (Math.abs(i) >= (appBarLayout.getTotalScrollRange())) {
        // Make your TextView Visible here
    } else {
        // Make your TextView Invisible here
    }

}

A: I'm not sure that you can do it like this. I resolved this way:
In activity add this listener.
mAppBarLayout = (AppBarLayout)findViewById(R.id.appbar);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.COLLAPSED) {
                    hideTextView();
                } else {
                    showTextView();
                }
            }
        });

where AppBarStateChangeListener is
public abstract class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener {

public enum State {
    EXPANDED,
    COLLAPSED,
    IDLE
}

private State mCurrentState = State.IDLE;

@Override
public final void onOffsetChanged(AppBarLayout appBarLayout, int i) {
    if (i == 0) {
        if (mCurrentState != State.EXPANDED) {
            onStateChanged(appBarLayout, State.EXPANDED);
        }
        mCurrentState = State.EXPANDED;
    } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
        if (mCurrentState != State.COLLAPSED) {
            onStateChanged(appBarLayout, State.COLLAPSED);
        }
        mCurrentState = State.COLLAPSED;
    } else {
        if (mCurrentState != State.IDLE) {
            onStateChanged(appBarLayout, State.IDLE);
        }
        mCurrentState = State.IDLE;
    }
}

public abstract void onStateChanged(AppBarLayout appBarLayout, State state);

}

A: You can add CoordinatorLayout.Behavior to the TextView you want to hide on scrolling.
Take a look at my answer, the explanation is for FAB but you can easily modify it for TextView
https://stackoverflow.com/a/34028178/557179


text:
Q: Error While Adding New Provider in ionic When i try to add a new provider to my existing ionic project it throws
The generate command is only available for projects t
hat use ionic-angular >= 3.0.0

I tried the following command to upgrade but it doesn't worked out
>npm install --save ionic-angular

My Ionic Version is 3.2.0
My Package.json looks
"dependencies": {
    "@angular/common": "2.4.8",
    "@angular/compiler": "2.4.8",
    "@angular/compiler-cli": "2.4.8",
    "@angular/core": "2.4.8",
    "@angular/forms": "2.4.8",
    "@angular/http": "2.4.8",
    "@angular/platform-browser": "2.4.8",
    "@angular/platform-browser-dynamic": "2.4.8",
    "@angular/platform-server": "2.4.8",
    "@angular/tsc-wrapped": "~0.5.2",
    "@ionic/storage": "2.0.0",
    "ionic-angular": "^2.3.0",
    "ionic-native": "2.4.1",
    "ionicons": "3.0.0",
    "lodash-es": "^4.17.4",
    "node-uuid": "^1.4.7",
    "rxjs": "5.0.1",
    "sw-toolbox": "3.4.0",
    "uuid": "^2.0.2",
    "zone.js": "0.7.2"
  }


text:
Q: Is it better to store images in a BLOB or just the URL?
Possible Duplicate:
Files - in the database or not?

I was wondering if there's any good reason to still use blob fields in a database. A couple of years ago I worked with a DB with a bunch of images in it, the DB was very slow and I couldn't see any good reason to keep the images inside the DB, so I got the images out and stored the filenames instead.
Was this a smart move? What would you do in my place?

A: I'm a big fan of storing the "reference" copy of the image in the database -- from a managability/disaster recovery standpoint this is really the way to fly.
Now, you can still do lots of things to serve the image out of the filesystem for most applications so you are not putting that much pressure on the database server itself to do things it doesn't really want to do.

A: If you are working with linux, storing the images in the filesystem and not in the database has significant better performance, see this excerpt of Brad Ediger's book Advanced Rails.

A: I'm not much of a fan of storing images in the database.  In a small app with a few users, it seems like an easy solution, but as you start to scale, it makes things more difficult.
My preference is to start out storing images in a folder on the web server, but keep the path in an easily accessible configuration so that when I need to, I can quickly move them to their own dedicated, optimized image server.  Later, I might want to move them somewhere else (think S3 or Akamai) in the same way.  All of that is much more complicated if I have to change out code that has been expecting to read them from the database.

A:
Was this a smart move?

If it was a smart move or not, it depends of your specific case:
If the file location is directly affecting any url structure or if you're storing full file addresses in the database (bad), I can say it was a bad move since you will have trouble in case somebody move or rename some directory.
But as But if your application is built in a way you simply have to point the files directory and the file access logic is dynamic, you made a smart move for the following reasons:

*

*With database storing, If there is need to serve a lot of images per
request, you will increase the response time of your application
since the files are going to be sent synchronously to the network.
Also you will add a little more processing to your server.

*File storing is usually cheaper than database storage.

*With file storing (unless there are restrictions to image access:
only a determined user can access a given group of images), there's
no need of any processing to access images or any other kind of file.

*With database storage it's not possible to access your files using
FTP (pretty obvious, but it's good to remember).

*Database file storage will slow down and / or clutter your database
periodic backups.

What would you do in my place?

I would keep that decision unless a contrary dominant factor appears.
Hope that helps.

A: As you can tell from the other answers, this is a big "It Depends." Some other factors might be if you are paying for hosting, do they charge more for file storage or database storage. File storage is typically cheaper, especially for cloud services.
If you are self hosted and using SQL Server, the upcoming version, codename Denali, will extend FILESTREAM to allow access via both TSQL and file system. It also will make sure these stay in sync. You can access, update, delete from either side and it will keep everything organized.
Do your research and find out what's important to you and pick the direction based on that choice.

A: The reason to use BLOBs is quite simply manageability - you have exactly one method to back and restore up the database, you can easily do incremental backups, there is zero risk of the image and its meta data stored in DB tables ever getting out of sync, you also have one programming interface to run queries or load/save images, so you don't need to give remote clients filesystem access and you know the same GRANTs will apply to images and their associated data. Plus you have one method of storage management (e.g. in Oracle you might put everything on ASM and use Oracle as your LVM for everything).
Another application is to mix relational data with serialized objects (a BLOB can be any binary, it doesn't need to be images). Or you can run a query against relation data and bytes x-y in the BLOB, which might be a file header for example. The applications are in fact endless.
If accessing a BLOB was slower than accessing your filesystem then it is highly likely your database was misconfigured.

A: I don't use blobs -- mostly from a backup and restore perspective, as I don't want the blob data slowing down my backups.
I don't store a full URL, however ... I only store the filepath below a certain point, and build the path as I have more than one way in which people & programs access my files  (FTP, HTTP, local directory, NFS mounted directories).
... of course, I likely deal with more & larger images than most people ... one of my datasets gets about 700GB of images (compressed) per day.  But even the thumbnails for those images, I still store externally.


text:
Q: Stored procedures and unit testing Does anybody know of a framework (or methodology) to unit test stored procedures just using SQL and be able to produce a reasonable report as to what has passed and what has failed (something similar to CPPUnit)?

A: MyTAP will probably be what you are looking for, you can find it in Github
it describes itself as: 'a unit testing framework for MySQL 5.x written using fuctions and procedures. It includes a collection of TAP-emitting assertion functions, as well as the ability to integrate with other TAP-emitting test frameworks.'
MyTAP is now hosted at [https://github.com/hepabolu/mytap][1]

A: Maybe you want to try STK/Unit, which is written in pure SQL and supports the ideas of Test Case and Test Suite. Also, supports expectations.
http://stk.wikidot.com/stk-unit


text:
Q: How to locate a cell value that ends in "net" and delete row in Excel VBA I have this procedure that is looking for any cell in Col D where the value ends in "net" then it will delete the entire row/rows. But it does not delete all of the rows where the value ends in "net". I am out of ideas.
Sub DeleteRows_net()
Application.ScreenUpdating = False
Dim rng As Range

For Each rng In Range("D4:D2700")

If InStr(1, rng.Value, "net") > 0 Then
rng.EntireRow.Delete
End If

Next rng

End Sub

A: It is so common mistake... When you loop to delete you have to start from last element taking direction to first.  Change looping into:
Dim i%
For i=2700 to 4 Step -1
    If InStr(1, Cells(i, "D").Value, "net") > 0 Then
        Cells(i, "D").EntireRow.Delete
    End If
Next i

By the way... Do not forget to place Application.ScreenUpdating = True somewhere before end of procedure!


text:
Q: Make GNU parallel return the server name in the sshlogin file I run commands on several remote servers using gnu parallel with the help of a sshlogin file:
seq 3 | parallel --sshloginfile hostfile "/etc/sin/bin/daemon status"

The output looks something like:
hostfile: RUNNING, pid 1234567

And the file hostfile contains a list of servers like below?
server1.finehost.prod
server2.finehost.prod
server3.finehost.prod

My question is:
Is there any way to show the hostnames so that the output looks like that:
server1.finehost.prod: RUNNING, pid 12345
server2.finehost.prod: RUNNING, pid 666
server3.finehost.prod: STOPPED

Thanks ;)

Note: I don't have permissions to install any extra tool on the servers such as pssh or similars.

A: It is unclear what you use the seq 3 for. If that is not needed then this will work:
parallel --sshloginfile hostfile --tag --nonall "/etc/sin/bin/daemon status"


text:
Q: Resource dictionary not found in WPF prism user control I have the following project structure:

When I tried to add Resoucse dictionary inside my user control FloorplanHierarchy I am getting file not found error:
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source=".../UserControls/UserControlResources/LookUpEditTemplate.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

LookUpEditTemplate.xaml is inside the folder UserControlResources. Please help.

A: Remove UserControls in the source because UserControlResources and FloorplanHierarchy both are in the same folder.
So changing this:
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source=".../UserControls/UserControlResources/LookUpEditTemplate.xaml" />
</ResourceDictionary.MergedDictionaries>

To this:
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="../UserControlResources/LookUpEditTemplate.xaml"/>
</ResourceDictionary.MergedDictionaries>

Should works.


text: Q: Can I use the JWT subject as a UID? Can the sub field of a JSON Web Token be used as a UID for identifying a user inside my app or do I have to use the username that is generated by my database (Couchbase) which looks like this: accounts.google.com_114...749 as a UID?


text:
Q: How to backup Kubuntu 15.04 config/settings? I would like to backup all my settings for the plasma desktop, dolphin, kate etc. I am working with kubuntu 15.04. How can I do this?
Reason is: just a few moments ago my plasmashell crashed (black screen, also after reboot) and I had to reset ~/.kde ~/.chache ~/.config/plasma* in order to fix it. So I lost some of my settings, I want to prevent this from happening again by saving all the settings somewhere for me to recover. Also handy after een clean install where I delete my /home folder.
I already looked up a few tools:
-Kup backup: http://kde-apps.org/content/show.php?action=content&content=147465
-plasmabac: https://linuxtidbits.wordpress.com/2009/11/04/plasmabac-when-plasma-solidifys/
But I am not sure if this will work, as I am very new to Linux.


text:
Q: JS object/JSON key wildcard I have an object that is evaluated from JSON that looks like this:
{
    "foo %s": "bar %s",
    "Hello %s world %s.": "We have multiple %s %s."
}

Using this object and the following inputs, I am trying to achieve something like this:

*

*foo bar -> matches foo %s -> bar bar

*Hello foo world bar. -> matches Hello %s world %s. -> We have multiple foo bar
So far I have the following code which works for one %s and only if it is surrounded by spaces.
let str = "input here";
let a = {
        "foo %s": "bar %s",
        "Hello %s world %s.": "We have multiple %s %s."
    },
    p = str.split(" "),
    result;
for (let j in p) { // loop indices
    let pp = p.map(u => u); // create local array
    pp[j] = "%s"; //replace index with %s
    if (a[pp.join(" ")]) { // check if this is in the object
        result = a[pp.join(" ")].replace("%s", p[j]); // join the array and replace %s from the result
        break;
    }
}

Any ideas or suggestions?

A: You could convert your object to regular expressions and then execute them in a call to String.prototype.replace.
Example with a single, defined, replacement operation:
console.log('Hello foo world bar.'.replace(/^Hello (.*?) world (.*?) bar\.$/, 'We have multiple $1 $2.'))
// Output: We have multiple foo bar.

Here we basically match against the whole string - if it matches the pattern, the whole contents will get replaced.
As you can see, to achieve this, you would need to transform the "Hello %s world %s." into /^Hello (.*?) world (.*?)\.$/ (with the (.*?) defining a non-greedy capture group containing any characters) and the "We have multiple %s %s." into "We have multiple $1 $2." (with $x referring to the x-th capture group's contents).
So you could have a function like this:

function replaceTemplates (str, templates) {
  // This helper function escapes any characters which would have a special
  // meaning in the regexp otherwise. $& is the match as a whole, so it replaces
  // each of these characters with themselves prepended by a backlash.
  const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

  for (const [template, replacement] of Object.entries(templates)) {
    // We create a regexp from the template, replacing every %s with (.*?), wrapping it
    // in ^ and $ (start/end of string) and escaping all the other special characters.
    const re = new RegExp('^' + escapeRegExp(template).replace(/%s/g, '(.*?)') + '$')

    if (re.test(str)) {
      // To get the correct string for the right side of the string replace method,
      // we have to replace each %s in the replacement string by $1, $2, $3 etc. and
      // also replace single $ signs by $$ because the $ has a special meaning as shown
      // above, and then we can call the actual replace and return the result. But since
      // a $ in the replacement has to be escaped as just explained, we have to write
      // FOUR $ signs to get TWO at the end.
      let i = 1 // This is used as counter in the following replacing operations for $x
      const reReplacement = replacement
        .replace(/\$/g, '$$$$')
        .replace(/%s/g, () => '$' + i++) // By using a function, we can make $x dynamic

      return str.replace(re, reReplacement)
    }
  }

  return str
}

const templates = {
  'foo %s': 'bar %s',
  'Hello %s world %s.': 'We have multiple %s %s.'
}

console.log(replaceTemplates('foo bar', templates)) // Output: bar bar
console.log(replaceTemplates('Hello foo world bar.', templates)) // Output: We have multiple foo bar.

By the way: If pp = p.map(u => u) is supposed to create a copy, I'd suggest pp = p.slice() or just pp = [...p] instead.


text:
Q: when update state in cypress Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement I'm using cypress to testting my React project, when click button state be updated, but i received error:
(uncaught exception)Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

I know some role convention coding with this error but i can't fix it.
My source:
const Component: React.FC = (): JSX.Element => {
const [state, setState] = useState(true)
cosnt onClick = () => setState(false);

return <button onClick={onClick}></button>
}

spec.cy
describe('App', () => {
  it('Should be mount perpectly', () => {
    cy.mount(<Component />);
    cy.get('button').click();
  });
});

Must be I', missing something else cause me do not using state in my testing cypress environment
I'm using cypress to testting my React project, when click button state be updated, but i received error:
(uncaught exception)Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

I know some role convention coding with this error but i can't fix it.
My source:
const Component: React.FC = (): JSX.Element => {
const [state, setState] = useState(true)
cosnt onClick = () => setState(false);

return <button onClick={onClick}></button>
}

spec.cy
describe('App', () => {
  it('Should be mount perpectly', () => {
    cy.mount(<Component />);
    cy.get('button').click();
  });
});

Must be I', missing something else cause me do not using state in my testing cypress environment


text:
Q: Declaring pointer to object as parameter to class member object I'm trying to control a Dynamixel motor using the C++ SDK and I would like to do this from a class if possible. I need two pointers to an object and one other object to be class member variables. I found How can I initialize C++ object member variables in the constructor? but while it discusses both pointers to objects and objects themselves I need a combination. The three members I need look like this (taken from the sample code):
dynamixel::PortHandler *portHandler = dynamixel::PortHandler::getPortHandler(DEVICENAME);

dynamixel::PacketHandler *packetHandler = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION);

dynamixel::GroupSyncWrite groupSyncWrite(portHandler, packetHandler, ADDR_MX_GOAL_POSITION, LEN_MX_GOAL_POSITION);

The issue is the GroupSyncWrite object depends on the pointers above it and must be declared after the first two are, so something like this:
Foo::Foo() : groupSyncWrite(...)
{
    porthandler = dynamixel::PortHandler::getPortHandler(DEVICENAME);
    packetHandler = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION);
}

doesn't seem to work since the groupSyncWrite constructor takes porthandler and packethandler as parameters.
If anyone knows how to do this or if it's not possible to implement it like this I would appreciate any help.
EDIT:
The question in a nutshell is how to initialize two object pointers in a constructor prior to an object initialization in the same constructor.
There is an object foo that requires two pointers to objects as parameters, bar *one, and baz *two. The object and pointers are all members of my class and need to be initialized in the constructor of the class. The problem was I did not know how to initialize the pointers in the format
Class::Class() : one() {}

such as can be done with non-pointer objects. @Matthieu's answer worked perfectly.

A: Initialize them properly and in order in the initialization list from the constructor:
Foo::Foo()
 : porthandler(dynamixel::PortHandler::getPortHandler(DEVICENAME)),
 packetHandler(dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION)),
 groupSyncWrite(porthandler, packetHandler)
{
}

Make sure you have the proper order when declaring the member variables of your class (porthandler, then packetHandler and finally groupSyncWrite).


text:
Q: R curvefit [REAT]: What are the equations of the nonlinear functions? I am trying to fit curves to my data with the curvefit() function of the REAT package.
The results look good and give me a table like this:
                       a           b Std. Error a Std. Error b  t value a t value b
Linear      -1494.108840 166.1867222  523.5387976  30.50266009 -2.8538646  5.448270
Power           0.425234   2.7725836    0.4456762   0.36780235 -0.8332776  7.538243
Exponential    32.008316   0.2022666    0.4492831   0.02617634  7.7145024  7.727078
Logistic        7.076363  -0.4071710    1.6305232   0.09499830  4.3399340 -4.286087

              Pr(>|t|) a   Pr(>|t|) b R squared Adj. R squared  F value       Pr(>F)
Linear      1.275234e-02 8.582766e-05 0.6795139      0.6566221 29.68364 8.582766e-05
Power       4.186780e-01 2.716813e-06 0.8023300      0.7882107 56.82511 2.716813e-06
Exponential 2.085140e-06 2.046447e-06 0.8100606      0.7964935 59.70773 2.046447e-06
Logistic    6.790587e-04 7.535634e-04 0.5675080      0.5366157 18.37054 7.535634e-04

What I would like to do is to extract the functional equations of the curves.
For linear fit, this is probably
y = ax + b.
But which functions are used for the other three?
In the function code I found
lm (log10(y) ~ log10(x)) for power,
lm (log(y) ~ x) for exponential and
lm ( (log((y.max-y)/y)) ~ x) for logistic.
Probably due to my faded maths skills, I don't know how to derive a function including the paramters a and b, just like the one for linear regression.
Therefore, any help is appreciated.

A: Tried around a lot and found out this:
Linear: y = b*x + a
Power:  y = a*x^b
Exponential: y = a*exp(b*x)
I am still missing the logistic function though, if someone knows it.


text:
Q: What is a "path_expression" in BigQuery BigQuery describes a path_expression in the Syntax page as follows:

A path expression describes how to navigate to an object in a graph of objects and generally follows this structure...

Examples:
foo.bar
foo.bar/25
foo/bar:25
foo/bar/25-31
/foo/bar
/25/foo/bar

What are some actual examples of a Path Expression with a valid table, for example in a CTE? My thinking was that a path expression would be something that explicitly qualifies a field or struct sub-field, such as:
myTable.myField.mySubfield

But from the above syntax, which allows for:
/:-

I'm not exactly sure what it is or how it would be used. Could someone show a real-world example of how a path expression would be used?

A: Path expressions describe where to search for (or store) data. Consider this example from the docs:
#legacySQL
SELECT
  weight_pounds, state, year, gestation_weeks
FROM
  [bigquery-public-data:samples.natality]
ORDER BY
  weight_pounds DESC
LIMIT
  10;

In this example, the portion [bigquery-public-data:samples.natality] is the path_expression.
It is saying to look at the natality table in the samples database in the bigquery-public-data project.

But from the above syntax, which allows for: /:-

This would actually not be allowed, as a path_expression.
This example would be parsed as:
/:-

{first_part}/{subsequent_part}:{subsequent_part}

{{ unquoted_identifier | quoted_identifier }} /
{{ unquoted_identifier | quoted_identifier | number }} :
{{ unquoted_identifier | quoted_identifier | number }}

An unquoted_identifier must at least begin with a letter or an underscore. A quoted_identifier can contain any character, but cannot be empty. The empty string therefore cannot be considered an unquoted_identifier, quoted_identifier, or number, so this expression is invalid (and is invalid in 3 positions).
A possible minimal path_expression could be something like:
a:b.c

meaning look in the c table in the b database in the a project.

A: I can be wrong, but I think you are confusing Path Expression (as it is defined in referenced documentation) with something like (for example) JSONPath.
In my mind, the the former is just terminology that introduced in order to have consistent reference within the documentation, while later (obviously) is query language for JSON, similar to XPath for XML, etc.
So, if you would asked for something like JSONPath use - I bet you would get tones of usage examples, but asking about Path Expression use has not much chances to gather answers even having hefty bounty as it is ONLY used in that documentation.


text:
Q: problemas em usar o inputFile no JSF 2.1 Eu estou usando a versão JSF 2.1 com esse artefato abaixo;
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.faces</artifactId>
    <version>2.1.21</version>
    <scope>compile</scope>
</dependency>

E preciso usar o inputFile como mostra a baixo;
        <p:outputLabel value="Imagem do Produto" />
        <h:inputFile value="#{cadastroProdutoBean.arquivo}" />

Eu sei que é necessário usar a tag seguintes abaixo;
xmlns:i="http://xmlns.jcp.org/jsf/html"

sendo que não reconheci, o que será que está errado? O que é preciso para eu fazer o inputFile ser reconhecido na pagina?
Atualização da postagem///////////////////////////////////////////////////////
Estou com uma enorme dificuldade para habilitar o inputFile do JSF, pois eu soube que o inputFile somente funciona no projeto JSF da versão 2.2.
Então resolvi criar o projeto do Zero e conseguir converter para a versão mais recente como podem ver;

Mais ainda tenho problemas e preciso de ajuda.

A: Amigo,
Ao incluir a linha xmlns:**i**="http://xmlns.jcp.org/jsf/html" você nomeou esse pool de componentes com a letra i.
Sendo assim, tente utilizar o componente com a seguinte tag
<i:inputFile value="#{cadastroProdutoBean.arquivo}" />