text:
Q: Mvc Identity Longin ClaimsPrincipal value always null This is my Login controller
public class AccountController : BaseController
{
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
      var identity = new ClaimsIdentity(new[]
      {
         new Claim(ClaimTypes.Name, "Huang"),
         new Claim(ClaimTypes.NameIdentifier, user.Vaild.ToString()),
         new Claim(ClaimTypes.Email,"xxx@gmail.com"),
         new Claim(ClaimTypes.MobilePhone,"123456"),
      },DefaultAuthenticationTypes.ApplicationCookie);

  IdentityTool.Authentication(AuthenticationManager,identity,rememberMe:true);

     // userEmail and userPhone  always null and I got null exception
        var userEmail = CurrentUser.Email;
        var userPhone = CurrentUser.MobilePhone;

    return View(model);
   }
}

public class BaseController : Controller
{
    public AppUser CurrentUser
    {
        get { return new AppUser(this.User as System.Security.Claims.ClaimsPrincipal);}

    }
}

IdentityConfig
public class IdentityTool
{
 public static void Authentication(IAuthenticationManagerauthenticationManager, ClaimsIdentity identity, bool rememberMe)
     {
        if (rememberMe)
        {
            authenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = true,
                ExpiresUtc = DateTimeOffset.UtcNow.AddDays(14)
            }, identity);
        }
        else
        {
            authenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = false
            }, identity);
        }
    }
}

//Custom property
public class AppUser : ClaimsPrincipal
{
    public AppUser(ClaimsPrincipal principal) : base(principal)
    {
    }
    public string Email
    {
        get
        {
            return this.FindFirst(ClaimTypes.Email).Value;
        }
    }

    public string MobilePhone
    {
        get
        {
            return this.FindFirst(ClaimTypes.MobilePhone).Value;
        }
    }
 }

This is my  Startup
public void ConfigureAuth(IAppBuilder app)
{
    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType =DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {

            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    });
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

Then I got null exception on "CurrentUser.Email" and "CurrentUser.MobilePhone" always null. Please help me to fix it. I really appreciate. I ask many people but no one can fix it.If you have some suggest to modify some code.May helpful.Please let me know.blow picture is my exception detail. Sorry for some Chinese in the picture.^^
This is my exception detail hope help


text:
Q: Chropath is not visible/working in Salesforce The ChroPath extension in Chrome browser is not visible for Salesforce website where as it is working in other sites.
Chrome browser version: 83.0.4103.61
ChroPath version: 6.1.4
ChroPath in other sites - The ChroPath tab is visible

ChroPath in Salesforce: The ChroPath tab is not visible

It is working in the Salesforce VisualForce page but not on the Salesforce Aura components, Salesforce Lightning Web Components pages.
The extension is enabled and even it was working properly earlier in the Salesforce site. I have tried re-installing the extension and browser but it is not working in Salesforce website.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set an user agent and connection timeout for jsoup in android I was trying to extract some tweets from mobile.twitter.com in an android, and as a result I get a mixed html document. After some searches I realized that I need to set an user agent.
My aim is to set a default user agent which would work not only for me, but also for other users who would use my application.
Document doc = Jsoup.connect("https://mobile.twitter.com/").userAgent(...).get();

A: For those who might be interested there is an easy way for getting default user agent if you are on Android 2.1 or above.
There is a system property called http.agent, which can be used to retrieve the User-Agent string.
My code would then turn to:
String userAgent = System.getProperty("http.agent");
Document doc = Jsoup.connect("https://mobile.twitter.com/").userAgent(userAgent).get();


text:
Q: How to slice and join DataFrame values if a certain condition is met I have a df:
name         data
jack        1.2.3
xander        1.2

If there is a 2nd '.' in the data string, I want to drop it and everything after.
As of now I am doing:
df.loc[df['data'].str.count('.') == 2, 'data'] = df['data'].str.split('.')

which gives back
name           data
jack        [1,2,3]
xander          1.2

How can I edit the code above to join the resulting list on '.' for the first two elements only to result in this?
name           data
jack            1.2
xander          1.2

I am trying to do something like this but run into a whole slew of errors (the join either does not join and leaves the list intact or gives back Nan)
df.loc[df['data'].str.count('.') == 2, 'data'] =  '.'.join(df['data'].str.split('.')[:2])

If there is a better way to do this please let me know!

A: One way:
df['data'] = df['data'].str.split('.').str[:2].apply('.'.join)

Or use extract:
df['data'] = df['data'].str.extract('^([^\.]+\.[^\.]+)')

Output:
     name data
0    jack  1.2
1  xander  1.2


text:
Q: Cannot use commands and events together in discord bot Source, (Forgive my possible spaghetti code, I am not that good) I am trying to add commands on this old code that I made a while back and the commands through events work just fine but the actual proper commands do not work.
Please could I get some tips or help?
Here is the source https://repl.it/@DontSniffSugar/DiscordBot#main.py

A: The issue in your code is that you didn't process the commands. When overwriting the default on_message event you also have to process them.
@client.event
async def on_message(message):
    # ...
    await client.process_commands(message)

Also a small note for the future, don't post links to your code, the code should be in the question itself. Also you should enable some intents, if you don't what that is and how to enable them, take a look at the introduction
Reference:

*

*Bot.process_commands


text:
Q: Switching between Ubuntu Flavors Is Ubuntu 16.04 same as Lubuntu 16.04 or Elementary OS Loki with the desktop environments changed? Can I install Elementary OS Loki and 'switch' to Ubuntu just by installing the Unity desktop environment?
My question is different from this question where the asker only wanted to switch between the desktop environments. I specifically want to know if the underlying codebase and kernel is same between all these flavors.
And lastly, if I have Elementary OS installed, is it possible to get updates from the latest Ubuntu repository?


text:
Q: Select Ids which have both NULL and Value(NOT NULL) in another column How to select IDs, which have both NULL and NOT NULL value in different column of same table?
Table:
Col1   |   Col2
abc    |   NULL
abc    |   123
bcd    |   456
Result
Col1   |   Col2
abc    |   NULL
abc    |   123

A: Try this:
select Col1
from mytable
group by Col1
having count(case when col1 is null then 1 end) > 0 and
       count(case when col1 is not null then 1 end) > 0

This will select Col1 values being related to both NULL and NOT NULL col2 values.

A: I'm not sure what you are asking.
Do you want rows where the 2 fields in the same rows have the same value, whether NULL or not?
SELECT *
FROM SomeTable
WHERE EXISTS (SELECT col1 INTERSECT SELECT col2)

SQLFiddle example
Or otherwise if you want "where values exists in any row in another column"
SELECT col1 FROM SomeTable
INTERSECT
SELECT col2 FROM SomeTable

SQLFiddle take 2
Both of these work because INTERSECT compares internally using "IS" logic instead of "=". See Paul White (SQLKiwi) for more

A: You can use isnulll() function.
like this
where isnull(col1,0)=isnull(col2,0)

A: see,if you use identity column or use row_number in query then it is very easy
Declare @table table (id int identity(1,1)
,Col1 varchar(50),Col2 varchar(50))
insert into @table
values
('abc', NULL )
,('abc', '123')
,('bcd' ,'456')

select a.col1,a.col2
from @table A
inner join @table b on a.col1=b.col1 and a.id<>b.id

OR
;with CTE as
(
select a.col1,a.col2,row_number()over(order by col1) rn
from @table A
)
select a.col1,a.col2
from CTE A
inner join CTE b on a.col1=b.col1 and a.rn<>b.rn

A: declare @table table
(
  col1 nvarchar(10),
  col2 integer
 )
 insert into @table
 (col1)
 values
 ('abc')
insert into @table
 (col1,col2)
 values
  ('abc',123),
 ('bcd',456)
select col1,col2 from @table where col1 in
 (
 select col1
 from
 (
 select col1,
    sum(case when col2 is null then 1 else 0 end) as nulls,
    sum(case when col2 is not null then 1 else 0 end) as notnulls
  from @table
  group by col1
 )  s
 where  nulls <> 0 and notnulls <> 0
)


text:
Q: Jqgrid, call URL with parameters for Json return i have the following code on my aspx page:
jQuery("#listFondos").jqGrid({
    url: '/PorMyController/LoadGridData/',
    datatype: 'json',
    mtype: 'GET',
    colNames: ['col1', 'col2',...etc

Everything is working fine, but i'm wondering if is it possible to call the URL method sending some parameters. I know that by default, when you call the url method, jqgrid sends some parameters to control paging of the grid:
public ActionResult LoadGridData(string sidx, string sord, int page, int rows)

So, i want to add an extra parameter to make some filter on the data that is going to be loaded into the grid. For example i would like to have this:
public ActionResult LoadGridData(string sidx, string sord, int page, int rows, string filterId)

As i know, i don't need to specify the first 3 parameters, cause jqgrid does it by default, but how do i send the filterId parameter?

A: I solve the problem myself.
All that is needed to do is send the parameter as querystring on the url:
url: '/PorMyController/LoadGridData?filterId=123',...etc

The defaul parameters for paging will keep being sended, so you only have to specify the additional parameters.

A: You can specify a function instead of a named datatype for the datatype parameter.  Then in that function you can manually do a jQuery .ajax call with whatever parameters you want.  This thread has a good example:  here.  (Specifically the last answer).


text:
Q: Components appear on mouse hover I have created a swings application, and what I am trying to do is, to add some components to it on button click. I am able to do this, but the problem is that, these components only appear when I hover over them. How should I make them appear as soon as the button is clicked?
public TransferFrom() {
    count=1;
    setTitle("Transfer Form");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 924, 571);
    pane = new JPanel();
    pane.setBorder(new EmptyBorder(5, 5, 5, 5));
    pane.setBackground(Color.decode("#5388BE"));
    setContentPane(pane);
    pane.setLayout(null);

    trans_pln_name= new JTextField[30];
    trans_pln_num= new JTextField[30];
    trans_amt= new JTextField[30];
    trans_inv_name= new JTextField[30];
    trans_clr=new JButton[30];
    trans_add=new JButton[30];

    JLabel lblNewLabel = new JLabel("Transfer Form Page");
    lblNewLabel.setForeground(new Color(240, 248, 255));
    lblNewLabel.setBackground(Color.decode("#2c3e50"));
    lblNewLabel.setBounds(0, 0, 1000, 40);
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
    lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
    pane.add(lblNewLabel);

    JLabel lbl1 = new JLabel("Action");
    lbl1.setBounds(300, 95, 150, 30);
    pane.add(lbl1);

    JLabel lbl2 = new JLabel("Begin Date");
    lbl2.setBounds(300, 139, 150, 30);
    pane.add(lbl2);

    JLabel lbl3 = new JLabel("Frequency");
    lbl3.setBounds(300, 183, 150, 30);
    pane.add(lbl3);

    JLabel lbl4 = new JLabel("$ or %");
    lbl4.setBounds(300, 227, 150, 30);
    pane.add(lbl4);

    JLabel lbl5 = new JLabel("Future Transaction Day");
    lbl5.setBounds(300, 272, 150, 30);
    pane.add(lbl5);
    String[] action = { "Custom Transfer","Simple Transfer"};
    trans_comboBox_3 = new JComboBox(action);
    trans_comboBox_3.setSelectedIndex(0);
    trans_comboBox_3.setBounds(470, 95, 180, 33);

    pane.add(trans_comboBox_3);

    String[] freq = {"Once", "Monthly","Quarterly","Semi-Annually","Annually"};
    String[] dollar = { "Dollar", "Percent"};
    trans_comboBox_4 = new JComboBox(freq);
    trans_comboBox_4.setSelectedIndex(0);
    trans_comboBox_4.setBounds(470, 183, 180, 33);
    pane.add(trans_comboBox_4);

    trans_comboBox_1 = new JComboBox(dollar);
    trans_comboBox_1.setSelectedIndex(1);
    trans_comboBox_1.setBounds(470, 227, 180, 33);
    pane.add(trans_comboBox_1);

    trans_comboBox_2 = new JComboBox();
    for(int i=1;i<29;i++)
    {
        trans_comboBox_2.addItem(String.valueOf(i));
    }

    trans_comboBox_2.setSelectedIndex(0);
    trans_comboBox_2.setBounds(470, 272, 180, 33);
    pane.add(trans_comboBox_2);

    JLabel lblMaritalStatus = new JLabel("On Future Date");
    lblMaritalStatus.setBounds(300, 315, 150, 30);
    pane.add(lblMaritalStatus);

    trans_begin = new JTextField();
    trans_begin.setColumns(10);
    trans_begin.setBounds(470, 139, 180, 33);
    pane.add(trans_begin);

    trans_future = new JTextField();
    trans_future.setColumns(10);
    trans_future.setBounds(470, 320, 180, 33);
    pane.add(trans_future);

    addItem();
    pane.revalidate();

    JButton btnNewButton = new JButton("Create Test Case");
    btnNewButton.setBounds(470, 800, 180, 33);
    btnNewButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e) {
            /*assignXML();
        System.out.println(XML);
        XMLPath=new String[10];
        XMLPath[0]="C:\\Users\\paranja\\Desktop\\UI\\"+main_test_num.getText()+".xml";
        File fileName = new File(XMLPath[0] );
        if(fileName.exists())
        {
            actionDialog = JOptionPane.showConfirmDialog(getContentPane(),
                    "Replace existing file?");
            if (actionDialog == JOptionPane.NO_OPTION)
                return;
        }
        try
        {
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName));

            out.write(XML);
            out.close();
        }
        catch(Exception ex)
        {
            System.err.println("Error: " + ex.getMessage());
        }
        CreateGroovyAndUploadXML create=new CreateGroovyAndUploadXML();
        create.CreateGroovy(XMLPath);
             */}
    });
    pane.add(btnNewButton);

}

private void addItem() {
    // TODO Auto-generated method stub

    pane.revalidate();
    trans_pln_num[count]=new JTextField();
    trans_pln_num[count].setBounds(50, (300+count*100), 100, 50);
    trans_pln_num[count].setColumns(10);
    trans_pln_num[count].setBorder(
            BorderFactory.createTitledBorder("Plan Number"));
    pane.add(trans_pln_num[count]);

    trans_pln_name[count]=new JTextField();
    trans_pln_name[count].setBounds(200, (300+count*100), 100, 50);
    trans_pln_name[count].setColumns(10);
    trans_pln_name[count].setBorder(
            BorderFactory.createTitledBorder("Plan Name"));
    pane.add(trans_pln_name[count]);

    trans_inv_name[count]=new JTextField();
    trans_inv_name[count].setBounds(350, (300+count*100), 200, 50);
    trans_inv_name[count].setColumns(10);
    trans_inv_name[count].setBorder(
            BorderFactory.createTitledBorder("Investment Name"));
    pane.add(trans_inv_name[count]);

    trans_amt[count]=new JTextField();
    trans_amt[count].setBounds(600, (300+count*100), 200, 50);
    trans_amt[count].setColumns(10);
    trans_amt[count].setBorder(
            BorderFactory.createTitledBorder("Amount"));
    pane.add(trans_amt[count]);

    trans_clr[count]=new JButton("Clear");
    trans_clr[count].setBounds(850, (300+count*100), 50, 50);
    pane.add(trans_clr[count]);

    trans_add[count]=new JButton("+");
    trans_add[count].setBounds(950, (300+count*100), 50, 50);
    trans_add[count].addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e) {
            count=count+1;
            addItem();
        }
    });
    pane.add(trans_add[count]);
    pane.revalidate();

}


text:
Q: PreferenceActivity vs. PreferenceFragment when writing App for all Versions I have a problem trying to use preferences with my App.
I could not find a solution in similar posts here.
My App shall support android versions from 8 to 19.
With Android Developer I found this:

If your app supports versions of Android older than 3.0 (API level 10 and lower), you must build the activity as an extension of the PreferenceActivity class.
      On Android 3.0 and later, you should instead use a traditional Activity that hosts a PreferenceFragment that displays your app settings. However, you can also use PreferenceActivity to create a two-pane layout for large screens when you have multiple groups of settings.

So what to do if I would not support neither API's up to level 10 and not higher nor API's only higher than 10?
I have tried to use the PreferenceActivity class together with addPreferencesFromRessource(R.id....)
But than I've got this:
package com.example.wbslideshow;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class initialpath extends PreferenceActivity {

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

        addPreferencesFromResource(R.xml.preferences);

    }
}

where addPreferencesFromResource is seen as addPreferencesFromResource because of the deprecated status.
together with this explanation:

The method addPreferencesFromResource(int) from the type PreferenceActivity is deprecated

What can I do? I think due to my API's level I can not use also PreferenceFragment which I would like to prefer. Any idea is appreciated.

A: Use the deprecated functions. They are still working but should not be considered state of the art. There is no option since you want to support older versions without the new possibilities. You could think about switching your project to newer APIs only.


text:
Q: Cypress interact with Metamask Extension I have a website related to blockchain. I am using cypress to execute automation testing for this site. I have problem when cypress interact with Metamask extension.
Embeeded chrome in Cypress can load Metamask extentsion but

*

*With first time using: I have to input seed phase by hand 1 time before.

*With other times: I have to input password by hand before

My question: How to configure cypress auto fill password or seed phase automatically.
My code is bellow:
cypress.config.ts:
...
on('before:browser:launch', (browser = {}, launchOptions) => {
launchOptions.extensions.push('D:/Research/META3/metamask-chrome-10.15.0')
// How to set password /seedpharse for Metamask extentsion.
return launchOptions
})


text:
Q: Add Change-Id to all commits I just installed Gerrit and I wanted to do a push to it, but I'm getting an error regarding Change-Id, but it appears to be in the commit it's complaining about.
$ git push gerrit HEAD:refs/publish/my-branch
Counting objects: 28, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (15/15), done.
Writing objects: 100% (15/15), 4.46 KiB, done.
Total 15 (delta 12), reused 0 (delta 0)
remote: Resolving deltas: 100% (12/12)
remote: Processing changes: refs: 1, done
remote: ERROR: missing Change-Id in commit message footer
remote: Suggestion for commit message:
remote: Revert "Refactoring controllers"
remote:
remote: This reverts commit dd1c5c86b12461f61326fd102a11d9e3cb51142e.
remote:
remote: Change-Id: Iaacf80a9e4f56b58d0b648112c3eb2413988f00e
remote:
remote: Hint: To automatically insert Change-Id, install the hook:
remote:   gitdir=$(git rev-parse --git-dir); scp -p -P 29418 user@ci:hooks/commit-msg ${gitdir}/hooks/
remote:
remote:
To ssh://user@ci:29418/Project
! [remote rejected] HEAD -> refs/publish/my-branch (missing Change-Id in commit message footer)
error: failed to push some refs to 'ssh://user@ci:29418/Project'

I assume that this is because of previous commits that are without Change-Id because they were made prior to having the hook. How can I update all previous commits to add the Change-Id?

A: When you have hook, you can do rebase branch into itself in interactive mode
git checkout branchName
git rebase -i branchName

When you see interactive menu change keyword pick to edit near every commit that you have no change id. Then git will stop before "rebasing" every commit that marked as edit. On every stop you do git commit --amend,save changes(change id will be added automatically, if you have commit hook hrom gerrit, othrwise you need to add it manually), and then git rebase --continue. After that every commit in your branch will have change-id.
Rince and repeat for every branch you need.

A: In Gerrit - at the project settings page disable the option which requiring change-Id in commits temporarily. Then push the existing commits to Gerrit.

A: As answered in this question. You will need to use git filter-branch --msg-filter which will simulate the process of creating Change-IDs
Basically you want to make a new orphan branch (no prior history) and then rewrite all the commits to have Change-IDs.
The specific code sample you need is (verbatim from the answer previously mentioned)
#create an orphan branch "tmp" from "master".
git checkout --orphan tmp master
git commit -m 'new root'
#cherry-pick all the commits from an upstream kernel branch.
git cherry-pick <all-the-commits>
#rewrite the commit message of every commit on "tmp"
git filter-branch --msg-filter 'git log -1 --pretty=%B $GIT_COMMIT > msg.txt;~/commit-msg msg.txt;cat msg.txt'
#all the commits now have Change-Id
#cherry-pick all of them except the root to "master"
root=$(git log --pretty=%H --max-parents=0)
git checkout master
git cherry-pick $root..tmp

A: All answers to this question seem to be more complicated than needed. I'd like to suggest a refined and (hopefully) easier version of HaoZeke answer.
First of all, I assume that the Change-Id adding message hook is already installed, like Gerrit instructs (Hint: To automatically insert Change-Id, install the hook: ...).
Then it should be enough to apply it on all commits in desired range with single git invocation:
git filter-branch --msg-filter '
    tmp=`mktemp` &&
    cat >$tmp &&
    $GIT_DIR/hooks/commit-msg $tmp &&
    cat $tmp &&
    rm -f $tmp' \
<YOUR_BASE_GIT_REV>..HEAD

A: Building off of @Asprelis's answer, I found a one line command that rebases and ammends all commits in the specified range without the need to waste time in interactive mode:
git rebase -f HEAD~<num_of_commits> <branch> --exec "git commit --amend --no-edit"

Explanation:
According to the git documentation at:
https://git-scm.com/docs/git-rebase
-f forces git rebase to "Individually replay all rebased commits instead of fast-forwarding over the unchanged ones. This ensures that the entire history of the rebased branch is composed of new commits"
and --exec "Append "exec " after each line creating a commit in the final history.  will be interpreted as one or more shell commands."
So in short, this command tells git rebase to rewrite and execute git commit --amend --no-edit on each commit you are rebasing.
If you installed the gerrit "commit-msg" hook, this will insert a Change ID into each commit.


text:
Q: Linq query select property list with join I'm trying to get a list in a linq with joins and get all events for specific user.
This is the query I have so far:
  var runnerObject = from r in _context.Runners
                               join re in _context.RunnerEvents
                               on r.RunnerId equals re.RunnerId
                               join e in _context.Events
                               on re.EventId equals e.EventId
                               where r.RunnerId == runnerId
                               select new RunnerVM
                               {
                                   RunnerId = r.RunnerId,
                                   FirstName = r.FirstName,
                                   LastName = r.LastName,
                                   UserId = r.UserId,
                                   Events = //get all events in Events table for the runnerId
                               };

Events should be all entries from Events table for that runner, based on their id which is joined in the RunnerEvents table. How can I get that?

A: Something like this?
var runnerObject = from r in _context.Runners
                           join re in _context.RunnerEvents
                           on r.RunnerId equals re.RunnerId
                           join e in _context.Events
                           on re.EventId equals e.EventId
                           where r.RunnerId == runnerId
                           select new RunnerVM
                           {
                               RunnerId = r.RunnerId,
                               FirstName = r.FirstName,
                               LastName = r.LastName,
                               UserId = r.UserId,
                               Events = r.Events.Select(e => new Event { }).ToList()
                           };


text:
Q: How to make Android TestRunner wait until activity finishes I am closing an Activity at the end of a testcase, so that it is null at the beginning of the next testcase:
public void test1() throws Exception {

    //activity is calling the RegisterActivity in onCreate
    activity = getActivity();

    // register next activity that need to be monitored.
    RegisterActivity nextActivity = (RegisterActivity) getInstrumentation()
        .waitForMonitorWithTimeout(activityMonitor, 5);
    // next activity is opened and captured.
    assertNotNull(nextActivity);
    if (nextActivity != null) {
        nextActivity.finish();
    }
}

public void test2() throws Exception {
    //nextActivity.finish() from the previous test has not yet finished

    //body of test2
    //...
    //...
}

If I set a Thread sleep in test1 then problem is solved:
    if (nextActivity != null) {
        nextActivity.finish();
        Thread.sleep(1500);
    }

Is there a better way to to this? Is there a method that blocks the TestRunner until nextActivity is finished?

A: Try creating a new thread for the nextActivity to run in. After calling the thread.start() method, call thread.join() where you want the TestRunner blocked.


text:
Q: removing duplication in google search api? I am performing a google search in my application through google search api. It gives me the duplicate results. How to avoid it. I refer http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje

A: You can look at the filtering option used at :

*

*http://code.google.com/apis/searchappliance/documentation/64/xml_reference.html
It uses two types of filter:

*

*Duplicate Snippet Filter

*Duplicate Directory Filter

So when calling, mark Filter=True
results = server.doGoogleSearch(key, 'mark', 0, 10, False, "", ...)

The API provides the following argument:
key - Your Google API key
q - The search word
start - The index of the result to start on
maxResults - The number of results to return.
filter - If True, Google will filter out duplicate pages
restrict - Set this to country plus a country code to get results only from a particular country
safeSearch - If True, Google will filter out porn sites
lr ("language restrict") - Set this to a language code
ie and oe must be "utf-8"


text:
Q: Detect if is cash drawer open with ESC command I have receipt printer Epson TM T-20II, the cash drawer is connect with printer. I would like to detect if cash drawer is open with standart ESC command. It is possible?

A: You can use the status commands of ESC/POS.
GS a [n] (0x1d 0x61 [n])

Activate/deactivate ASB (Auto Status Back).
If bit 0 of [n] is set, the drawer status will be reported by the printer.
Other bits activate monitoring of other features (paper sensor, cover sensor etc.)
If any ASB mode is activated, the printer will send the status if any of the requested status have changed. The ASB message are always 4 bytes with some fixed bits which can be used to identify the message as an ASB message.
Bit 2 of the first byte signals the drawer state.
GS r 2 (0x1d 0x72 0x02)

If you prefer to poll for the drawer status, you can use this command.
Here the printer returns one byte, Bit 0 will give you the drawer state.
For more details I recommend the ESC/POS reference which can be found here:
https://reference.epson-biz.com/pos/reference/


text:
Q: Add mp3 to React I added an mp3 to the src folder in a project bootrstrapped with Create React App. I added a component for the audio file, Audio.js, which I'd like to play conditionally based on whether a prop playAlarm is true or not.
The parent App.js passes the prop to child Timer.js, which renders Audio.js.
The Audio.js file is giving me a 'React' is defined but never used error, and I'm not sure why.
Audio.js:
import React, { Component } from 'react';

class Audio extends Component {
  constructor() {
    super();
    this.url = "./chime.mp3";
    this.audio = new Audio(this.url);
  }

  render() {

    return (
      this.audio
    );
  }
}

export default Audio;

In Timer.js, Audio is rendered like this: {props.playAlarm ? <Audio /> : null}
When I tested playing the audio, when playAlarm is set to true I get Uncaught RangeError: Maximum call stack size exceeded at the line with super() in Audio.js.
App.js:
import React, { Component } from 'react';
import Timer from './Timer';

class App extends Component {
  // ES6 class property/class field syntax allows you to remove constructor when just being used to initialize state
  state = {
    sessionDuration: 5, // TODO: change back to 1500 when testing done
    breakDuration: 3, // TODO: change back to 300 when testing done
    sessionTimeRemaining: 5, // TODO: change back to 1500 when testing done
    breakTimeRemaining: 3, // TODO: change back to 300 when testing done
    isSession: true,
    timerOn: false,
    sessionNumber: 0,
    playAlarm: false
  }

  // Using property initializer syntax to avoid need to bind, since arrow functions don't create their own this context and use value of enclosing context instead. transform-class-properties Babel plugin necessary to use this syntax (included in Create React App). Refer to https://itnext.io/property-initializers-what-why-and-how-to-use-it-5615210474a3 for more details

  // DURATION CHANGES

  decreaseBreakDuration = () => {
    // Conditional statement prevents decrease when break is at 1 minute
    if (this.state.breakDuration === 60) {
      return undefined;
    } else {
      this.setState({
        breakDuration: this.state.breakDuration - 60
      });
    }
  }

  increaseBreakDuration = () => {
    this.setState({
      breakDuration: this.state.breakDuration + 60
    });
  }

  decreaseSessionDuration = () => {
    // Conditional statement prevents decrease when session is at 5 minutes
    if (this.state.sessionDuration === 300) {
      return undefined;
    } else {
      this.setState({
        sessionDuration: this.state.sessionDuration - 60,
        sessionTimeRemaining: this.state.sessionTimeRemaining - 60
      });
    }
  }

  increaseSessionDuration = () => {
    this.setState({
      sessionDuration: this.state.sessionDuration + 60,
      sessionTimeRemaining: this.state.sessionTimeRemaining + 60
    });
  }

  manageBreak = () => {
    this.setState({
      playAlarm: false
    });
    this.time = setInterval(() => {
      this.setState({
        breakTimeRemaining: this.state.breakTimeRemaining - 1
      });
      if (this.state.breakTimeRemaining === 0) {
        this.handleBreakComplete();
      }
    }, 1000);
  }

  manageSession = () => {
    this.setState({
      playAlarm: false
    });
    // Every 1,000 ms (1 second), subtract 1 (a single second) from displayed sessionTimeRemaining. Assigned to this.time (scoped to entire class) in order to pass it to clearInterval() when pause button is clicked
    this.time = setInterval(() => {
      this.setState({
        sessionTimeRemaining: this.state.sessionTimeRemaining - 1
      });
      if (this.state.sessionTimeRemaining === 0) {
        this.handleSessionComplete();
      }
    }, 1000);
  }

  handleSessionComplete = () => {
    clearInterval(this.time);
    this.setState({
      playAlarm: true,
      sessionNumber: this.state.sessionNumber + 1
    })

    if (this.state.sessionNumber === 4) {
      this.handlePomodoroCycleDone();
    } else {
      this.setState({
        timerOn: false,
        sessionTimeRemaining: this.state.sessionDuration,
        breakTimeRemaining: this.state.breakDuration,
        isSession: !this.state.isSession,
      });
    }
  }

  handlePomodoroCycleDone = () => {
    // TODO: Display message in modal
    console.log('Great work! You finished a pomodoro cycle (four sessions). Time to relax.')
    // Change back to default values
    this.setState({
      isSession: true,
      timerOn: false,
      sessionDuration: 5, // TODO: change back to 1500
      breakDuration: 3, // TODO: change back to 300 when testing done
      sessionTimeRemaining: 5, // TODO: change back to 1500
    });
  }

  handleBreakComplete = () => {
    clearInterval(this.time);
    this.setState({
      timerOn: false,
      sessionTimeRemaining: this.state.sessionDuration,
      breakTimeRemaining: this.state.breakDuration,
      isSession: !this.state.isSession,
      playAlarm: true
    });
  }

  // PLAY, PAUSE, RESTART BUTTONS

  startTimer = () => {
    this.setState({
      timerOn: true,
    });

    if (this.state.isSession) {
      this.manageSession();
    } else {
      this.manageBreak();
    }
  }

  pauseTimer = () => {
    // Stops setInterval's calling its (setState) callback every 1000 ms
    clearInterval(this.time);

    this.setState({
      timerOn: false
    });
  }

  resetTimer = () => {
  // Stops setInterval's calling its (setState) callback every 1000 ms
  // TODO: Display 4 unchecked circle icons again
    clearInterval(this.time);
    this.setState({
      timerOn: false,
      sessionDuration: 5, // TODO: change back to 1500
      breakDuration: 3, // TODO: change back to 300 when testing done
      sessionTimeRemaining: 5, // TODO: change back to 1500
      breakTimeRemaining: 3, // TODO: change back to 300 when testing done
      sessionNumber: 0
    });
  }

  render() {
    return (
      <Timer
        breakDuration={this.state.breakDuration}
        sessionDuration={this.state.sessionDuration}

        decreaseBreakDuration={this.decreaseBreakDuration}
        increaseBreakDuration={this.increaseBreakDuration}
        decreaseSessionDuration={this.decreaseSessionDuration}
        increaseSessionDuration={this.increaseSessionDuration}

        sessionTimeRemaining={this.state.sessionTimeRemaining}
        breakTimeRemaining={this.state.breakTimeRemaining}
        timerOn={this.state.timerOn}
        sessionNumber={this.state.sessionNumber}

        isSession={this.state.isSession}

        startTimer={this.startTimer}
        pauseTimer={this.pauseTimer}
        resetTimer={this.resetTimer}

        playAlarm={this.state.playAlarm}
      />
    );
  };
}

export default App;
Also here's Timer.js:
import Audio from './Audio';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlay } from '@fortawesome/free-solid-svg-icons';
import { faPause } from '@fortawesome/free-solid-svg-icons';
import { faUndo } from '@fortawesome/free-solid-svg-icons';
import React from 'react';
import PomodoroIcons from './PomodoroIcons';
import DurationControls from './DurationControls';

const TimeFormat = require('hh-mm-ss');

const Timer = props => (

  <DurationControls
    breakDuration={props.breakDuration}
    sessionDuration={props.sessionDuration}

    increaseBreakDuration={props.increaseBreakDuration}
    decreaseBreakDuration={props.decreaseBreakDuration}

    increaseSessionDuration={props.increaseSessionDuration}
    decreaseSessionDuration={props.decreaseSessionDuration}
  />

  {/* TIME REMAINING */}

    {props.isSession ? TimeFormat.fromS(props.sessionTimeRemaining) : TimeFormat.fromS(props.breakTimeRemaining)}

  {/* PLAY, PAUSE, RESTART BUTTONS */}

      <FontAwesomeIcon
        role="button"
        onClick={props.startTimer}
        icon={faPlay}
        className="btn bottom-btn"
        size="4x"
      />

      <FontAwesomeIcon
        role="button"
        onClick={props.pauseTimer}
        icon={faPause}
        className="btn bottom-btn"
        size="4x"
      />

    <FontAwesomeIcon
      role="button"
      onClick={props.resetTimer}
      icon={faUndo}
      className="btn bottom-btn"
      size="4x"
    />

 {/* End bottom-btns */}

  <PomodoroIcons sessionNumber={props.sessionNumber} />

  {props.playAlarm ? <Audio /> : null}

);

export default Timer;

A: i dont follow everything going on here.. but at a glance this is an issue:
class Audio extends Component {
  constructor() {
    super();
    this.url = "./chime.mp3";
    this.audio = new Audio(this.url);
  }

  render() {

    return (
      this.audio
    );
  }
}

the call stack exceeded error is because you're entering into an infinite loop.  You instantiate Audio inside of Audio which will make another Audio object and so on into infinity.


text:
Q: Count how many blocks in dataframe I would like to count how many down and up trends there are in this dataframe containing simple moving average data:
Date        SMA_50     SMA_200    Trend Trend CumCount      T
2019-09-24  35.559013  38.942979  Down              1
2019-09-25  35.427135  38.904934  Down              2
2019-09-26  35.295066  38.864042  Down              3
2019-09-27  35.165275  38.827087  Down              4
2019-09-30  35.035484  38.788046  Down              5
2020-08-31  34.697343  34.689469    Up              1
2020-09-01  34.768881  34.691034    Up              2
2020-09-02  34.852941  34.690655    Up              3
2020-09-03  34.932827  34.686765    Up              4
2020-09-04  35.009488  34.680598    Up              5
2020-09-08  35.083302  34.675285    Up              6
2020-09-09  35.150474  34.667884    Up              7
2019-10-01  34.895256  38.744687  Down              1
2019-10-02  34.736053  38.701518  Down              2
2019-10-03  34.594877  38.665180  Down              3
2019-10-04  34.466983  38.634488  Down              4
2019-10-07  34.329222  38.605361  Down              5

I would like the result to be:
Date        SMA_50     SMA_200    Trend Trend CumCount      T
2019-09-24  35.559013  38.942979  Down              1       1
2019-09-25  35.427135  38.904934  Down              2       1
2019-09-26  35.295066  38.864042  Down              3       1
2019-09-27  35.165275  38.827087  Down              4       1
2019-09-30  35.035484  38.788046  Down              5       1
2020-08-31  34.697343  34.689469    Up              1       1
2020-09-01  34.768881  34.691034    Up              2       1
2020-09-02  34.852941  34.690655    Up              3       1
2020-09-03  34.932827  34.686765    Up              4       1
2020-09-04  35.009488  34.680598    Up              5       1
2020-09-08  35.083302  34.675285    Up              6       1
2020-09-09  35.150474  34.667884    Up              7       1
2019-10-01  34.895256  38.744687  Down              1       2
2019-10-02  34.736053  38.701518  Down              2       2
2019-10-03  34.594877  38.665180  Down              3       2
2019-10-04  34.466983  38.634488  Down              4       2
2019-10-07  34.329222  38.605361  Down              5       2

Based on Trend column, how can I count how many times up and down trends appear in the dataframe?

A: Use a combination of replace, diff, and cumsum:
df["T"] = ((df.Trend.replace({"Down": 0, "Up": 1}).diff() == -1) + 1).cumsum()

A: You can identify when the Trend shifts back to the first value:
# equal to first Trend?
s = df['Trend'].eq(df['Trend'].iloc[0])
# when is the first value coming back for the first time after a change?
# perform cumsum to get T
df['T'] = (s&~s.shift(fill_value=False)).cumsum()

output:
          Date     SMA_50    SMA_200 Trend  Trend CumCount  T
0   2019-09-24  35.559013  38.942979  Down               1  1
1   2019-09-25  35.427135  38.904934  Down               2  1
2   2019-09-26  35.295066  38.864042  Down               3  1
3   2019-09-27  35.165275  38.827087  Down               4  1
4   2019-09-30  35.035484  38.788046  Down               5  1
5   2020-08-31  34.697343  34.689469    Up               1  1
6   2020-09-01  34.768881  34.691034    Up               2  1
7   2020-09-02  34.852941  34.690655    Up               3  1
8   2020-09-03  34.932827  34.686765    Up               4  1
9   2020-09-04  35.009488  34.680598    Up               5  1
10  2020-09-08  35.083302  34.675285    Up               6  1
11  2020-09-09  35.150474  34.667884    Up               7  1
12  2019-10-01  34.895256  38.744687  Down               1  2
13  2019-10-02  34.736053  38.701518  Down               2  2
14  2019-10-03  34.594877  38.665180  Down               3  2
15  2019-10-04  34.466983  38.634488  Down               4  2
16  2019-10-07  34.329222  38.605361  Down               5  2

A: # I ignored the "Trend CumCount" column in testing,
# but it shouldn't change anything.
df.loc[df.Trend.ne(df.Trend.shift(-1)), 'T'] = 1
df['T'] = df.groupby('Trend')['T'].cumsum().bfill()
print(df)

Output:
          Date     SMA_50    SMA_200 Trend    T
0   2019-09-24  35.559013  38.942979  Down  1.0
1   2019-09-25  35.427135  38.904934  Down  1.0
2   2019-09-26  35.295066  38.864042  Down  1.0
3   2019-09-27  35.165275  38.827087  Down  1.0
4   2019-09-30  35.035484  38.788046  Down  1.0
5   2020-08-31  34.697343  34.689469    Up  1.0
6   2020-09-01  34.768881  34.691034    Up  1.0
7   2020-09-02  34.852941  34.690655    Up  1.0
8   2020-09-03  34.932827  34.686765    Up  1.0
9   2020-09-04  35.009488  34.680598    Up  1.0
10  2020-09-08  35.083302  34.675285    Up  1.0
11  2020-09-09  35.150474  34.667884    Up  1.0
12  2019-10-01  34.895256  38.744687  Down  2.0
13  2019-10-02  34.736053  38.701518  Down  2.0
14  2019-10-03  34.594877  38.665180  Down  2.0
15  2019-10-04  34.466983  38.634488  Down  2.0
16  2019-10-07  34.329222  38.605361  Down  2.0


text:
Q: Bash: CTRL+A prints ^A to stdout A few days ago, my ubuntu console started printing '^A' whenever I hit 'CTRL+A', instead of moving the cursor to the start of the line as it did before. The same problem happens for 'CTRL+E', while the 'CTRL+Arrow' shortcuts behave as they should.
However, if I log in to a remote machine via ssh, everything works fine.
Unfortunately, I do not remember anything in particular which could have triggered this behaviour (I have not changed shortcuts, nor modified my '.bashrc' file, nor updated the system).
some useful information:
I am not using nor screen nor tmux or other terminal multiplexers;
joe@Zen:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 19.10
Release:    19.10
Codename:   eoan

joe@Zen:~$ echo $TERM
xterm-256color

joe@Zen:~$ ps -f -p$PPID
UID        PID  PPID  C STIME TTY          TIME CMD
joe      11539  1575  0 12:27 ?        00:00:04 /usr/libexec/gnome-terminal-server

joe@Zen:~$ echo $SHELL
/bin/bash

joe@Zen:~$ cat /proc/version
Linux version 5.3.0-62-generic (buildd@lcy01-amd64-018) (gcc version 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2)) #56-Ubuntu SMP Tue Jun 23 11:20:52 UTC 2020

Thank you in advance if you give me some ideas about what could I try.

A: I would suggest that you have inadvertently changed your line editing scheme from the default "emacs" to "vi".
You can reset this back with
set -o emacs

Or change it back to vi mode with
set -o vi


text:
Q: Handling null in JSON RESPONSE I am getting json response as
["L500","Success",null]

How can I handle it
Here is what I tried
jsonArray.getJSONArray(2).getJSONObject(2).equals(JSONObject.NULL);

However, it produces the error:

org.json.JSONException: Value null at 2 of type org.json.JSONObject$1 cannot be converted to JSONArray

If null I need to show a Toast message to user something like "No records found".

A: I solved it by replacing
jsonArray.getJSONArray(2).getJSONObject(2).equals(JSONObject.NULL);

with
jsonArray.get(2).equals(null);


text:
Q: Gaussian filter of 2d image with location dependant sigma in Python I am trying to implement in Python a Gaussian filter in which the kernel is

where  f(x,y) is some function of the coordinates. Is it possible somehow to trick scipy.ndimage.filters.gaussian_filter to do the job?
Eventually I will have to perform the following integration over space:

And so I get $\tilde G(x',y') $ as a coordinate dependent coefficient.
Right now I am making it with tedious for loops:
def calc_g1(b,w,p):
    nx,ny = b.shape
    g1 = np.zeros_like(b)
    for i in np.arange(nx):
        for j in np.arange(ny):
            for ii in np.arange(nx):
                for jj in np.arange(ny):
                    g = calc_kernel(b,p,i,j,ii,jj)
                    g[i,j]+=g*w[ii,jj]
    return g1

def calc_kernel(b,w,i,j,ii,jj):
    dx,dy = p['dx'],p['dy']
    dist_x = dx*np.abs(ii-i)
    dist_y = dy*np.abs(jj-j)
    dist = dist_x**2 + dist_y**2
    f = (1.0 + p['eta']*b[i,j])**2
    return 1.0/(2.0*np.pi)*np.exp(-(dist)/(2.0*f))

** Can I do it somehow using Symbolic calculation using SymPy or Theano?

A: Convolutions, from a certain signal and filter support size onwards are always faster to perform in Fourier space by pointwise multiplication of the Fourier transforms of signal and filter and inverse transforming.
In that case one assumes the filtering to be linear and shift-invariant, so your context does not fit the classic context of convolution.
So you will have to implement this yourself.
If you have a lot of signals to apply this to, your best bet without resorting to writing low-level code is to write this transformation in the form of a scipy.sparse matrix. For this, you have to create all the Gaussian filters you need and place them appropriately in the image and stacking the ravelled versions of these filter images in a sparse matrix. You should truncate the support of you Gaussians so most of the pixels of your image are equal to 0. Once this matrix is created, you can apply it immediately to the pixel array of any image to get the desired result.


text:
Q: Prevent opening data sources Read-only when refreshing pivot table with external connection Normally I have all my questions answerred with topics from Stack Overflow, but now I ran into some difficulty to which I cannot find me a working answer.
Brief explanation what I am trying to achieve with the following setup:
I have setup a database in MS Access (which basically is a SQL query that links some Excel sources into one large table which i want to use in a pivottable)
I have a pivottable in Excel which I have connected to this MS Database by doing the following, it is working perfectly despite one minor issue I want to have resolved.
In MS Access:
-Import Excel-sheets and Create linked-tables to the data source
-Create query where I have combined the Excel-tables with UNION (not UNION all).
[opening this query works like a charm, i have the Excel sheets correctly combined in one dataset]
In MS Excel:
-Data > Get External Data > From Other Sources > From Microsoft Query > MS Access Database > OK > database.accdb [read-only on/off*] > AccessTable > OKOKOK
-Insert PivotTable > Use external datasource > choose connection > AccessTable
[situation: MS Access is unopened, I refresh PivotTable, Excel uses query of MS Access to reload all data from Excel sheets, it works perfectly when all Excel files are closed = no users have the Excel sources open]
Problem:
-MS Excel: when users have the data source Excels open, upon refreshing the pivot, Excel opens all Read-only files are are open by other users. I do not want this to happen. I want the connection to treat the files as read-only, if opened, just use data that has not yet been saved by user. I do not want Excel to open all the open documents as Read only.
When having an Excel data source open, and I have MS Access open, then i get the following alert. However, this does not limit the query to refresh the data. For me, this currently is no problem, just some other symptom.
-MS Access: "The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data"
What have i already attempted:
-https://bytes.com/topic/access/answers/957940-access-db-opens-read-only-when-linked-excel-file-open
[this solution does not work in my situation, i have the following error: "no value given for one or more required parameters mode share deny none" or "no value given for one or more required parameters mode read".]
-some vba code that stops opening other read-only files, but this is only patching some symptom instead of solving the root cause.
I am very curious what other possibilities I have to overcome this.


text:
Q: Encoding of characters when running powershell script as python subprocess Currently, I'm scripting a small python application that executes a PowerShell script. My python script should process the returned string but unfortunately, I have some trouble with the encoding of special characters like 'ä', 'ö', 'Ü' and so on. How can I return a Unicode/UTF-8 string?
You can see a simple example below. The console output is b'\xc7\xcf\r\n'. I don't understand why it's not b'\xc3\xa4\r\n' because \xc3\xa4 should be the correct UTF8 Encoding for the character 'ä'.
try.py:
import subprocess
p = subprocess.check_output(["powershell.exe", ".\script.ps1"])
print(p)

script.ps1:
return 'ä'

I adopted my PowerShell script in some ways but did not get the desired result.

*

*Added "[Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8". Result: b'\xc3\x83\xc2\xa4\r\n'

*Returned return [System.Text.Encoding]::UTF8.GetBytes("ä"). Result: b'195\r\n131\r\n194\r\n164\r\n'
Who can help to get console output of 'ä' for my upper script?

A: I used "pwsh" because I ran it on mac, you can use "powershell.exe" in your code
Try this:
import subprocess

p = subprocess.check_output(["pwsh", ".\sc.ps1"])
print(p.decode('utf-8'))

For more: You can read here.
Working Screenshot


text:
Q: Combining of two adjacent stack allocated arrays in C Say I have two arrays, dynamically allocated on the stack using C99 features. Due to the compiler's freedom of being able to reorder such arrays however it likes, and by great desire to out of bounds check, the two arrays aren't cleanly adjacent.  If I just needed it to work I'd write the whole part in assembly but I'm not that serious yet.
char a[] = {'H','e','l','l','o',',',' '};
char b[] = {'W','o','r','l','d','!','\n',0};

If this were assembly, and perhaps if I knew the language better, instead of setting b, I would just grow a by perhaps just increasing the stack pointer and then copy b over.
char* b = "World!\n";
size_t b_size = 8;// or some bothered way to get the sizeof("World!\n")
char a[] = {'H','e','l','l','o',',',' '};
predict_the_future_and_run_away_if_likely_explosion(); // Maybe... just use malloc bro
if(is_magical_failure(magically_grow_array_to_size(a, sizeof(a)+b_size))
    inform_user_of_grand_tragedy_and_recover_gracefully_or_explode_in_a_fire(
        "There was not enough spacetime left available to continue.");// TODO
//... or something...
strncpy(&a[a_size], b, b_size); // This copy seems necessary

If this magically_grow_array_to_size, can exist, it would, without copy, increase the size of the stack "knowing" that a is the last thing on the stack, and complain to me that I'm stupid for trying to grow the stack for an array that is smack in the middle, and say bro, just use malloc and put it on the heap like all the other good people on stackoverflow.
If the answer is "sister, just use malloc bro", please be respectful in the comments.
I know with utmost certainty that if I go into assembly and *assume the hardware architecture, and *assume there is a stack frame, and figure out how to reference the stack limit and know if It will be reached by said operation or not, everything will work.
If the answer is: c99, as elegant as it is, the feature you're looking for only got added in like version c2x or c4x or c09x... c12x, if it's within a couple years, go ahead. Beyond that, someone might appreciate it, can't promise, and hopefully I'd have accepted an answer appropriate of my time.
"don't use alloca bro" I'm having trouble parsing the answer I think; And I feel reassured as people seem to think the stack is faster than the heap~; so if alloca is slow, that's fine but why would I then go and use malloc if I don't have to?  I didn't understand the it's a free lunch thing, because does that mean I can shrink my stack usage once I figure out how much I need? I feel like if I move beyond once I received a free lunch, I'll be chugging memory. Once I move beyond combining two arrays on the stack, I'd like to know I'm not using any more memory than I have to. If I could see some code on how to free lunch, considering, oh, my predicament isn't super clear.
I really don't want to have to track the length of a anywhere other than compile time, I have determined b and it's length is available and b is either in program memory or is stored on the heap. How can I free lunch using a before I've actually checked the size of a, and if I can't... well, I should be able to... and in assembly if not in C99.  I still don't understand how to grow an array encouraged to be placed at the end of the stack frame... and if the endian-ness is wonky, ensure a is moved a from the middle to the beginning and add b to the end and if the endian-ness isn't wonky, just extend the size of the stack copy b in and Bob's your uncle, Alice we've done it! Should be dead simple, but apparently I'm clueless at the moment, maybe I missed the answer in plain sight, or don't know the search term but I couldn't find it.
If assembly is the best and only way to do this, if you could clear up my misconceptions about how possible or not writing cross-platform assembly is... really should be another question.  I really would like a pure C99 solution if possible, if a particular flavor of assembly was perfectly defined for all C99 capable devices, or reluctantly including mostly all or vast majority of, excluding only the most obtuse of microcontrollers, and never excluding any desktop machines, I'm down for some extern asm.
Please forgive my ignorance, and the wordiness of the question, if I were smart enough for it to be shorter and concise.

With love to the comments, the following is the question: Can I merge two stack allocated arrays in place using exactly enough memory at the end but using within an order of magnitude of the memory as the below example to get there?
const char a[]={'H','e','l','l','o',',',' '};
const char b[]={'W','o','r','l','d','!','\n',0};
char c[sizeof(a)+sizeof(b)];

strncpy(c,a,sizeof(a));
strncpy(&c[sizeof(a)],b,sizeof(b));

Without assembly, I refuse to believe this is this the best I can do in terms of memory usage.
I'm using twice as much stack space as strictly necessary.
If this is the best that can be done, I'll accept the closed question.  It's just annoying, I'd rather not go into assembly.
I can't figure out how to allocate enough space for c before defining a and b and once a and b are defined, I can't figure out how to get rid of them after defining c, other than to just do it in assembly.
It's not life threateningly critical, nobody is going to die, and I have a inefficient solution, but it is a serious question, I think. If nothing else it's just irritating that I can't get this space efficient (without assembly). Be it compiler directives or anything.
If it's closed again, I'll be asking how to do this in assembly. Because I'm lacking in comprehension.
If there is a clang solution, I'm fine with LLVM, however, cross compiler would be preferred.
If the gnu c compiler specifically, has a solution, it has good range of deployment targets as clang, if msvc only, I'd be less favorable to.


text:
Q: Emails from a support system that have the ticket number as the email address I have seen automated support ticketing systems which will email the user as soon as their ticket is created with a custom email address for that ticket.
For example, support_ticket_1234@example.com
Does postfix support such a system? Are there any examples out there that might explain how this system might work?

A: Many email systems (sendmail, postfix, and others) support the idea of "address extensions".  For example, let's assume my address is "bob@example.com".  If my mailer supports address extensions, I may also be able to send email to "bob+some_extension@example.com".  The mail still goes to the same places, but the extension is available for filtering.  The mail environment feeding a ticket system could be configured with '_' as the extension separator, so that anything addressed to ticket_1234@example.com would get forwarded to the ticketing system, which would use the address extension ("1234") to match the email to an issue.
Another mechanism is to dedicate an entire subdomain to the ticketing system.  In this case, instead of email going to ticket_1234@example.com, maybe it would go to ticket_1234@support.example.com.  The example.com mail system would be configured to pass all email for support.example.com to the ticket system.
All of these models are used in practice.

A: This would be better posted at ServerFault.com as Andreas mentioned. In general it is done by routing any address which is not resolved to an existing mailbox to a default mailbox, and then having a script that processes those mails for specific template data.

A: Yes, postfix supports it.
You can find a quick example in http://arstechnica.com/civis/viewtopic.php?p=4161616&sid=3bffda21847839a597dc19cfe3c82bb4#p4161616.
Best of luck,
João Miguel Neves


text:
Q: zclip not work in jquery ui inactive tab I am using zclip in my asp.net webpage on jQuery UI dialog in jQuery UI tab. It works great in first tab which is active but it doesn't work when I add it to second tab and click second tab and clip copy button.
my markup is below:
<input type="text" id="txtCallStatus" class="disabled"
    readonly="readonly" value="NOT SET" />
Copy status

Js code is below:
$.ajax({
    type: "POST",
    dataType: "json",
    url: "/recording/verifyUser",
    data: {
        ID: $("#ID").val(),
        PSSWD: $("#PSSWD").val(),
        ACCID: $("#ACCID").val(),
        PASSWDINT: $("#PASSWDINT").val()
    },
    success: function (data) {
        if (data == "success") {

            $('#dialog-AddCallRecording').dialog({ closeOnEscape: false });

            $(".ui-dialog-titlebar").hide();
            $("#dialog-AddCallRecording").dialog({
                dialogClass: 'transparent',
                modal: true
            });
            $("#dialog-AddCallRecording").dialog("open");

            // The link with ID "copy-description" will copy
            // the text of the paragraph with ID "description"
            $('a#copy-dynamic').zclip({
                path: '../../Content/Zclip/ZeroClipboard.swf',
                copy: function () { return $('input#txtCallStatus').val(); }
            });

            // The link with ID "copy-dynamic" will copy the current value
            // of a dynamically changing input with the ID "dynamic"

        }
        else {
            $("#dialog-user-login").dialog('option', 'position', 'center');
            $("#dialog-user-login").dialog("open");
        }
    }
});

In success, after dialogue is open, I am initializing the zclip.
Please suggest solution to it. Thanks


text:
Q: NSXMLParser results are null when not initialized in app delegate Why does initializing a parser...

*

*in a TVC instead of the app delegate

*writing the parsed values directly to the parser delegate, declared in .h:
@interface TVC:UITableViewController{
NSMutableArray *parsedDataArray;
}
@property (nonatomic, weak) NSMutableArray *parsedDataArray;

...result in a NULL value breakpoint when trying to use the parsed values in said TVC?
like so:
NSDictionary *topicsDict = [NSDictionary dictionaryWithObject:parsedResult forKey:@"News"];

and when breakpoints are turned off, we get this in the output:
2013-05-31 01:38:28.256 app[2383:c07] parsedDataArray: (null)
2013-05-31 01:38:28.257 app[2383:c07] *** Terminating app due to uncaught exception
 'NSInvalidArgumentException', reason: '***
-[__NSPlaceholderDictionary initWithObjects:forKeys:count:]:
attempt to insert nil object from objects[0]'
*** First throw call stack:
(0x16f4012 0x14f8e7e 0x16baa95 0x16c8946 0x7943 0x51e1c7 0x51e232 0x51e4da 0x5358e5
 0x5359cb 0x535c76 0x535d71 0x53689b 0x5369b9 0x536a45 0x63c20b 0x48d2dd 0x150c6b0
0x121fc0 0x11633c 0x121eaf 0x52c2bd 0x474b56 0x47366f 0x473589 0x4727e4 0x47261e
0x4733d9 0x4762d2 0x52099c 0x46d574 0x46d76f 0x46d905 0x476917 0x4976 0x43a157
0x43a747 0x43b94b 0x44ccb5 0x44dbeb 0x43f698 0x2618df9 0x2618ad0 0x1669bf5 0x1669962
 0x169abb6 0x1699f44 0x1699e1b 0x43b17a 0x43cffc 0x464d 0x1f85)
libc++abi.dylib: terminate called throwing an exception

Parser.m
 - (Parser *) initXMLParser {

    TVC *tvc = [[TVC alloc] init];

    NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"categorial" ofType:@"xml"];

    NSData *xmlData = [NSData dataWithContentsOfFile:xmlPath];

    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];

    [xmlParser setDelegate:tvc];

 return self;

The following is how I allocate the parser array
    tvc.parsedDataArray = [[NSMutableArray alloc] init];
... They are also synthesized in the implementation of TVC...
If there is anything else I should know or share with you to figure this out, let me know.


text:
Q: Using google drive to stream video into html5 player I tried to use google drive as a place to host videos, but whenever I try to use the video as a source, google never returns anything. (Not even a http response)
Example video player
<video>
  <source
    src="https://www.googleapis.com/drive/v3/files/<file_id>/?alt=media&key=<api_key>"
    type="video/mp4"
  />
</video>

If I enter the url in the browser it successfully prompts me for permission to download.
Does anybody have any idea what to do?

A: // This works...
<video src="https://www.googleapis.com/drive/v3/files/fileID?alt=media&key=apiKey">

// But, even better if you have access to a worker or can otherwise output the file through a script (and modify resonse headers)
async function getFile(request) {
    let response = await fetch('https://www.googleapis.com/drive/v3/files/fileID?alt=media&key=apiKey', request)
    response = new Response(response.body, response)
    response.headers.set('Accept-Ranges', 'bytes') // Allow seeking, not necessarily enabled by default
    response.headers.set('Content-Disposition', 'inline') // Disable Google's attachment (download) behaviour, display directly in browser or stick into video src instead
    return response
}
addEventListener('fetch', event => {
    event.respondWith(getFile(event.request))
})

A: Short answer: Nope
Longer answer: Oh boy. I spent quite a long time trying to figure this one out myself! I'm working on a project called DriveStream, that aims to use purely JavaScript and Apps Script to make an organised video library of a Drive account.
The project itself works fine, but implementing video streaming did not go anywhere near as planned. I tried a few different methods. One similar to yours and the other involving getting the downloadUrl property of a file and parsing the html of the download prompt page to give me a direct link to the file. I can initiate a download of that file, and that can be seen in the network requests, but there is no way to get it to stream into a video container.
The reason that doesn't work is due to the limitations of AJAX. It can return the data from a video, but there seems to be no way to funnel that data into a video container.
In the end, I've had to compensate by having the 'Play' button of each video only link to the preview video.
https://drive.google.com/file/d/fileId/preview

It's not a bad workaround, as it can play up to 1080p encodes of anything you upload.

A: This should work:
<video>
    <source src="https://drive.google.com/uc?export=download&id=file_ID" type='video/mp4'>
</video>

Replace "file_ID" in the link with your video ID. (to find it - right click on the Google Drive video, get shareable link. The file should be shared in order to access the file.)
It plays the source video. If you would like to change quality or to use unsupported codecs it's not easy to get google drive stream/converted files as said in previous answer. (Ajax will not let you get the link because of CORS and PHP is server side and the link contains an IP address so will not be accessible directly from client side.)

A: It's a long answer I will try to shorten it up..

*

*Upload your file to the drive and using the share option make it public.

*Then click on the preview option, and it will open a new tab.

*Look for the vertical 3 dots (top right corner) leading to a sub-menu and select open in a new window.

*As soon as you get to the new window click on the vertical 3 dots (top right corner) and this time you will see an  'Embed item' option click it.

*You will get the iframe code now include it your webpage or website.

Just give it a try once!!!
I hope this helps thank you!!

A: I might be a bit late to answer, but if anyone's interested, I have written an answer on streaming videos from Google Drive before here. There are a few ways to go about this, but in summary, you will have to do some server-side programming (can be ASP.NET, PHP etc.) if you don't want to use Google Drive's embedded player. Alternatively, if you have large videos that you want to stream that exceed the limit of 100MB, have you looked into HLS (HTTP Live Streaming)? You can create .m3u8 playlists with segments of your video (preferably less than 100MB) and that way, you can stream your videos. I hope my answer helps!


text:
Q: Can a java application interface with an ipad? I am working on a research project to create a system to control electronic music through a touch screen. We're planning on building out own special screen for this purpose, but that won't be ready for some time, and I need to start working on the software now. I've been given an ipad to use as a temporary test bed touch screen.
So, it looks like I'll be creating my software in java, and I need to find some way to interface the touch information from the ipad with my code. The connection doesn't need to be wireless. In a perfect world, I would even send display information to the ipad, but that's not a necessary feature. I mostly need to be able to test out multi touch functionality in my control engine before I get my hands on the actual screen we'll be using.
As the screen we'll be using will simply be passing in a set of touch points on each frame (as it's machine vision based), that's all I really want from the ipad. I don't need its gesture interpretation, as I'll be doing that on my end. I just need to get my java application to somehow get real time touch information from the ipad. I haven't had much luck googling solutions to this. Only thing relevant was the TouchPad app, but I think that's more directly interacting with the operating system, and wouldn't be giving me the data I need (although I'm going to buy it and experiment). Does anyone have a suggestion as to where I may start? Thanks!

A: Yes, you can develop everything in Java and then expose the business logic using a Web Service, which you can then consume using wsdl2objc in your iPad.
Then basically you will just call that Java business logic on your callbacks for the touches on the iPad.

A: Another option (to the web service) is to abstract the functionality away from the ipad to your computer, i.e. use it as a basic input device (multitouch mouse).
http://www.google.co.uk/search?sourceid=chrome&ie=UTF-8&q=use+iphone+as+a+pc+mouse#sclient=psy&hl=en&source=hp&q=use+ipad+as+a+pc+mouse

A: You need to interface them using TCP/IP (or higher layers, e.g. HTTP), and ensure the machine running your Java program has IP connectivity over WLAN to your iPad.
So, you need to write a program running on the iPad that connects via TCP/IP to your Java program, and exchanges the information you need, such as passing the touch points over to your java program.

A: as a workaround you can use the following way

*

*Install WebORB for Java on your dev box.

*Create a simple rtmp application with your logic

*Download the  WebORB for iOS RTMP Library and attach it to your project.

*Communicate with your server code through the RTMP protocol.

At this point the client library supports method invocation (client-server-client), data push ... Also with this workaround, you will have a persistent connection between the client and the server (I have no idea if it will be beneficial for your, but sounds awesome :) ). Moreover, it works really fast... Finally, for this case this approach is free - you can apply for the WebORB community license, or just use it in the development mode.
Examples
http://www.themidnightcoders.com/products/weborb-for-mobile/ios-integration/rtmp-ios-examples-integration-between-java-net-and-ios.html
Documentation
http://www.themidnightcoders.com/fileadmin/docs/ios/
Let me know if you need more information


text:
Q: backboneJS application runs fine in NodeJs but not in any other server? I was trying to load a json file in Collection of BackboneJS. While trying to run this through nodeJS server, it works fine. But once put in a server environment like XAMPP or even in a remote server it does not work? Any link would be a nice help. ( For reference my code is at github : https://github.com/saumya/backboneJS-basics )
thanks

A: Hey thanks for the helping hand.
Probably I did not understand the situation, so the question is not correct as I see now.
The modified question is:

*

*I have a frontend Application running on NodeJS server at some port.

*I am trying to load JSON from another server running on another server.

The answer of @Floby is the way I solved it. Its the CORS thing on the server which provides the JSON. It took me sometime to understand what is happening.


text:
Q: predicting a incoming sentence in a if statement? c# my problem is that i am trying to predict a key within a dictionary after this string "what is the weather like in". So you probably know already what this is after that sentence. I am making an weather application with voice recognition. And i need "what is the weather like in" to be static and after that sentence a city comes. For example "what is the weather like in gothenburg". where gothenburg is a recognized city in my dictionary i have.
I tried with
static Dictionary<string, int> cityList = new Dictionary<string, int>();
if (e.PartialResult.ToString() == string.Format("what is the weather like in {0}", cityList.ContainsKey(e.PartialResult.ToString().Trim("what is the weather like in ".ToArray()))))
{
            string city = e.PartialResult.ToString();
            city = city.Trim("what is the weather like in ".ToArray());
            int cityId = cityList[city]; //here is just city the recognized "city" from the voice recognition
}

however that didn't work, if statement is not true when i say for example "what is the weather like in gothenburg". the triming on the end of the if statement is just to get the "said" city standalone. If i wouldnt trim it that would be "what is the weather like in city" and not just "city".
this is the recognized i got when i tried "what is the weather like in south park". "south park" is in my dictionary so i have no clue why the code in the if statement is not being run when this is recognized. seems right to me?
basicly the if statement is suppose to be able to predict multiple city's. "what is the weather like in gothenburg" , "what is the weather like in denmark". You name it, what i do with the city that is recognized is that i trim down that whole string so that the city is just standalone. where i seach my dictionary for an int value by the string. so that i can send out that id to the weather api server and get back a proper response just for that city that was recognized
i am using bing speech api if that makes any difference in solving this issue.

A: Here's a more readable example of what I was talking about in the comments.

*

*What we can do is first check if the user input .StartsWith the weather query string (in a case-insensitive manner below).

*If that's true, then we can get the city portion of the string by calling .Substring() on the user input and passing in the length of our weather query. This will return the rest of the string.

*Finally we can pass this to the .TryGetValue method on the cityList dictionary, which will search the keys for that string and, if found, set the out parameter to the cityId value associated with that city in the dictionary.

Also notice that we should initialize our dictionary with a case-insensitive comparer, just to be sure we don't miss a key because of some capitalization.
For example:
static Dictionary<string, int> cityList =
    new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

static void SomeMethod(SomeType e)
{
    var weatherQuery = "what is the weather like in";
    int cityId;

    string userInput = e.PartialResult.ToString().Trim();

    if (userInput.StartsWith(weatherQuery, StringComparison.OrdinalIgnoreCase) &&
        cityList.TryGetValue(userInput.Substring(weatherQuery.Length).Trim(), out cityId))
    {
        // We have a weather query and have located the cityId
        CallSomeWeatherAPI(cityId);
    }
}


text:
Q: Surjectivity for permutation representation of a group action I am having trouble proving that my function is surjective. Here is the problem statement:
Problem statement: Let T be the tetrahedral rotation group. Use a suitable action of T on some set, and the permutation representation of this action, to show that T is isomorphic to a subgroup of $S_4$.
Outline of my attempt at a proof:
Let $S$ be the set of faces of the tetrahedron. There exists a homomorphism $f:T$ $\rightarrow$ (permutations of the faces). There are $4$ faces, so $|Perm(|4|)| = 24$. We want to show that $T$ is a bijection, and show the faithfulness of $f$. Well, $|Ker(f)|=1$, because no rotation fixes all faces. So $f$ is injective. Also, the class equation for $T$ is $12 = 1+3+4+4$, which admits no "subsums" to $6$, implying that there are no odd permutations because $T$ has no subgroup of index $2$. So $T \approx A_4$, which is a subgroup of $S_4$.
The thing that evades me is how to prove that $f$ is surjective?

A: The easiest way to do this would be to use the Orbit-Stabilizer Theorem.
$$
|G|=|\text{orbit}||\text{stabilizer}|
$$
Think about the action of a permutation on the tetrahedron. Draw a particular tetrahedron. How many rotations of the tetrahedron fix one of its faces?

There are 3

Then what is the orbit for that particular tetrahedron?

 There are 4

So then the group has order?

 The group has order 12.

To show that the group is $A_4$. Since we have already have an action of permutations, we need to show that we can only have even permutations of the "correct" order. I'll leave you to flesh out the details. But first ask why there can be no element of order $12$ in the group

 There can be no element of order $12$ as then the group would be cyclic--Clearly not the case!

Finally, why are there no elements of order $6$?

 It is a permutation of the FOUR faces of the tetrahedron.

Then finally, ask yourself, why does this only leave the subgroup $A_4$ of $S_4$?


text:
Q: Javascript checkbox increment and decrement What i want is that when a user click a checkbox in otherwords uncheck decrement when check it increment.
echo "<input type=checkbox name='check1' id='check1' value='".$info['eventCategory']."' onclick=if(this.checked){recal(" . $info['totalEvents'] . ",true)} else if(!this.checked){recal(" . $info['totalEvents'] . ",false)}   checked>	" . $info['id'] . "      " . $info['name'] . "	";

i wrote above code and
Only true statement is works

What i want  is to execute also else statement. I mean when user uncheck it must also decrease the number.
Thank you.

A: This works for me :
echo <input type=checkbox name='check1' id='check1' value='".$info['eventCategory']."' onclick="recal(" . $info['totalEvents'] . ",this.checked)" checked>"


text:
Q: incompatible types required: int found: java.lang.String (basic programming) I have come across this error a few times, and I try many things to fix it, but I can't seem to find out what is going wrong. here is the code:
import java.util.Scanner;
public class InputExample {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String name1 = scan.nextLine();
        String name2 = scan.nextLine();
        int num1 = scan.nextLine();
        double num2 = scan.nextLine();

        System.out.println("Employee Name:" + name2 + name1);
        System.out.println("Age:" + num1);
        System.out.println("Salary:" + (double)num2);
    }
}

And the error that shows up specicfically is:

[File: /InputExample.java Line: 9, Column: 25] incompatible types required: int found: java.lang.String
[File: /InputExample.java Line: 10, Column: 28] incompatible types required: double found: java.lang.String

A: You're reading in a String, but want to save it as Integer/Double. Try this:
int num1 = Integer.valueOf(scan.nextLine());

Same goes for Double.
Or as OldCurmudgeon mentioned:
int num1 = scan.nextInt();


text:
Q: Where to find quality audio samples for looping I am working on a musical instrument app for iPhone and need sample sounds that I can use for the various wind instruments. I'll be using OpenAL with looping, so a 1 second sample that is spot-on in-tune and without vibrato or other variation is essential.
My question is: Where can I find audio samples that are, or can be converted to .CAF format for looping play? Need these to be "realistic" sounding, not electronic sounding. Not looking for freebie, looking for professional quality.
Thanks in advance!

A: Here's the command for converting to CAF format:
/usr/bin/afconvert -f caff -d LEI16@44100 myaudiofile.wav myaudiofile.caf;

Regarding finding samples, there's a ton out there. Search Google with "free audio samples".
Magazines like Sound On Sound and Computer Music will often have deals. Although sometimes you'll need to buy the magazine, or be a subscriber. They do lots of reviews of commercial sample CDs. Often these are quite reasonably priced (e.g. $50).
As with everything, the key is to check the license carefully to make sure it's full use and that you can redistribute in your app. That also applies to samples that you can download for free.


text:
Q: Access host on network B from machine on network A My notebook has IP 1.1.1.1 and has a wired connection to another machine B that has IP 2.2.2.2. I don't have access to machine B because I locked myself out of it.
How do I have to setup routing on my notebook so I can connect to machine B?
My notebook runs Debian 9.2.

A: If they are wired without any routers in between (are in the same network segment) but aren't in the same subnet you need to setup routes on both devices that inform the OS that the other IP address is directly reachable via an interface. I assume your network interface is eth0.
On the notebook you need to execute
ip route add 2.2.2.2/32 dev eth0

On machine B you need to execute
ip route add 1.1.1.1/32 dev eth0

If both addresses are in the same subnet, the devices will automatically know that they can reach each other through interface eth0. Then these commands aren't neccessary.
EDIT: If you have no access to machine B you need to set up an address on your laptop in the same subnet as machine B.
If machine B is in subnet 2.2.2.0/24 your laptop needs an address in the range 2.2.2.1 - 2.2.2.254. You need to check how large the subnet is and add an unoccupied address in that subnet to your laptop's network interface. For example:
ip addr add 2.2.2.42/24 dev eth0


text:
Q: ImageMagick MVG vs. SVG -- graphic context I am currently porting some app of me from ImageMagick MVG to SVG output. I made heavily use of the "push graphic-context" command of MVG and now wonder, what's the equivalent to this in SVG?
What "push graphic-context" does is in short (copied from some other source):
When a graphic context is pushed, options set after the context is pushed
(such as coordinate transformations, color settings, etc.) are saved to a
new graphic context. This allows related options to be saved on a graphic
context "stack" in order to support hierarchical nesting of options. When
"pop graphic-context" is used to pop the current graphic context, the
options in effect during the "push graphic-context" operation are restored.

Is the equivalent to use nested SVG documents, like the following example?
<svg>
    ...
    <svg>
        ...
    </svg>
    ...
</svg>

or should i use something else?
Thanks in advance!

A: You can use either <svg> or <g> elements for this, I'd recommend <g> elements unless you need a new viewport - in that case go for <svg>.


text:
Q: rewrite from http to https i have some weeks been struggeling with setting up my domain. First off there was problems to show my files under the wwwroot. That got fixed with this line of code:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{REQUEST_URI} !wwwroot/
RewriteRule (.*) /wwwroot/$1 [L]

Afterwords I found out that my domain not was a https. Therefore I enabled the SSL on my domain, and a person from the support said I had to add the following code:
RewriteEngine on
RewriteCond %{REQUEST_SCHEME} http [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]

But as I see it that is not working, and I really do not know how to solve this? I am thinking the two pieces of code has to be written together?
Update
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{REQUEST_URI} !wwwroot/
RewriteRule (.*) /wwwroot/$1 [L]

RewriteEngine On
RewriteRule ^apache-redirect-http-to-https\.html$ example.com/apache-redirect-http-to-https.html [R=301,L]


text:
Q: Can I use JNDI to share a MongoClient instance? I'm using Jetty for a web server. I have built a custom LoginService/realm that uses MongoDb to get users. This LoginService is in it's own jar and is on the jetty server container's classpath.
I also want to use MongoDb in my web application. Normally, for SQL, you would set up a connection pool shared via JNDI. Can I do something similar with MongoDb?
Each MongoClient manages a connection pool. Can I store arbitrary objects in JNDI (ie. a MongoClient instance) or do I have to use the ObjectFactory interface?
If I have to create some kind of ObjectFactory, can I basically turn it into a singleton and return the same instance of MongoClient?
I don't fully understand JNDI because there are few resources out there that really explain the magic of it, so I may not even be asking the right questions.

A: You need something like this in your server.xml:
<mongo id="mongo">
    <hostNames>YOUR.MONGODB.HOSTNAME.HERE</hostNames>
</mongo>

<mongoDB databaseName="YOUR_DATABASE_NAME" jndiName="mongo/mongodb" mongoRef="mongo"/>

Then in your java class:
@Resource(name = "mongo/mongodb")
DB mongoDB;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  DBCollection table = mongoDB.getCollection("YOUR_TABLE_NAME");
  // etc.
}


text:
Q: show that the function $f(x)= \frac{x^2+1}{x+1}$ is continuous at the point $x_0=1$ Here is my attempt.
So starting with $f(x_0)=f(1)=1$ and $\epsilon >0$, I want to find $\delta >0$ such that if $|x-1|< \delta$ I get $|f(x)-f(x_0)| \leq \epsilon$.
I started studying $|f(x)-f(x_0)|$ as follows
$|f(x)-f(x_0)|= |\frac{x^2+1}{x+1}-1|= |\frac{x^2-x}{x+1}|= |x \frac{x-1}{x+1}| \leq |\frac{x}{x+1}| \delta$
But now I cannot find a way to conclude. I want to find an upper bound for $|\frac{x}{x+1}|$ and then find an expression for $\delta$ in terms of $\epsilon$
$|f(x)-f(x_0)|= |\frac{x}{x+1}| \delta \leq \frac{(\delta +1)\delta}{2- \delta}$
From now on I tried to set $ \frac{(\delta +1)\delta}{2- \delta} = \epsilon$ and solve for $\delta$ but this didn't work.
I then noticed that $\frac{(\delta +1)\delta}{2- \delta} \leq \frac{(\delta +1)^2}{2- \delta}$ from where I tried solving $\frac{(\delta +1)^2}{2- \delta}=\epsilon$ but again, I failed to find an applicable solution.
I have the feeling that I am near but somehow I cannot see how to overcome the difficulty.
Thank you for your help.

A: Unfortunately, $$\frac{x}{x+1}=1-\frac1{x+1}$$ is an unbounded function, so that $\left\lvert\frac{x}{x+1}\right\rvert$ has no upper bound. However, we can bound it by making sure that $x$ is bounded away from $-1,$ at which the function has its vertical asymptote. Fortunately, this isn't an issue, since we want to keep $x$ near $1,$ anyway.
So long as $x$ is positive, $\frac{x}{x+1}$ will be positive, as well, and necessarily less than $1.$ Can you see why?
Consequently, picking some arbitrary $\alpha\in(0,1),$ we need only make sure that $\delta=\min\{\alpha,\epsilon\},$ at which point we'll have $$\left\lvert\frac{x}{x+1}\right\rvert\delta<\delta\le\epsilon$$ whenever $|x-1|<\delta,$ which completes the proof.

A: You could choose a $\delta$ which ensures both $|\frac{x}{x+1}| < 1$ and $\delta < \epsilon$ so you can easily extend the steps in your first line of workings.
It can be shown that $|\frac{x}{x+1}| < 1 \ \text{if and only if} \ x > -\frac 12$, and we know $ 0 < |x-1| < \delta \iff 1 - \delta < x < 1 + \delta$ and $x \neq 1$. Therefore, we want a $\delta$ such that $1 - \delta \geq -\frac 12 \iff \delta \leq \frac 32$.
We have narrowed down our requirements for $\delta$ to

*

*$\delta \leq \frac 32$

*$\delta < \epsilon$

*$\delta > 0$
I would then suggest finding a function of a real positive variable which satisfies these conditions.
An example of such $\delta$ is $\delta = \frac{\epsilon}{\epsilon+1}$.
$\textbf{Edit}$: It is fine to relax the condition $\delta < \epsilon$ to $\delta \leq \epsilon$ as shown in Cameron's answer.


text:
Q: FlatList in React Native does not render when only one item I'm trying to render item using FlatList in React Native project. So my problem is when I render 2 items I can see the result but when there is only on item in my data array they is no result on my screen any idea why this is happening?
 const data = this.getListPrise()

 <View>
    <View style={styles.allPAge} >
       <View style={styles.centerText}>
          <Text style={styles.text}>Voici vos differentes capture </Text>
        </View>
        <View  style={{flex: 1}}>
        <FlatList
          data={data}
          renderItem={({ item }) =>
            <TouchableOpacity style={styles.container}  onPress={() => this.modifCapture(item)}>
              <Image style={styles.mark} source={avatar}></Image>
              <View style={styles.displayUnder}  >
                <Text style={styles.textCapture}><Text style={styles.textCaptureTitle}>Espèce </Text>: {item.espece}</Text>
                <Text style={styles.textCapture}><Text style={styles.textCaptureTitle}>Date </Text>:
                      {moment(item.date).format(" D MMMM  YYYY, h:mm:ss")}</Text>
                <Text style={styles.textCapture}><Text style={styles.textCaptureTitle}>Poids </Text> : {item.poids} kg</Text>
              </View>
            </TouchableOpacity>
          }
          style={{ flex: 1, flexDirection: 'column', padding: 1 }}
        />
        </View>
         <ActionButton buttonColor="rgba(231,76,60,1)" onPress={() => this.Addfish()}></ActionButton>
       <View>

    </View>
      </View>

    </View>


text:
Q: Unable to click below overlay on Android 12 I have an app called Migraine Relief: Green Dimmer on the play store. This app basically creates an overlay on top of all the apps with green color, which is known best for Migraine soothing.
It works perfectly for anything below Android 12. But, since Android 12 it no longer works. I can still interact with my application, but once minimized I no longer can click on anything or change anything at all. I have to restart the device to close the application.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                 FLAG_NOT_TOUCH_MODAL | FLAG_NOT_TOUCHABLE | FLAG_NOT_FOCUSABLE | FLAG_LAYOUT_IN_SCREEN ,
                PixelFormat.TRANSLUCENT);

    }

This is how I create the overlay on top. I checked the documentation, but could not find any information. I will be grateful if I can get any help and suggestions to fix this issue.


text:
Q: Getting an error "COPY failed: stat /home/app/target/Service.jar : file does not exist" in multistage docker build My Docker File is,
FROM maven:3.6.0-jdk-11-slim AS build

COPY src /home/app/src

COPY pom.xml /home/app

RUN mvn -f /home/app/pom.xml clean package

FROM openjdk:11-jre-slim

COPY --from=build /home/app/target/Service.jar /usr/local/lib/Service.jar

EXPOSE 8081

ENTRYPOINT ["java","-jar","/usr/local/lib/service.jar"]

When executing COPY --from line, getting an error "COPY failed: stat /home/app/target/Service.jar : file does not exist".
Note: when we execute "RUN ls /home/app" command, its listing Files and target directory .
Could someone help on this.

A: Do you have a finalName defined in your pom?
<build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
...

if not the resulting artifact will have versioning in the name and will not be called Service.jar but something like Service-1.0-SNAPSHOT.jar
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app/pom.xml
WORKDIR /home/app
RUN mvn clean package

FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/Service_AND_VERSION_STUFF.jar /usr/local/lib/Service.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","/usr/local/lib/Service.jar"]

don't forget to always use the same casing (Sevice != service)


text:
Q: Can't run app exe on other machines, python2.7, fpdf, pyinstaller I have an issue with running exe application from pyinstaller on other machines. It is looking for path on PC, where I built application:
console output
I use and added font in pyPDF in following way:
from fpdf import FPDF

pwd = os.path.realpath(os.path.dirname(sys.argv[0])) + "\\font\\DejaVuSansCondensed.ttf"

pdf = FPDF(orientation = 'L', unit = 'mm', format='A4')
pdf.add_page()
# Add a DejaVu Unicode font (uses UTF-8)
# Supports more than 200 languages. For a coverage status see:
# http://dejavu.svn.sourceforge.net/viewvc/dejavu/trunk/dejavu-fonts/langcover.txt
pdf.add_font('DejaVu', '', pwd, uni=True)
pdf.set_font('DejaVu', '', 18)
#then I use pdf.write() to write data
#save and close pdf file
pdf.output('C:\\Users\\' + getpass.getuser() + '\\Documents\\pdf_file' + time_stamp + '.pdf', 'F')

I tried to build it in following ways:
pyinstaller app.py
pyinstaller --onefile app.py

There is no issue on machine, where I build code. I suppose there is something in output method from fpdf or settings of pyinstaller, am I right?
I have to create pdf with unicode characters. I use latest versions of fpdf and pyinstaller modules.
I will be thankful for any help.
Thank you in advance,

A: There is no issue when you build it on your machine since you have DejaVuSansCondensed.ttf where python expects it to be. But when you compile with PyInstaller and run it on another system, it is looking in the same spot (which may not exist on other systems).
What I would suggest is to copy that ttf file to your current working directory and update the line font line to (or something similar that fits your code):
pwd = "DejaVuSansCondensed.ttf"

You also have to make sure that the .exe has access to that file, independent of system (relative to the exe). So you have to copy the ttf file to the same directory as your exe so that when you run it on another computer, your code will look in the directory that the exe is in and find the ttf file.


text:
Q: How do you use awk to set column position? My problem is pretty simple, but I can't seem to find a solution after searching. I had a short line of code that I used previously for this but sadly have lost the code and knowledge to build it again myself.
I need an awk code to ensure the second column in a dataframe always starts at the 10th position. So, for example, with a normal single space delimiter, my data would look like:
123987 9876653
123456 6519849
234567 6516515
5648 6516578
123 7896511

What I want to achieve is this:
123987   9876653
123456   6519849
234567   6516515
5648     6516578
123      7896511

Thanks for any help!

A: To start the 2nd field in column 10 you can force the 1st field to take up the first 9 columns, eg:
$ awk '{printf "%-9s%s\n",$1,$2}' data
123987   9876653
123456   6519849
234567   6516515
5648     6516578
123      7896511


text:
Q: Sustainsys.Saml2 start authentication dynamically for ASP.NET Hello I try to SMAL integration with Sustainsys.Saml2. I develop an web application with ASP.NET (not MVC or Core). This web application is service provider for SAML.
I changed the my config as in the example. Now I need to start authenticate in my login page and redirect to identity provider's page. In this page they say for ASP.NET web forms "In many cases it should just be configured in the web.config file and work without any code written in the application at all". But authentication not start automatically.
I run MVC example and see this line in Index.cshtml
Sign in - default IDP
@foreach (var idp in Sustainsys.Saml2.Configuration.SustainsysSaml2Section.Current.IdentityProviders)
{
    var entityId = idp.EntityId;
    var destinationUrl = idp.SignOnUrl;

    Sign in@: - @entityId - @destinationUrl
}

If I click this link it redirect to identity provider's page. How can integrate this for ASP.Net and start authentication for ASP.Net?

A: You should use the HttpModule with Web forms. To start authentication redirect the user to /Saml2/SignIn.
Or protect the entire application with automatic redirection by settings in web.config:

*

*Authentication mode Forms with a login url of /Saml2/SignIn

*Set Authorization rules in web.config to disallow anonymous access to all pages.


text:
Q: How to embed WebContent in Liferay Is that it is possible embed web content in a template velocity?
I have two web contents and I want to unite the two into a single one.
I tried this:
#set ($webcontent-id = "13054")
#set ($webcontent=$journalContentUtil.getContent($group_id, $webcontent-id,null,"$locale",$theme_display))
<div> $webcontent </div>
#set ($webcontent-id = "13065")
#set ($webcontent=$journalContentUtil.getContent($group_id, $webcontent-id,null,"$locale",$theme_display))
<div> $webcontent </div>

However, it displays the variable. I think I did not access the service in a webcontent.

A: Web content templates do not have access to the ThemeDisplay directly. They can access request information via the $request map, which contains among other things variables from ThemeDisplay. This wiki page lists the variables that can be used from templates.
Also, when calling Liferay services from velocity templates you need to make sure that all arguments have the correct type. You can use $getterUtil to accomplish this, for example to convert a String to Long.
Here's a revised version of your example:
#set ($group_id = $getterUtil.getLong($request.theme-display.scope-group-id))
#set ($webcontent-id = "58007")
#set ($webcontent=$journalContentUtil.getContent($group_id, $webcontent-id, "", "$locale", ""))
$webcontent


text:
Q: GNU make rule for multiple targets I'm trying to get GNU make to produce multiple outputs from a single input. The most simple example I can demonstrate is:
a b : test
    cp $< $@

which, I believe, should copy the file test to the files name a and b. However, it only makes the file a, which seems to me to be contrary to the instructions listed here:
http://www.gnu.org/software/automake/manual/make/Multiple-Targets.html
Am I doing something wrong?
Thanks,
Tom

A: If you run a rule that depends on a, it will run your rule with $< as test and $@ as a. If you run a rule that depends on b, $@ will be b instead. If you make a rule above your current rule like:
all: a b

It will run the rules for a and b, which is that same rule twice. Otherwise, if your rule is the first in the file it will run it with the first target only, which is a

A: A small clarification to @MichaelMrozek's answer.
This:
a b : test
    cp $< $@

Is exactly the same as:
a : test
    cp $< $@
b : test
    cp $< $@

a is the first target in the file, so it's the default target.  Only the rule for a runs, since there's no dependency on b.
Like @MichaelMrozek said, you can add another rule, or you can run
make a b

A: Everything is OK. The manual says :
bigoutput littleoutput : text.g
        generate text.g -$(subst output,,$@) > $@

is equivalent to
bigoutput : text.g
        generate text.g -big > bigoutput
littleoutput : text.g
  generate text.g -little > littleoutput

So your Makefile is also equivalent to
a : test
    cp $< $@
b : test
    cp $< $@

and when you'd entered the command 'make', the program defaulted to build the first target, i.e. 'a'.