text:
Q: Struts2 field validator - Validate multiple fields together As part of my project I have the credit card month and year as two different fields,
<field name="expiry-month">
    <field-validator>
        ...
    </field-validator>
</field>
<field name="expiry-year">
    <field-validator>
        ...
    </field-validator>
</field>

Now, I want to validate the values of these two fields as together so that the credit card expiry month and year are not in past.
How can I do that within XML?
Thank you.


text:
Q: Have z-index issue with IE bug - CSS I am struggling with z-index for popup (newsletter signup) and it is still underneath the navigation and its dropdown. I googled and found out that relative + zindex gives IE bug but I added in z-index and they either go under or top of each other. Right now I cannot figure why it is behaving weird.
I am wondering whether the header and the navigation are conflicting with each other in z-index? Any suggestion or anything will be appreciated. thank you

A: To #header, add z-index: 101.
It's 101 because something has a z-index of 100: I suspect it's div.col-left.
I forget the exact details of the IE bug in question, but the fix in this case is applying a higher z-index value to the parent element.

redpajama_set_name: RedPajamaStackExchange


text:
Q: kubernetes production deploy docker multi-node or ubuntu bare metal? We are currently trying out docker multi-node and need recommendations on production deployment docker or bare metal on ubuntu?

A: The getting started guides using docker (both the single and multi-nodes examples) are not meant to be used in a production deployment. They are meant to provide the lowest friction path to getting a cluster running where you can experiment with the Kubernetes concepts in a running cluster.
If your choices are between running a variant of the docker multi-node configuration and bare metal on Ubuntu, I would definitely recommend running on Ubuntu. See the Kubernetes Deployment On Bare-metal Ubuntu Nodes getting started guide.


text:
Q: How to fix invalid syntax error in definition of inner functions in Python? The below code throws an invalid syntax error in line 12:

'def run():'  is invalid syntax.

I don't see any mistake I could possible make there.
def removelastodd(numbers):
        odd = []
        flag = False
        for num in numbers:
            if num % 2 == 1:
              flag = True
              odd.append(num)
        if flag:
          return numbers.pop(odd.index(odd[-1])

    def run():
      numbers = [1, 7, 2, 34, 8, 7, 2, 5, 14, 22]
      removelastodd(numbers)

    run()

A: Try this method :
def removelastodd(numbers):
    nums=[]
    flag=False
    for i in numbers[::-1]:
        if i%2==0:
            nums.append(i)
        elif i%2==1:
            if flag:
                nums.append(i)
            flag=True
    return nums[::-1]

def run():
    numbers = [1, 7, 2, 34, 8, 7, 2, 5, 14, 22]
    print(removelastodd(numbers))

run()

Output:
[1, 7, 2, 34, 8, 7, 2, 14, 22]


text:
Q: Is there a way to designate some HTML content as not managed by jQuery? In another question, I asked why it takes so long to remove HTML content from a page with jQuery.
Apparently when removing HTML content from an element, jQuery has to march through each element and do... something.. I don't know exactly what.  And this can take a vvery long time for large-ish HTML content.
In an effort to side-step the problem, I'm wondering:
Is there a way to add dynamic HTML content to a page, that uses jQuery, but NOT allow jquery to "adopt" the content?
In other words I want some subset of the HTML content in a page to be outside of the purview of active management by jQuery.
In this particular case, the content is within a jQuery accordion.  So I want the accordion to work, but for everything beneath the divs for the accordion panels, I want jQuery to not be aware of those things. The goal is to short-circuit the very lengthy process it takes to remove that content, later.
Does this make sense?
possible?
What if, instead of doing something like  $('#elementid').html(content), I just used the innerHTML property on the element itself, using document.getElementById()  Would that keep jQuery out of the subcontent?
I guess I'll try it, but if anyone has any insight, I'd appreciate it.

A: If it is in the DOM, the jQuery knows about it.

A: It does sort of make sense but sidestepping it is going to be ugly.
The first thing that came to mind was embedding your content with iframes. I'll freely proffer that this is an absolute abomination of an idea, but it should work as it should be a whole new document and thus a whole separate DOM.

A: Is it important that this content be kept?  If they are visible elements, you could simple hide() them instead.


text:
Q: Which Java library contains the javax.faces.webapp.FacesServlet class? I'm working on a NetBeans project and can't seem to get my website to run properly because my internal Apache Tomcat server keeps returning an error that it cannot load the FacesServlet class. Which available library contains this? Currently I have the Java EE Web 7 API and Java DB libraries loaded on.

A: Oh, just now found out it was under the JSF 2.2 library! Sometimes it just pays to ask to think more about it! :)

A: You use service like findjar to find jars that contain some class:
http://www.findjar.com/class/javax/faces/webapp/FacesServlet.html


text:
Q: how can a single command take stdin in one program and filename in other What i'm trying to do is pass argument into the second program in such a way that it takes cmdline-args and is opened with sudo but doesn't have anything to with stdin that i pass to sudo.
Below is an example to understand what i'm trying to do.
echo "mypass" | sudo -S nvim "filename"

Here sudo must take stdin and nvim must take a file-name from cmdline-arg. But nvim opens an unnamed file and puts stdin into that file and doesn't even care about the args i pass to it.
My end goal is not to only open file without entering password but to understand how can i pass arguments the way i want to
Is it even possible?

A: Exactly as you have it seems like it ought to work.
Maybe try a bash call explicitly. That works even if you need a separate input redirection.
$ echo "$pw"|sudo -S bash -c "head -3 < foo"
0
1
2

If you need to pass a file argument, maybe explicitly bind your stdin elsewhere.
$ echo "$pw"|sudo -S bash -c "head -5 foo </dev/null"
0
1
2

A: Since the sudo password doesn't need to be repeated for two consecutive sudo commands, I should issue two sequential commands:
echo "mypass" | sudo -S -v
sudo nvim "filename"         # will not prompt for password this time

Explanation: sudo -v just updates the credentials of sudo without executing any command.

A: Simply pass the filename as first argument of your script:
echo "<your password>" | sudo -S nvim "$1"

and call the script with:
./script.sh myfile.txt

Note that the -S option of sudo behaves differently depending if the credentials are already cached or not. Better also use the -k option to invalidate the credentials:
echo "<your password>" | sudo -k -S nvim "$1"


text:
Q: C++/Qt defining/undefining QT_NO_SESSIONMANAGER macro I want to compile QGis which requires QApplication to have commitData() as well as saveState() member functions. Thought, they are put in a preprocessor if statement:
#ifndef QT_NO_SESSIONMANAGER
void commitDataRequest(QSessionManager &sessionManager);
void saveStateRequest(QSessionManager &sessionManager);
#endif

But QT_NO_SESSIONMANAGER is defined and these functions are not declared, nor defined. When I #undef the macro in the qapplication.h, I received undefined reference errors. So, it seems that I should resolve the problem in another way.
I doubt if there have been a problem with Qt configuration I've used, because the session manager is defined in prebuilt Qt libraries, but it is not in the Qt I compiled Qt v4.8.2.2. It is also possible that I should send some arguments to qmake or gcc to define/undefine this macro. I searched a while for related material on the net & stackoverflow, but I found no answer.

A: It is a problem with your Qt configuration. It seems your compiled Qt without Session management support (Support X Session Management, links in -lSM -lICE).
Probably, you do not have the sm-dev library installed on your system:
dpkg -l | grep libsm-dev
sudo apt-get install libsm-dev
Try again to compile your Qt's sources. Make sure Session management is enabled (yes) when you run qt's configure.


text:
Q: The slideshow and the zoom function is not working anymore of fetching content I have an images slideshow which each images can bee zoomed in the slideshow. And all the codes I used was working fine before I added some change there.
Here is the working code:

In the working code, all the content in the #bigPicture div is set maually, and the slideshow is run by this script:
var $el = $('#leftBigWraper'),

//  SETUP  ////////
F = 600 ,    // Fade Time
P = 5000 ,   // Pause Time
C = 0 ,      // Counter / Start Slide# (0 based)
///////////////////

$sl = $('#bigPicture > div'),
$th = $('#smallPicture > img'),
N = $sl.length,
T = 10000;

$sl.hide().eq(C).show();
$th.eq(C).addClass('on');

// ANIMATION
function anim() {
   $sl.eq(C%N).stop(1).fadeTo(F,1).siblings().fadeTo(F,0);
   $th.removeClass('on').eq(C%N).addClass('on');
}

// AUTO ANIMATE
function autoAnim() {
   T = setTimeout(function() {
   C++;
   anim();     // Animate
   autoAnim(); // Prepare another iteration
  }, P+F);
}

autoAnim();      // Start loop

// HOVER PAUSE
$el.hover(function(e) {
   return e.type==='mouseenter'? clearTimeout( T ) : autoAnim();
});

// HOVER THUMBNAILS
$th.on('mouseenter', function() {
   C = $th.index( this );
   anim();
});

THE WORKING FIDDLE

However, when all the contents in the #bigPicture div are set by calling it from hidden div and with Jquery, the slideshow and the zooming function is not working anymore.
The Jquery that I used to fill the blank div from the hidden div is here:
$(document).ready(function(){
      $('#bigPicture').html($('#pilihWarna li #bigHidden:first').html());
      $('#smallPicture').html($('#pilihWarna li #smallHidden:first').html());

   $('#pilihWarna li').click(function(event) {
      $('#bigPicture').html($(this).find('#bigHidden').html());
      $('#smallPicture').html($(this).find('#smallHidden').html());
   });
});

As follows:

First, I left the div of #bigPicture to be blank or without any content in there.

Then, I create some hidden div that will transfer all the contents insede the div to the #bigPicture div.

The ul which its id is #pilihanWarna has at least 5 li, which I used as clickable menus that I have been discussing here
That's when the slidshow and the zooming images functions are not working anymore.

A: You're using the same IDs multiple times, IDs should be unique. Given multiple elements with the same ID:

One

Two

Three

Searching the DOM for the elements will only ever return the first instance:
document.getElementById('foo'); // returns
One

Start by removing the duplicated IDs and using a different selector (a class probably, but you could just use an element selector too) and then you might be getting somewhere.


text:
Q: Disable 10 seconds timeout on BroadcastReceiver. Android Development I have a IncomingSmsReceiver class that receives a sms message but the problem is it takes a while to receive the text message, I know that the BroadcastReceiver class automatically stop the process if it's listening for more the 10 seconds, is there any way to disable this?
heres my code:
public class IncomingSmsReceiver extends BroadcastReceiver {

private ShowDialogInterface callback;

public void onReceive(Context context, Intent intent) {

    if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
        String messageBody = "no data";
        String messageFrom = "no data";
        for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
            messageBody = smsMessage.getMessageBody();
            messageFrom = smsMessage.getDisplayOriginatingAddress();
        }

        if(callback != null) {
            callback.smsDetails(messageFrom, messageBody);
        }
    }
}

public void registerReceiver(ShowDialogInterface receiverCallback) {
    this.callback = receiverCallback;
}

// Show different UI elements to notifying the user of an incoming SMS
public interface ShowDialogInterface {
    void smsDetails(String from, String message);
}
}

Here is my debug error:
enter image description here
Best Regards,
Noob Android_dev

A: You can start service from your BroadcastReceiver and do all job in it. It's a standard way to do such things.


text:
Q: JQuery audio source undefined I'm trying to play an mp3 when a button is clicked.
The following error occurs: TypeError: dontlose is undefined
Jade:
audio#actrl(preload="auto")
      source(src="sound/quickscope.mp3",type="audio/mpeg")
      source(src="sound/dontloseyourway.mp3",type="audio/mpeg")
      source(src="sound/blumenkranz.mp3",type="audio/mpeg")
      No audio for you!

JQuery:
$(document).ready(function(){
  var dontlose= $("#actrl")[1];
  $("#1").click(function(){
    dontlose.play();
  });
});

A: You obviously have multiple ID's or are forgetting that indexes start at 0, which is causing an issue. This line:
var dontlose= $("#actrl")[1];

makes no sense. The ID selector expects 1 result, therefore the [1] will return undefined. You should use [0] to get the actual element, or use getElementById


text:
Q: Get error while using extend-chrome/messages while sending messgae from background script to content script I am using this library for messaging.
I have my background script like this
import { sendUrlInfo, waitForUrl } from 'utils/messaging';
import URL from 'url-parse';

chrome.webNavigation.onHistoryStateUpdated.addListener((details) => {
  const url = new URL(details.url);
  console.log('sending', url.hostname, url.pathname);
  sendUrlInfo(new URL(details.url));
});

chrome.webNavigation.onCompleted.addListener((details) => {
  if (details.url !== 'about:blank') {
    const url = new URL(details.url);
    console.log('sending', url.hostname, url.pathname);
    sendUrlInfo(new URL(details.url));
  }
});

And according to documentation i have message.js as shown below
import { getMessage } from '@extend-chrome/messages';
import URL from 'url-parse';

const messageTypes = {
  URL_INFO: 'URL_INFO',
};

export const [sendUrlInfo, urlStream, waitForUrl] = getMessage<URL>(
  messageTypes.URL_INFO,
);

and now content script I have written in react
So i am trying to subscribe to stream when the component is mounted
import React, { useState, useEffect, useRef } from 'react';

import Editor from 'content/components/Editor';
import Opener from 'content/components/Opener';
import { urlStream, waitForUrl } from 'utils/messaging';

const Main: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [showContent, setShowContent] = useState(false);

  const editorRef = useRef<HTMLTextAreaElement | null>(null);

  useEffect(() => {
    console.log('MOunted');
    urlStream.subscribe(([url]) => {
      console.log('Received', url.hostname, url.pathname);
      if (url.hostname === 'www.youtube.com' && url.pathname === '/watch') {
        if (!showContent) setShowContent(true);
      } else {
        if (showContent) setShowContent(false);
      }
    });
  }, []);

  useEffect(() => {
    document.addEventListener('keydown', onKeyPress);
    return () => {
      document.removeEventListener('keydown', onKeyPress);
    };
  });

  const onKeyPress = (e: KeyboardEvent) => {
    if (e.ctrlKey && e.which === 192) {
      e.preventDefault();
      setIsOpen(!isOpen);
    }
  };

  if (!showContent) return <></>;

  return (
    <>

test

      <Opener isOpen={isOpen} onClick={() => setIsOpen(true)} />
      <Editor
        isOpen={isOpen}
        ref={editorRef}
        onClose={() => setIsOpen(false)}
      />
    </>
  );
};

export default Main;

The error I am getting in background script console is

Could not establish connection. Receiving end does not exist

I think as much as i understand the background script is trying to send msg but the content script observable is not subscribed yet. As content script run after the page is loaded.
If this is the issue is there any way to use this library properly.
BTW this works if we use normal chrome api like this
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(
        tabs[0].id,
        message,
        function () {
                console.log("msg sent")
        }
    );
});

and use onMessage to receive the msg.

A: The background page needs to know that we're sending a message to a tab. Unless options.tabId is defined, sendUrlInfo sends a message using chrome.runtime.sendMessage.
Add the options argument to sendUrlInfo in the background script:
chrome.webNavigation.onHistoryStateUpdated.addListener((details) => {
  const url = new URL(details.url);
  console.log('sending', url.hostname, url.pathname);

  const options = { tabId: details.tabId }; // Add options.tabId here
  sendUrlInfo(new URL(details.url), options);
});


text:
Q: Jquery Mobile - disabled dialog on page load? I have an initial init page in my application that acts as an entry point and loads my login page.
<!DOCTYPE html>

<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-      1.3.0.min.css" />

When my login page loads there is a button which loads a dialog. This button initially doesn't work and only loads the dialog when the page is manually refreshed. Why does this happen and what can I do to enable the button/dialog immediately upon page load.
<!DOCTYPE html>

  <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />

  <link rel="stylesheet" href="../css/global.css" />
  <link rel="stylesheet" href="../css/login.css" />

    Settings

A: Not sure if you've fixed this but it seems to be something to do with the DOM cache & AJAX.
I'm not sure how you'd do it, but try setting the ajax: false when you do the window reload. Alternatively you could redirect via server side (I'd recommend this as it'll still work if the user has JS turned off.
Why I figured this out was because I had a page with a list on it, the list items sent me to a new page which has a jump link on it (#settings_dialog). Setting the data-ajax="false" on each list item somehow 'refreshed' the DOM and forced the second page to load 'fresh' and voila - my dialog works 100% now.
So, in short, turn off the AJAX feature or (better) redirect from serverside & be happy!


text:
Q: validation on exact length of numeric field in laravel 5 I have numeric field i want to validate on exact fill 4 digits.
like: 1234, 4567,1245
but these invalid inputs:
like: 123, 346, 45m6, 34567
what I am trying:
'last4digits'             => 'numeric|between:4,4',

A: You are looking for the digits rule. From the docs:

The field under validation must be numeric and must have an exact length of value.

'last4digits' => 'digits:4'

A: in general case ,say, for a string with arbitrary characters:
'last_not_only_4_digits' => 'size:4'


text:
Q: Unable to generate the split values in new file The resulting file shows the year    0    0    0
eg 1985    0    0    0,
   1986    0    0    0 and so on.
It's not taking real values from given input file. I don't understand, where am I going wrong. I have 5 specific values in .txt files, such as file name, year, average max, average min and average precipitation.
The data in YearlyAvarage.txt:
USC00339312.txt     1985        14.11       3.96        100.67
USC00339312.txt     1986        15.09       5.13        94.76
USC00339312.txt     1987        15.66       5.28        81.15
USC00339312.txt     1988        15.22       3.66        89.82
USC00339312.txt     1989        14.48       3.98        101.83

My code:
import glob
import os
import sys

script_dir = os.path.dirname(os.path.realpath('__file__'))
path = os.path.join(script_dir[0:-3],'YearlyAverages.txt')
path1 = os.path.join(script_dir[0:-3],'YearHistogram.txt')
file_list = glob.glob(os.path.join(os.getcwd(), "wx_data", "*.txt"))
filelist = []

final_output = open('YearHistogram.txt', 'w')
for files in sorted(file_list):
    filelist.append(files.split('/')[8])

file = open('YearlyAverages.txt','r')
lines = file.read().splitlines()
row_sets = [[c for c in line.split()] for line in lines]
# print(row_sets)
data=[]

for f in filelist:
    subset = [row for row in row_sets if row[0] == str(f)]
    data.append(subset)

diction = {}

for dd in data:
    maxT = -sys.maxsize
    minT = sys.maxsize
    total = 0
    diction[dd[0][0]] = {}
    for result in dd:
        #print(result)
        if maxT < float(result[2]):
            maxT = max(maxT, float(result[2]))
            #print(maxT)
            tempMax = result[1]
            #print(tempMax)
        if minT > float(result[3]):
            minT = min(minT, float(result[3]))
            tempMin = result[1]
            #print(tempMin)
        if total < float(result[4]):
            total = max(total, float(result[4]))
            tempTotal = result[1]
            #print(tempTotal)
    diction[dd[0][0]]['max'] = tempMax
    diction[dd[0][0]]['min'] = tempMin
    diction[dd[0][0]]['total'] = tempTotal
    #print(diction)

for year in range(1985, 2015):
    maxtotal = 0
    mintotal = 0
    prectotal = 0
    for v in diction.values():
        if v['max'] == str(year):
            maxtotal = maxtotal + 1
        if v['min'] == str(year):
            mintotal = mintotal + 1
        if v['total'] == str(year):
            prectotal = prectotal + 1
    final_output.write(str(year) + '\t' + str(maxtotal) + '\t' + str(mintotal) + '\t' + str(prectotal) + '\n')


text:
Q: Zurb foundation last column overflows onto next line I've got a simple column layout using Zurb Foundation 5:

1

10

1

But below a certain width the last column breaks out onto the next line, even though there is plenty of room for all the content.
Demo here: https://jsfiddle.net/kqscrxpq/
Edit: I'd like to understand why it's doing this, particularly in light of the apparent free space still available, and then hopefully find an appropriate fix.

A: This is because the padding of small-1 column is fixed 30px in total and when width of small-1 column gets less than the padding, the column breaks to next line.
e.g if window size is 359px the size of column will be 8.333333 % of 359px = 29.91px which is less than the padding so the width of column will not be less 30px. The remaining space is 29.91px and 30px column will break to next line.


text:
Q: Are low volume products RoHS exempt in the EU? Are small companies that intend to sell less than 100 units in the EU market required to comply with RoHS?
This Forbes article seems to state that exemptions are possible till 2017?

REACH and RoHS both started with companies shipping high volumes of product into the EU, giving exemptions to lower-volume companies, but eventually all companies conducting business in Europe will need to comply (in most cases by 2017)."

(source)

A: In practice, it would be very difficult to get exempted, and wouldn't be worth the trouble in the case of electronic items.
Products also have to conform to the EMC requirements.

A: I've been doing my own research, and nowhere have I seen any reference to small-volume exemptions, unfortunately. e.g.
http://www.newark.com/pdfs/RohsTechManual_v2.pdf
http://www.bis.gov.uk/assets/nmo/docs/rohs/support-literature/nmo_technicalbrochure_acc4.pdf
http://www.bis.gov.uk/nmo/enforcement/rohs-home/due-diligence
(This and WEEE compliance really badly affects small-volume electronics in the EU, I think)


text:
Q: SSE2 instruction to load integers in reverse order Is there any SSE2 instruction to load a 128 bit int vector register from an int buffer, in reverse order ?

A: It's quite easy to reverse 32 bit int elements after a normal load:
__m128i v = _mm_load_si128(buff);                    // MOVDQA
v = _mm_shuffle_epi32(v, _MM_SHUFFLE(0, 1, 2, 3));   // PSHUFD  - mask = 00 01 10 11 = 0x1b

You can do the same thing for 16 bit short elements, but it takes more instructions:
__m128i v = _mm_load_si128(buff);                    // MOVDQA
v = _mm_shuffle_epi32(v, _MM_SHUFFLE(0, 1, 2, 3));   // PSHUFD  - mask = 00 01 10 11 = 0x1b
v = _mm_shufflelo_epi16(v, _MM_SHUFFLE(2, 3, 0, 1)); // PSHUFLW - mask = 10 11 00 01 = 0xb1
v = _mm_shufflehi_epi16(v, _MM_SHUFFLE(2, 3, 0, 1)); // PSHUFHW - mask = 10 11 00 01 = 0xb1

Note that you can do this with fewer instructions using _mm_shuffle_epi8  (PSHUFB), if SSSE3 is available:
const __m128i vm = _mm_setr_epi8(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1);
                                     // initialise vector mask for use with PSHUFB
                                     // NB: do this once, outside any processing loop
...
__m128i v = _mm_load_si128(buff);    // MOVDQA
v = _mm_shuffle_epi8(v, vm);         // PSHUFB

A: EDIT: (The following is for single precision floating point scalars, leaving it here just in case)
The most approximate (and handy) is _mm_loadr_ps intrinsic. Be aware the address must be 16byte aligned.
Although this intrinsic translates to more than instruction (MOVAPS + shuffling).


text:
Q: working with master and develop branch in Azure DevOps, avoiding the 1 ahead and 1 behind state of master We have an Azure DevOps repo with 2 remote branches: master and develop.
The develop branch is marked as the "Default" branch and also the "Compare" branch.
I have today completed a pull request to the remote "develop" branch from a local branch called ajf2 but I allowed this action to delete my local ajf2 branch (as per default of Azure DevOps).
The change is only a change to one file.
We are now keen to update the remote master branch.
The last time we did a pull direct from the remote develop to the remote master branch but this left the master branch with a 1 behind and 1 ahead status and an admin person then did a branch delete and recreate on the develop branch to resolve this 1 behind and 1 ahead status.
I have a strong feeling I was meant to pull from local ajf2 branch to master and then from ajf2 to develop before allowing local ajf2 branch to be deleted?
Maybe we shouldn't worry about the 1 behind 1 ahead type of status indication on master branch on Azure DevOps?
I have had a review of this article:
https://gitversion.readthedocs.io/en/latest/git-branching-strategies/gitflow-examples/
Am wondering what steps we can take from here, this time, to avoid the 1 behind and 1 ahead status that occurred last time we pulled directly from remote develop branch to remote master branch. I guess we could regard the master as now requiring a "hot fix" ?  I don't have access to mark the master branch as the default branch.
Fun with Git branches and repos !
I would like to learn the correct steps for working with both develop and master branch and local branches and avoiding this 1 behind and 1 ahead branch status on master.
Any advice / answers much appreciated !


text:
Q: Asset images not showing on release mode I'm hoping someone can give me a suggestion that helps.
I am updating an app I developed for my company 2 years ago, the issue is that almost all of the images in the assets folder do not show on screen when the app is launched manually by a user. When I run the app through XCode all my images appear normally, whereas when I tap on the app from the home screen most of the images do not load. The UI is still set and you can click on buttons that have image icons, but there is simply no image there. I am running the latest XCode 12.1 and supporting iOS 12 and up. Ive tried running this on the simulator and on devices running iOS 14, the same issue happens on both.
I have spent several days trying to figure out the problem, and haven't found many references online aside from issues with iOS 7 and with react-native.
What I've done

*

*remove target membership for the assets and reset to project's target

*removed and reset the asset catalog from "Copy Bundle Resources"

*cleaned (many times) and rebuilt the project

*deleted and replaced the asset catalog

*Moved all project files to another project (issue kept happening)

*Create a minimal reproducible example by just moving the images to another project, but assets behaved normally in that case

*deleted the app from devices/simulators and re-built

*quit & re-opened Xcode and the simulator

*Gone through build settings comparing to another working project and tried to mimic settings

Image example:
Home page tab bar when ran from Xcode:

Home page tab bar when ran from user input (it's just empty, but the tab bar items are clickable)

I would appreciate any suggestions that someone can give as this issue has been driving my head in for several days now.
Thank you,
Alan

A: I am really sorry for posting it as an answer but I am new to stackOverFlow:) I still don't have enough reputation to comment but really want to help you!
Have you tried setting rendering setting as Template?
(Render as Template Image)

A: Update since I cannot delete the question anymore. My issue was with one of the pods I had in the project called Gifu, with iOS 14 a UIImageView extension messed up basically all the Image Views in my project, so if someone is also having this issue a suggestion is to go through any of your pods that affect your images and see if any issues have arisen with them, they probably would've been listed in the issues on the pods github page.


text:
Q: Which space is bigger? (Sobolev Space) First, let us define the following space :
\begin{align*}
H^{1}(\Omega) :=\{u :\Omega\to\mathbb{R}\,|\,\forall\alpha\text{ multiindex },0\leq|\alpha|\leq1,||D^{\alpha}u||_{L^{2}(\Omega)}<\infty\} \\
H^{2}(\Omega) :=\{u :\Omega\to\mathbb{R}\,|\,\forall\alpha\text{ multiindex },0\leq|\alpha|\leq2,||D^{\alpha}u||_{L^{2}(\Omega)}<\infty\}\\
\end{align*}
Then, we can define the corresponding space $H_{0}^{1}(\Omega) \subset H^{1}(\Omega)$ and $H_{0}^{2}(\Omega)\subset H^{2}(\Omega)$.
Finally we define the following :
\begin{equation*}
\begin{cases}
D(B) := \{u \in H_{0}^{1}(\Omega)\,|\,\Delta u\in L^{2}(\Omega)\} \\
\forall u\in D(B), B u=\Delta u
\end{cases}
\end{equation*}
I can immediately see by definition that $D(B)\subset H^{2}(\Omega)$. However, can anyone help me to construct a counter example or to show that $H_{0}^{2}(\Omega) \subset D(B)$?
Any help is much appreciated! Thank you very much!


text:
Q: Close Javascript menu by clicking outside of menu I want to close my Javascript menu by clicking outside of the menu. I am using this menu. I'm not professional, please tell me how to change my code to do that:
$("#theme_select").click( function () {
  if (theme_list_open == true) {
    $(".center ul li ul").fadeOut();
    theme_list_open = false;
  } else {
    $(".center ul li ul").show();
    theme_list_open = true;
  }
  return false;
});
$("#theme_list ul li a").click(function () {
  var theme_data = $(this).attr("rel").split(",");
  $("li.purchase a").attr("href", theme_data[1]);
  $("li.remove_frame a").attr("href", theme_data[0]);
  $("#iframe").attr("src", theme_data[0]);
  $("#theme_list a#theme_select").text($(this).text());
  $(".center ul li ul").hide();
  theme_list_open = false;
  return false;
});

A: If you want to close that menu when the iframe area is clicked, you have to do that in the iframe. Try putting this in your iframe's document ready function:
$("html").click( function () {
    $(".center ul li ul", window.parent.document).fadeOut();
    window.parent.theme_list_open = false;
});

A: Seems you use $("#theme_select").click( function () { for both open and close the menu. and use $("#theme_list ul li a").click(function () { to handle click on menuitem, which will close the menu after.
In fact there is simple solution to your problem. Use $("#theme_select").click for only open the menu, and $("#theme_list ul li a") for handle the link, and introduce $(window).click to close the menu.
function checkAndCloseMenu(evt) {
  var dropmaker = $('#theme_select')[0];
  for (var node = evt.target; node != document.body; node = node.parentNode)
    if (node == dropmaker) return false;  // check if click in the dropmaker
  $('.center ul li ul').fadeOut();
  $(window).unbind('click', checkAndCloseMenu);
}
$("#theme_select").click(function() {
  $(".center ul li ul").show();
  $(window).click(checkAndCloseMenu);
});
$("#theme_list ul li a").click(function() {
  var theme_data = $(this).attr("rel").split(",");
  $("li.purchase a").attr("href", theme_data[1]);
  $("li.remove_frame a").attr("href", theme_data[0]);
  $("#iframe").attr("src", theme_data[0]);
  $("#theme_list a#theme_select").text($(this).text());
  return false;
});

PS: may be you should give the menu and menuitems some class names, your selector is painful to read.


text:
Q: Can the account name of 'distributor_admin' be changed? 'distributor_admin' is a SQL-auth account that is used for replication. Out of the box it is granted sysadmin and currently it looks like that can not be dialed back to db_owner (see related Does distributor_admin need sysadmin? ).
According to some sources (pg4 of PDF) distributor_admin is one of the top eight SQL usernames used in brute force attacks. It is considered a best practice to rename the 'sa' account can the 'distributor_admin'be renamed also?
I looked around and don't find anyone suggesting this alternative. I found a few posts that implied the possibility of the 'distributor_admin' being hard coded into the replication process.
There is not a lot of recent documentation about the distributor_admin account with replication.

A: No it can't be renamed.  The good news is that the account only exists on the distributor, which doesn't really contain any user data.
You can safely disable the account when you aren't setting up new replication publishers. If you need to setup a new publisher, enable the account setup the publisher then disable the account again.
It does need to have sysadmin rights. It needs to be able to create linked servers.


text:
Q: Error: el divisor es igual a cero en Oracle Necesito realizar la siguiente consulta SQL en ORACLE:
select
        (DISPONIBILIDADES/EFECTIVO) as DISPONIBLE
    from sbv
    where banco = 'ACTIVO (BU)'

Pero obtengo el siguiente error:

ORA-01476: el divisor es igual a cero
  01476. 00000 -  "divisor is equal to zero"

El campo EFECTIVO tiene como valor 0. Se que una división entre 0 da una indeterminación pero necesito que si la división es entre 0, me de como resultado 0.

A: Para esto podemos usar un case para antes hacer la division chequear que el valor no sea 0.
select
CASE EFECTIVO
    WHEN 0 THEN 0
    ELSE (DISPONIBILIDADES/EFECTIVO) END as DISPONIBLE
from sbv
where banco = 'ACTIVO (BU)'

A: Generalmente es mejor aceptado que el resultado de esta división sea NULL y no cero, pues su significado es justamente indeterminado.
Para lograrlo, puedes valerte de la función nullif:
select DISPONIBILIDADES / nullif(EFECTIVO, 0) as DISPONIBLE
  from sbv
 where banco = 'ACTIVO (BU)'

Si de todas formas quieres que te devuelva cero, puedes valerte de nvl() o `coalesce():
select coalesce(DISPONIBILIDADES / nullif(EFECTIVO, 0), 0) as DISPONIBLE
  from sbv
 where banco = 'ACTIVO (BU)'


text:
Q: Add an Icon using pure HTML i would like to know if there's any way I could add a fas-fa clock icon using pure html. Reason being, I'm currently doing an assignment using a free wordpress account. Because its free, i have alot of limitations(no javascript, no CSS). only pure HTML coding.

<meta name="viewport" content="width=device-width, initial-scale=1">

A: You could easily download the svg and host it as a raw svg on github or something of the likes and link to it as an image, it's dirty but it works

A: An alternative you can use is uni characters here

<meta name="viewport" content="width=device-width, initial-scale=1">

🕓

A:

You can easily put them as an image as in this example.
you can find more svg icons of font-awesome on GitHub on this link https://github.com/FortAwesome/Font-Awesome/tree/master/svgs


text:
Q: Delay `ssh-add` passphrase prompt until first use I would like ssh-add to delay asking for the passphrase to my private key(s) until they are first accessed.  The reason for this is that I would like to start ssh-agent on login and add keys to it, but I don't always use SSH, so I want the keys locked until and unless I actually need to start SSHing.
I have not been able to find any mention of anything like this in my Googling.  Is there a way to do this?  How do I keep my SSH keys locked until I actually need them?

A: The AddKeysToAgent option will function as needed.  Setting this option on the command line (-o AddKeysToAgent=yes) or in your SSH config file (~/.ssh/config --> AddKeysToAgent yes) will automatically add your SSH keys, as you use them, to the running SSH agent.  This will have the effect of deferring the password prompt and unlocking of keys until you actually use them.
Thanks to BasketCase on #openssh on Freenode.


text:
Q: automatically add a column if it doesn't exist when appending a table (python pandas) I am writing away lines in an SQL database,
Sometimes however there is a new feature that is not yet a column in the SQL database, and so I get an error.
Is there a way to write a line into SQL and add automatically a new column if it did not exist yet?

A: With Python, you could do something like:
def add_column_to_table(c, table_name, column_name, column_type):
    for row in c.execute('PRAGMA table_info({})'.format(table_name)):
        if row[1] == column_name:
            # print('column {} already exists in {}'.format(column_name, table_name))
            break
    else:
        # print('add column {} to {}'.format(column_name, table_name))
        c.execute('ALTER TABLE {} ADD COLUMN {} {}'.format(table_name, column_name, column_type))

c = db.cursor()
add_column_to_table(c, 'mytable', 'newcolumn', 'INTEGER')

A: Let say the table name is MY_TABLE
and you need to add BLOB column MY_COLUMN with default value = 0
hasColumn = 0
for row in self.conn.execute('PRAGMA table_info(MY_TABLE)'):
    if row[1] == 'MY_COLUMN':
        hasColumn = 1
        break

    if(hasColumn == 1):
        self.conn.execute('ALTER TABLE MY_TABLE ADD COLUMN MY_COLUMN BLOOB DEFAULT 0 ')


text:
Q: Getting string characters in an array I have a string in ruby whose initial characters would be numbers and the last character would always be a letter. Some of the examples are: 2C, 1P, 45H, 135D.
I want to get an array which would have 2 objects, first would be the number and second would be the character.
Eg: for 2C, array would be [2, C]
    for 45H, array would be [45, H]
    for 135D, array would be [135, D]

I tried my_string[/(\d+)([A-Z])$/].split(//, 1), but it gives me an entire string in an array. Like ["2C"], ["45H"]
Am I missing something here?

A: I had to do some quick Googling to see how to use Ruby's split, but here is how you want to do it:
print '2C'.split(/(?<=\d)(?=[A-Z])/);
// ["2", "C"]

The expression works by doing a lookbehind ((?<=...)) and a lookahead ((?=...)).  This means we will match the spot that has a digit to the left and a letter to the right.

A: You can use scan:
'150D'.scan(/\d+|\w/)
# => ["150", "D"]


text:
Q: How i can make Mapreduce get by year? any one can help me,,
my brain stacking for make this collection to mapreduce,
how i can get PurchaseAmount, PurchaseReturnAmount, and TotalAmount, with key by "year".
{
    "_id" : {
            "OwnerId" : "coba@aja.com",
            "SupplierId" : BinData(3,"AYC8In8bFkGYNx34poQLlg=="),
            "GroupId" : BinData(3,"mzWBCilngEGd72YpeyijcQ=="),
            "ProductId" : BinData(3,"gZ2g/syue06v8b88+0pqRA=="),
            "Date" : ISODate("2013-01-15T00:00:00Z")
    },
    "value" : {
            "OwnerId" : "oetawan@dokuku.com",
            "Date" : ISODate("2013-01-15T00:00:00Z"),
            "SupplierId" : BinData(3,"AYC8In8bFkGYNx34poQLlg=="),
            "SupplierName" : "Matahari",
            "GroupId" : BinData(3,"mzWBCilngEGd72YpeyijcQ=="),
            "GroupCode" : "Umum",
            "GroupName" : "Umum",
            "ProductId" : BinData(3,"gZ2g/syue06v8b88+0pqRA=="),
            "ProductCode" : null,
            "ProductBarcode" : "IPAD2",
            "ProductName" : "iPad 2",
            "PurchaseAmount" : 19500000,
            "PurchaseReturnAmount" : 0,
            "TotalAmount" : 19500000
    }

}
i want to use this map reduce to C#

A: Here's a shell example using MR. You could also do it with the aggregation framework of course, but presumably you want to run this in the background;
db.so.mapReduce(
        function () { /* map */
            var key = this._id.Date.getFullYear();
            emit(key, { PurchaseAmount:this.value.PurchaseAmount, PurchaseReturnAmount:this.value.PurchaseReturnAmount, TotalAmount:this.value.TotalAmount } );
        },
        function (key, array) { /* reduce*/
            var result = { PurchaseAmount: 0, PurchaseReturnAmount: 0, TotalAmount: 0 };
            for (var i = 0; i < array.length; i++) {
                {
                    result.PurchaseAmount += array[i].PurchaseAmount;
                    result.PurchaseReturnAmount += array[i].PurchaseReturnAmount;
                    result.TotalAmount += array[i].TotalAmount;
                }
            }
            return result;
        },
        {
            out: "so_mr_example",
            query:{}
        }
);

db.so_mr_example.find();

Produces something like;
{ "_id" : 2013, "value" : { "PurchaseAmount" : 39000000, "PurchaseReturnAmount" : 0, "TotalAmount" : 39000000 } }
{ "_id" : 2014, "value" : { "PurchaseAmount" : 19500000, "PurchaseReturnAmount" : 0, "TotalAmount" : 19500000 } }


text:
Q: Crafting a target variable for propensity to purchase My goal is to predict when a prospect customer has the intent to purchase a product (industry has a very slow sales cycle). This is ultimately a marketing model, so predicting/estimating when the prospect becomes interested in purchasing this type of product is as important (if not more) than knowing the actual year they will purchase.
I think my question will be best solved by generating some fake data so I can best explain my intentions. Please see the R code below for generating some fake data.
# setup fake dataset with no purchases or flags to begin with
sales_data <- expand.grid(year=2004:2011,prospect=c('A', 'B', 'C'),
                          flag=0, purchased=0)

# quick function to populate the sales, nothing to write home about
make_fake_sale <- function(data, prospect, salesyear) {
    # flag our actual purchase (pretend that this has been done already)
    yearindx <- which(data[,1] == salesyear)
    prospindx <- which(data[,2] == prospect)
    prosp_yr_indx <- yearindx[yearindx %in% prospindx]
    data[prosp_yr_indx,4] <- 1

    # set our fake target variable "flag" = to 1
    flag_yrs <- (salesyear - 3):(salesyear - 1)
    yearsindx <- which(data[,1] %in% flag_yrs)
    pros_flgyr_indx <- yearsindx[yearsindx %in% prospindx]
    data[pros_flgyr_indx,3] <- 1
    return(data)
}

sales_data <- make_fake_sale(sales_data, 'A', 2010)
sales_data <- make_fake_sale(sales_data, 'B', 2008)
sales_data <- make_fake_sale(sales_data, 'C', 2009)

sales_data

that leaves us with the following data below (I cut off prospect 'C', but you get the idea).

(not pictured here are the features I would use to actually train the model itself)
My question is: Is there any danger to removing the 'purchased' column and using this new 'flag' field as my target variable for modeling?
Are there certain models where this would be a good idea and some where it would not?
Would it at all be a good idea to maybe turn this into a regression and make up a scoring construct so the year before the purchase would receive a value of 100, then two years before the purchase would receive a 75, and so on? That way we take into consideration how close they are to making the actual purchase?
The ultimate goal here is to model/predict when prospect customers have started considering their need for a product that has a very long sales cycle (typically over one year).
Also a final note, I am being very careful with how I split my train and test for the validation phase of modeling, so I have already considered the pitfalls there (data leaks, prospects who straddle the cutoff year, etc.)
EDIT: clarifying intentions for this model
EDIT: the industry I am dealing with is low-volume, so the "purchased" column is very sparse. Additional reasoning for the "flag" target variable would be for giving the predictive model more actual positive results to train with.

A: It is perfectly valid to create a target variable like flag, you just need to be aware of how this differs from the purchased variable and your knowledge of the sales industry is needed to decide which is better.
Obviously flag and purchased are closely related but they both have potential drawbacks.

*

*Predicting purchased will only give you 1-12 months notice before the customer is expected to buy the item. This might not be long enough for your to market the item to them.

*Predicting flag should give you a few years notice for when a customer will buy a product, the downside is that 3 years notice is treated the same as 1 year notice (you know better than I if this is important). Are customers actually expected to show signs 3 years in advance? Is a customer who will buy in 3 years more similar to one who will buy in 4 or 2 years? If 3 years is more similar to 4 years then treating 3 years notice as a true flag will obscure the pattern in the data.

A possible solution to the issue with predicting flag is to reduce flag gradually between 1 and 4 years ahead of purchase. Perhaps 1 year ahead of time then flag=1, 2 years ahead flag=0.66, 3 years ahead flag=0.33, 4+ years ahead flag=0. This treats 4 and 5 years the same, you can decide if this is a fair assumption.
Treating 1 year ahead of purchase differently from 3 years ahead of purchase allows you to prioritize resources to those customers who will be purchasing soon.


text:
Q: Download/update dependent framework into ios project automatically I am using a framework/library for my iOS project. That framework is also created by me and uploaded as private on GitHub.
I want to update the added framework into my application project on the basis of version number automatically whenever I pull from git or build my app.
How can I achieve this for ios app? Can it be done through Jenkins or through git or xcode or some other approach is there?
I have no idea how it could be done. Please help and share ideas. Thanks!

A: It sounds like your looking for a dependency manager. There are two available. The Ruby based CocoaPods and native OS X Carthage. Of the two, I think Carthage is the easiest to learn because it does not change your project's settings and only needs a simple file to setup.


text:
Q: Logtash grok / multiline confusion My real patterns are more complex but I have tried to boil the problem down to the core issue.  Something I don't understand.
Please try this out on http://grokconstructor.appspot.com/do/match
I'm trying to match the following lines:
Start-Date: 2017-08-07  06:48:12
End-Date: 2017-08-07  06:48:12

Start-Date: 2017-08-07  12:55:16
End-Date: 2017-08-07  12:56:01

Using the additional patterns:
DATE_EU2 %{YEAR}-%{MONTHNUM}-%{MONTHDAY}[\s]+?%{HOUR}:?%{MINUTE}(?::?%{SECOND})?%{ISO8601_TIMEZONE}?
DATE_COMB %{DATE_EU2}?%{DATE_EU}?%{DATE_US}?

And the following main pattern:
Start-Date: %{DATE_COMB:starttime}\nEnd-Date: %{DATE_COMB:endtime}

With the multiline filter:
^\n (negated)

Run that and you should (hopefully!) get:
Start-Date: 2017-08-07 06:48:12 End-Date: 2017-08-07 06:48:12 Start-Date: 2017-08-07 12:55:16 End-Date: 2017-08-07 12:56:01
MATCHED
starttime   2017-08-07··06:48:12
endtime 2017-08-07··06:48:12
after match:    Start-Date: 2017-08-07 12:55:16 End-Date: 2017-08-07 12:56:01

So it's matched the first record but not matched the second.
If I add a '\z' to the end of the main pattern then it will match
the second record but not the first. So it's clearly treating the whole thing as one line. But why? My multiline filter states that if a line does not start with a newline it's part of the previous record, right? Well that should leave a blank line in the middle which clearly does start with a newline and should therefore comprise a seperate event, no?
Any pointers gratefully accepted.

A: Input
Start-Date: 2017-08-07  06:48:12
End-Date: 2017-08-07  06:48:12

Start-Date: 2017-08-07  12:55:16
End-Date: 2017-08-07  12:56:01

Multiline filter = ^\n (negated)
The multiline filter will look at each line in turn to see what should be merged.
First line starts with `^Start-Date` (merged)
Second line starts with `^End-Date` (merged)
Third line is blank (merged, unless logstash skips blank lines)
Fourth line starts with `^Start-Date` (merged)
Fifth line starts with `^End-Date` (merged)

Trying to match a \n, especially at the start of a line makes no sense.
You're better off matching ^End-Date: and merging that with previous. (Or if there's more lines for an event, and it always starts with Start-Date:, match that and negate.
Edit, based on comments and testing with the Grok constructor.
If it makes more sense to use the blank line as the record separator, ^\z or ^\Z appears to work. \Z ignores any final terminator, but seeing as \z also worked in my tests, it appears to confirm that the line, when passed into the filter, is a completely empty string (no newline or any other termination characters).


text:
Q: Why is the unittest's assert methods slower than raw assertion? unittest comes with many assert methods. I did a timeit test on using built-in Python assert and comparison operator vs built-in simple unittest assertion.
#!/usr/bin/python
import timeit

s = """\
import unittest
class TestRepomanManExtFunctions(unittest.TestCase):
    def test1(self):
        someObj = object()
        newObj = someObj
        self.assertEqual(someObj, newObj)

    def test2(self):
        str1 = '11111111111111111111111111111111111111'
        str2 = '33333333333333333333333333333333333333'
        self.assertNotEqual(str1, str2)

if __name__ == '__main__':
    unittest.main()

"""
t = timeit.Timer(stmt=s)
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

s2 = """\
import unittest
class TestRepomanManExtFunctions(unittest.TestCase):
    def test1(self):
        someObj = object()
        newObj = someObj
        assert someObj == newObj

    def test2(self):
        str1 = '11111111111111111111111111111111111111'
        str2 = '33333333333333333333333333333333333333'
        assert str1 != str2

if __name__ == '__main__':
    unittest.main()

"""

t = timeit.Timer(stmt=s2)
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

The results are
yeukhon@yeukhon-P5E-VM-DO:/tests$ python t.py
1203.46 usec/pass
873.06 usec/pass
yeukhon@yeukhon-P5E-VM-DO:tests$ vim t.py
yeukhon@yeukhon-P5E-VM-DO:tests$ python t.py
1300.33 usec/pass
956.35 usec/pass
yeukhon@yeukhon-P5E-VM-DO:tests$ python t.py
1208.82 usec/pass
865.18 usec/pass

One advantage of using the unittest's built-in assert methods is that it tells the user what is actually being compared. An example from of my actual tests:
======================================================================
FAIL: test_000_write_to_file_directory_not_exist (__main__.TestRepomanManExtFunctions)
Test writing content to a new file whose parent directory
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1224, in patched
    return func(*args, **keywargs)
  File "test_ext.py", line 71, in test_000_write_to_file_directory_not_exist
    self.assertNotEqual(mk_exists.call_args_list, exists_call_list)
AssertionError: [call('/tmp/test/fake/')] == [call('/tmp/test/fake/')]

Here is using simple assert X = Y
======================================================================
FAIL: test_000_write_to_file_directory_not_exist (__main__.TestRepomanManExtFunctions)
Test writing content to a new file whose parent directory
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1224, in patched
    return func(*args, **keywargs)
  File "test_ext.py", line 72, in test_000_write_to_file_directory_not_exist
    assert exists_call_list != mk_exists.call_args_list
AssertionError

Besides this advantage, what other nice things can we do by utilising the built-in self.assert_*(...)?
Why is the raw faster? I know accessing attribute and checking against a class is generally slower. But I want to know what's going on too? I hope this is a valid question.
Thanks

A: Probably the assert* function is slower because there is overhead in calling it (pushing parameters to stack, calling, popping return address from stack etc.), compared to the assert keyword which is executed inline. The assert* functions have some other nice properties as you have mentioned, like printing the expected and actual value.
Are you asking out of curiosity or is this an actual problem? I'd be surprised to see any situation where the speed of asserts is a bottleneck.

A: When unit testing the assert provided by the unit testing library that you use collect much more information about your tests. They collect wither the test was a success or a failure, what caused the error, capture whatever exceptions were thrown, and any output from your tests.  This collection of data is then manipulated into whatever output you require be it stdout or a xml file.  This all just takes time and requires a lot of function overhead to be completed, where as a single assert is as said more or less inline and displays an error along with the file and line number.
There is a huge different between the two behind the scenes.


text:
Q: What triggers a Control re-rendering after the initial page load? I was working with Controls in SAPUI5 and saw events like onBeforeRendering and onAfterRendering on them; I supposed a Control was rendered only one time (in the initial loading of the page); However, are there other occasions that re-render a control without full a page reload? And in what occasions makes sense to re-render a control? How it is useful to the developer? Thanks in advance!

A: A control is usually re-rendered when

*

*a property changes

*an aggregation is manipulated

*an aggregated control requests so

To be precise, any of the above only invalidates the control which tells the UI5 runtime core that re-rendering is necessary (which then happens asynchronously for performance reasons).
Depending on the implementation, re-rendering can be suppressed. E.g. the sap.m.Text control doesn't invalidate the control when the text property changes but just manipulates its DOM directly.
For the the majority of scenarios, you don't need to worry about re-rendering. It's being taken care of by the UI5 runtime. In fact, for most scenarios, when you need to explicitly re-render/invalidate a control, there's probably something wrong with your implementation.


text:
Q: Error when running flutter pub get command I would like to ask for help, I've searched all the answers here in the community and I can't solve my error.
I had to update a personal project to Android sdk 32, but when I try to run the Flutter pub get command I'm having an SDK version error, I'm leaving the pub spec and the error image below.
Error Picture Here
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.17.0 <3.0.0"

dependencies:
  dio: ^4.0.0
  rxdart: ^0.27.1
  bloc_pattern: ^3.0.0

  flutter_launcher_icons: ^0.10.0
  flutter_translate: ^4.0.3
  flutter_localizations:
    sdk: flutter
  equatable: any
  json_annotation: any
  freezed_annotation: any
  webview_flutter: ^3.0.4
  flutter_cache_manager: ^3.3.0
  upgrader: ^4.6.1
  video_thumbnail: ^0.5.3

  ## Animation rive
  #rive: ^0.7.22

  # Native
  package_info_plus: ^1.0.3
  geolocator: ^9.0.2
  path_provider: ^2.0.2
  file_picker: ^4.1.6
  open_file: ^3.2.1
  url_launcher: ^6.0.8
  shared_preferences: ^2.0.6
  qr_code_scanner: ^1.0.1
  cross_file: ^0.3.2
  camera: ^0.10.0+3

  # Layout
  introduction_screen: ^3.0.2
  font_awesome_flutter: ^10.1.0
  select_form_field: "^2.1.0"
  #mask_text_input_formatter: ^2.0.0
  another_flushbar: ^1.10.24
  flutter_switch: ^0.3.2
  flutter_app_badger: ^1.2.0
  image_picker: ^0.8.5+3
  flutter_neat_and_clean_calendar: ^0.3.8+22
  date_utils: ^0.2.0
  date_format: ^2.0.2
  #flutter_form_builder: ^6.0.1
  date_time_picker: ^2.1.0
  flutter_rating_bar: ^4.0.0
  signature: ^5.2.1
  flutter_simple_treeview: ^3.0.0-nullsafety.1
  widget_to_image: ^2.0.0
  flutter_email_sender: ^5.0.2
  in_app_review: ^2.0.2
  flutter_typeahead: ^4.1.1
  brasil_fields: ^1.5.0
  grouped_list: ^5.1.2
  mat_month_picker_dialog: ^1.0.1

  # Videos Acesso Cameras
  video_viewer: ^1.2.6
  fijkplayer: ^0.10.1

  # Conteudo html
  flutter_html: ^3.0.0-alpha.5

  ## FIREBASE
  firebase_core: ^1.13.1
  firebase_messaging: ^13.0.3
  flutter_local_notifications: ^11.0.1

  ## Share Social
  share: ^2.0.4

  flutter:
    sdk: flutter
  json_serializable: any
  build_runner: any
  freezed: any

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.

dev_dependencies:
  mockito: ^5.0.10
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

flutter_icons:
  android: "ic_launcher"
  ios: true
  image_path: "assets/icon/icon.png"
  adaptive_icon_background: "assets/icon/icon.png"
  adaptive_icon_foreground: "assets/icon/icon.png"

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/img/
    - assets/i18n/
    - assets/animation/loading.riv
    - assets/json/paises.json

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages```

A: replace your sdk with
  sdk: ">=2.15.1 <3.0.0"

A: I managed to solve this problem, I uninstalled flutter on the mac and installed it again, I think the mac was cached.


text:
Q: update table with values from 2 other tables I would like to find the nearest Employee for my Customer and update in order table. I tried a Query which throws an error. Can any one suggest what am doing wrong on my query? The only select Statement is working fine. But the update looks some thing wrong.
I have 3 tables
Customer_Master
 Customer_ID  Customer_Name   WHID   Cust_Location
    Cust100001   Subash        WH10001  0xE6100000010C1B2E724F57172A408449F1F109685340
    Cust100002   Naresh        WH10002  0xE6100000010CBE30992A18152A4093AAED26F8675340

Employee_Master
Emp_ID      Emp_name   WHID            Emp_Location
Emp100001   Prakash   WH10001    0xE6100000010C363B527DE7172A4069C36169E0675340
Emp100002   Suresh    WH10002    0xE6100000010C98C3EE3B86172A4064E597C118685340
Emp100003   Vincent   WH10001    0xE6100000010CE5B8533A58172A4090DD054A0A685340
Emp100004   Paul      WH10002    0xE6100000010C2EE6E786A6142A40A0A696ADF5675340

Order_Tran
Order_ID          Cust_ID         Emp_ID
ORD19847      Cust100001      ?????
ORD19856      Cust100002      ?????
I have Location of the customer and also Employee in Master Tables. Now i want to update  Emp_ID in Order_Tran table who is nearest to the customer location in Order Table for Customer Cust100001.
I tried the below query which  is showing error
Update Order_Tran Set Emp_ID=(Select Top (1) Emp_ID, Employee_Master.Emp_Location.STDistance(Customer_Master.Cust_Location) AS DistanceApart FROM Customer_Master, Employee_Master WHERE Customer_ID = 'Cust100001'
and Customer_Master.WHID = Employee_Master.WHID  ORDER BY DistanceApart);

A: Try selecting a single value in your sub-query (to stop the error) and adding an outer where clause (to ensure only the specified employee is updated).
UPDATE Order_Tran
SET Emp_ID=(SELECT TOP (1) Emp_ID
            FROM Customer_Master, Employee_Master
            WHERE Customer_ID = 'Cust100001'
            AND Customer_Master.WHID = Employee_Master.WHID
            ORDER BY Employee_Master.Emp_Location.STDistance(Customer_Master.Cust_Location))
WHERE Customer_ID = 'Cust100001'


text:
Q: What is the lastest SEO technology used by Google? What is the  latest SEO technology used by Google?

A: Disclaimer: I am not from Google, and I do not intend to answer you question directly since no one out side Google knows what they do and Googlers are not allowed to tell you this kind of info I guess. It occurs to me, though,that WikiLeak provide you some secretes as US diplomatic cable does. Just kidding:-)
That being said, there are some approaches that are encouraged by Google, used by Google and most importantly worked for me in the past couple of years.
Link. I am sure you know how many in-bound links does Google have. Well not exactly, but you know the point, link still counts. Try your best to build relevant links, both in bound links and on site links. Good link not only helps your SEO, but also boosts your referring traffic.
Content. It is our king, if your web site does not like say, Google(it has tons of links), then you'd better provide great content, like Stackoverflow does. The most thing that makes SO so exceptional on search engines ranking is that SO provides the best content, unique and fresh.
Semantic web code. HTML related stuff like title, h, mata, atl and so forth. Web server involved thing like clean URL,  and URL rewrite, 301 redirect. Moreover, loading speed of your site is also important. Just name few.
Your users behavior. I am not sure about this, but some people write somewhere on Stackover that your web site's click through rate from Google's search result page, on site time, bounce rate also count. I do not believe this actually because it sounds like Google is watch us like big brother. But considering so many web site are using Google Analytics, it is still possible. Anyway, if you provide great content, with sound code, and useful links, you users love it, and arguably Google loves it.
Have fun and come back Stackoverflow, I am sure you gonna learn a lot.

A: this is how different tags a ranked
1 title
2 headline(h1)
3 meta description
4 h2
5 h3 etc


text:
Q: Why does Steward of Darkshire not buff a Silver Hand Recruit if I have Sword of Justice? I just played paladin and had Steward of Darkshire on the field and Sword of Justice equipped.

The steward was played in an earlier turn than the sword. When I summoned a Silver Hand Recruit by using my hero power it got the +1/+1 buff but not a Divine Shield. My only explanation for this is that it first got the sword buff and since this makes it a 2/2 minion it doesn't get steward's buff any more.
Nevertheless this should not happen in my opinion because the card text of steward clearly reads "Whenever you summon..." whereas the one of the sword is "After you summon...". So what I thought would happen is that the recruit first gets a devine shield followed by +1/+1.
What is the reason for the recruit not getting a devine shield? I was not able to test with other 1-cost minions since the game was over after that turn.

A: According to the wiki:

Steward of Darkshire triggers after Sword of Justice for merely
  summoned minions, but before Sword of Justice for played minions. She
  always triggers after Health auras update (such as Murloc Warleader)
  and after Hobgoblin triggers. It is unknown which of these
  interactions are bugged and which are intended

The Silver Hand Recruits are summoned by hero power. So this would explain that behavior. You can as well see it with a Murloc chain. A played 1 hp Murloc will gain both effects, while effect-summoned Murlocs only get the +1 hp buff without Divine Shield.


text:
Q: iTunes Match uploading slowness with eventual error -9810 After several weeks now and still in dialogue with Apple third tier support still haven't resolved an upload problem, can anyone help?
I have around 12,500 tracks out of which iTunes Match found purchases, matched and uploaded a significant number leaving me with around 3000 tracks in 'uploading' status. Then the whole system slowed down. At the present rate it will take over twelve months to upload the remaining tracks. iTunes gets to around 10 uploads (on a good day) and then seems to just stop uploading but leaving iTunes itself unaffected - not crashed. On some occasions but not all I get an error message -9810 which Apple Support have no note for.
Any one cured this one before?

A: According to a the Apple Discussion Forum, it's a sign on authentication error (SSL). You should try to sign out, sign on elsewhere and sign back on your iMac. When you do sign out, some flags on the Apple Servers are reset or restored, so you could sign on with the proper speed and permissions again.
Or you could change from WiFi to Ethernet or vice versa, this is also mentionned as a solution.
The article mentions more solutions, so I suggest you take a look at the article if above information doesn't help you out.


text:
Q: JSR303 validator message recursive resolution? I have written a JSR303 validator that compares property value to constraint:
@Documented
@Constraint(validatedBy = Cmp.LongCmpValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface Cmp {
    String message() default "{home.lang.validator.Cmp.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    long value();
    public enum REL { LT,LT_EQ,EQ,GT,GT_EQ;
        @Override
        public String toString() {
            return toString_property();
        }
        public String toString_property() {
            switch(this) {
                case LT   : return "{home.lang.validator.Cmp.REL.LT}";
                case LT_EQ: return "{home.lang.validator.Cmp.REL.LT_EQ}";
                case    EQ: return "{home.lang.validator.Cmp.REL.EQ}";
                case GT   : return "{home.lang.validator.Cmp.REL.GT}";
                case GT_EQ: return "{home.lang.validator.Cmp.REL.GT_EQ}";
            }
            throw new UnsupportedOperationException();
        }
        public String toString_common() { return super.toString(); }
        public String toString_math() { switch(this) {
                case LT   : return "<";
                case LT_EQ: return "\u2264";
                case    EQ: return "=";
                case GT   : return ">";
                case GT_EQ: return "\u2265";
            }
            throw new UnsupportedOperationException();
        }
    }
    REL prop_rel_cnstr();

    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        Cmp[] value();
    }

    class LongCmpValidator implements ConstraintValidator<Cmp, Number> {
        long cnstr_val;
        REL prop_rel_cnstr;

        public void initialize(Cmp constraintAnnotation) {
            cnstr_val = constraintAnnotation.value();
            prop_rel_cnstr = constraintAnnotation.prop_rel_cnstr();
        }

        public boolean isValid(Number _value, ConstraintValidatorContext context) {
            if(_value == null) return true;

            if(_value instanceof Integer) {
                int value = _value.intValue();
                switch(prop_rel_cnstr) {
                    case LT   : return value <  cnstr_val;
                    case LT_EQ: return value <= cnstr_val;
                    case    EQ: return value == cnstr_val;
                    case GT   : return value >  cnstr_val;
                    case GT_EQ: return value >= cnstr_val;
                }
            }
            // ... handle other types
            return true;
        }
    }
}

ValidationMessages.properties :
home.lang.validator.Cmp.REL.LT=less than
home.lang.validator.Cmp.REL.LT_EQ=less than or equal
home.lang.validator.Cmp.REL.EQ=equal
home.lang.validator.Cmp.REL.GT=greater
home.lang.validator.Cmp.REL.GT_EQ=greater than or equal

home.lang.validator.Cmp.message=Failure: validated value is to be in relation "{prop_rel_cnstr}" to {value}.

Works fine. Almost. The validation message I get looks like this:
Failure: validated value is to be in relation "{home.lang.validator.Cmp.REL.GT}" to 0.

Would anybody please suggest easy and convenient way, how to make Validator recognize and resolve nested {home.lang.validator.Cmp.REL.GT} key? I need it to be nicely usable in JSF2, which handles validation.
I'm not using Spring, but use hibernate-validator 4.
By the way, looks like hibernate-validator 4 doesn't fully implement JSR303, since later states in the 4.3.1.1.:

*

*Message parameters are extracted from
  the message string and used as keys to
  search the ResourceBundle named
  ValidationMessages (often materialized
  as the property file
  /ValidationMessages.properties and its
  locale variations) using the defined
  locale (see below). If a property is
  found, the message parameter is
  replaced with the property value in
  the message string. Step 1 is applied
  recursively until no replacement is
  performed (i.e. a message parameter
  value can itself contain a message
  parameter).

A: Ok, I did dig into this. The algorithm specified by JSR303 has an unintuitive mess with what (props) are recursively resolvable and what's not. I think, that's mainly due to bad distinction in grammar of annotation''s properties and RB's properties.
So I've made my own MessageInterpolator, which you can find in my repo: http://github.com/Andrey-Sisoyev/adv-msg-interpolator. It solves almost all the problems, and also allows to address the resource bundle, where to look for the property.


text:
Q: HTML doesn't recognize jpg file I have this very simple program in PHP and HTML. I am using Microsoft SQL Server
<?PHP
echo "A
";
echo "End of PHP
";

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The program doesn't recognize Pic1.jpg image and when run this php, the result is no image.

Thanks in advanced
Notice: I developed a small website to an organization one year ago and it is working live. Now they asked me to do some changes, but I couldn't do any thing because this problem is appeared when I work in localhost which I worked in before that.   Very strange, right?

A:

It's xHTML not HTML so try this and check image path Images/Pic1.jpg

A: If your path is good, you can also check sharing and permission of the file.
Public permission is usualy denied if it comes from the web

A: You have to either use absolute path, or verify with your server's configuration (httpd.conf or nginx's virtuial.conf) what is set as a document root of your web server and then verify the Images directory seats in this path relative to the document root.


text:
Q: Create and handle an exception in R I want to have a function where for a particular exceptions it throws and return a message, and then simply check whether what is returned is one of my defined 'exceptions'. For example say I have the function:
divideByX <- function(x){
    # If x is NA throws exception
    if(is.na(x)){
        return(exception('x is NA'))
    }
    # If x is 0 throws exception
    else if(x == 0){
        return(exception('Cannot divide by zero'))
    }
    else{
        return(10/x)
    }
}

So if x is 0 it returns the expception 'Cannot divide by zero', if x is NA it returns the exception 'x is NA' and for all other values of x it tries to evaluate the expression 10/x.
Then I would want to run something like this:
tempList <- list('a' = 2, 'b' = 0, 'c' = 5, 'd' = NA)
lapply(tempList, function(x){
   if(is.exception(x)){
       return(x)
   }
   else{
       y <- divideByX(x)
       return(y^2)
   }
 })

So it first checks if the value is one of my defined exceptions and if so returns the message, else it squares my value, so the above should return
$a
[1] 25

$b
[1] 'Cannot divide by zero'

$c
[1] 4

$d
[1] 'x is NA'

Does anyone know the best way to do this? Please let me know if anything is unclear.
Thanks in advance

A: Create a function to generate exceptions. The exceptions can be a linear hierarchy that extends the simple error class
exception <-
    function(class, msg)
{
    cond <- simpleError(msg)
    class(cond) <- c(class, "MyException", class(cond))
    stop(cond)
}

Here's your function
divideByX <- function(x){
    # If x is 0 throws exception
    if (length(x) != 1) {
        exception("NonScalar", "x is not length 1")
    } else if (is.na(x)) {
        exception("IsNA", "x is NA")
    } else if (x == 0) {
        exception("DivByZero", "divide by zero")
    }
    10 / x
}

and use to generate the output you asked for
lapply(tempList, function(x) tryCatch({
    divideByX(x)
}, MyException=function(err) {
    conditionMessage(err)
}))

or to treat some exceptions differently from others
> lapply(list(NA, 3:5), function(x) tryCatch({
+     divideByX(x)
+ }, IsNA=function(err) {
+     warning(err)  # signal a warning, return NA
+     NA
+ }, NonScalar=function(err) {
+     stop(err)     # fail
+ }))
Error: x is not length 1
In addition: Warning message:
x is NA

A: Unless you are always dividing 10, you would want to include the numerator in yoru function.
    divideByX <- function(X, num=10) {

    if(is.na(X))
        return('X is NA')
    if(X == 0)
        return('Cannot divide by zero')

    return(num / X)
    }

usage:
y <- 3
lapply(tempList, divideByX, num=y^2)
#   $a
#   [1] 4.5
#
#   $b
#   [1] "Cannot divide by zero"
#
#   $c
#   [1] 1.8
#
#   $d
#   [1] "X is NA"


text:
Q: What is the average lowest value from N random binomial experience Let $X_1,\ldots,X_n$ be indepedent Bin(n,1/2), and let M be their minimum. What is $E[M]$? (or an upper bound for it).

A: Its easy to write a summation for it:
$P (\min_i X_i >m ) = P(X_1,\ldots,X_n >m) = P(X_1 >m) P(X_2 >m) \ldots P(X_n >m)$ when $X_1,\ldots,X_n$ are independent.
In the i.i.d. case, $P(\min_i X_i >m) = (P(X_1 >m))^n$. Now, you can use the fact that $\min_i X_i$ is non-negative integer valued to note that $E[\min_i X_i] = \sum_{m >0} P[\min_i X_i > m] = \sum_{m=0}^n (P(X_1 > m))^n$.
If you want to upper bound it, substitute a binomial tail bound for $P(X_1 > m)$.


text:
Q: Python, tkinter running along side simulaiton I have a simulation, where a create moves around a map. The map is drawn with tkinter. In the simulation's init I call
    root = Tk()
    root.geometry("800x800+300+300")
    self.ex = land.Example(root)
    root.mainloop()

to start tkinter, where land.Example is the class below. What should happen is the map is initially drawn, then the simulation runs and anytime the creature moves it will use self.ex to draw that in tkinter. The problem is, when it runs, the map is drawn initially, and I have to close it so that the rest of the simulation will run. In that case the whole thing breaks because the simulation is trying to use a canvas that doesn't exist anymore. How can I fix this so the map and simulation both stay running
Simulation self.ex interaction
def move(self, creature, target):
        self.map[creature.x][creature.y].creatures.remove(creature)
        self.ex.updateMap(creature.x, creature.y, "remove")

land.Example
class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("Board")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self)
        self.upperX = 0
        self.lowerX = 0
        self.upperY = 0
        self.lowerY = 0

        for x, row in enumerate(landMass):
            for y, cell in enumerate(row):
                color = "grey"
                if isinstance(landMass[x][y], Food):
                    color = "green"
                elif isinstance(landMass[x][y], Water):
                    color = "blue"
                elif isinstance(landMass[x][y], Shelter):
                    color = "black"
                self.canvas.create_rectangle(50 * x , 50 * y , 50 * x + 50, 50 * y + 50,
                    outline=color, fill=color)
                self.canvas.create_text(3 + 50 * x, 3 + 50 * y, anchor=NW, fill="white", text=landMass[x][y].elevation)
                if color == "green":
                    self.canvas.create_text(3 + 70 * x, 3 + 50 * y, anchor=NE, fill="red", text=landMass[x][y].vegitation)
                elif color == "black":
                    self.canvas.create_text(3 + 70 * x, 3 + 50 * y, anchor=NE, fill="orange", text=landMass[x][y].quality)
        self.canvas.pack(fill=BOTH, expand=1)

    def updateMap(self, x, y, action):
        color = "grey"
        if action == "append":
            #DRAW THE CREATURE AT X,Y
        elif action == "remove":
            #DRAW THE ORIGINAL TILE AT X,Y
        ...
        self.canvas.pack(fill=BOTH, expand=1)

Edit: Other Attempts
when I add the following to the Simulation's init() and add a function. The whole thing runs, but the tk canvas, show the end result, not the result as it is happening.
        root = Tk()
        root.geometry("800x800+300+300")
        self.tkmap = land.Example(root)
        root.after(2000, self.runSim)
        root.mainloop()
    #End of __init__()

    def runSim(self):
        for generation in range(self.lifeCycles):
            self.simulate(generation)
        return self.evolve()

A: In your after called runSim, you perform your whole simulation. The idea is to do perform only one (or a few) step of your simultation in each after call.
Here is a little example of how it could works:
import random
from Tkinter import *

c = Canvas()
c.pack()
circle = c.create_oval(100,100,110,110, fill="red")

def simulate():
    #one step of simulation
    c.move(circle, random.normalvariate(0,3),random.normalvariate(0,3))
    c.after(100, simulate)

c.after(100, simulate)
c.mainloop()


text:
Q: sql result set to Output JSP page I have a sql query fired in my model class which returns a table of user data. Now i need to display the result on my view page (JSP). I don't want to fire the sql from JSP page. How do i pass of the result set to JSP? do i need to construct a collection set and pass it on to the JSP or is there any better way to do it?
Thanks,
-Vijay

A: use the request scope to pass from one jsp to another if you are using import
in the WORST  case use the session scope but you will be prone to memory leak.


text:
Q: How to setup iOS with ShareKit and OAuth I have setup my config for twitter as described in the documentation. I setup bitly and all other things. I even made a change to ShareKit to use https and api.twitter.com.. But I am still getting "Could not authenticate with OAuth" error.
Any idea what to check next?

A: Sometimes what is wrong is the authentication 'saved' into iPhone, and you must relogin.
See: https://github.com/ideashower/ShareKit/issues/89


text:
Q: maven bintray is shutdown, after using secret token getting Could not resolve com.mapbox.navigator:mapbox-navigation-native6.2.1 image here
i am getting this error
Could not resolve com.mapbox.navigator:mapbox-navigation-native6.2.1

A: Several possibilities:

*

*In your build.gradle you should be using "com.mapbox.navigator:mapbox-navigation-native:6.2.1" Notice the colon between "native" and the version number

*See this thread on github about this issue: https://github.com/mapbox/mapbox-navigation-android/issues/4533

*You may be using the wrong mapbox developer access token, which you will need to download the native libraries.


text:
Q: Performing calculations writing answers in standard form I have the question "Perform the following calculation writing your answer in standard form:
$$\frac {1.94925 \times 10^8}   {3.45 \times 10^3}\tag{1}$$
I'm not sure whether the answer is $\frac{19492500}{3450} = 56500$. And then in standard form this should be $5.65 \times 10^4$
OR
Whether the answer should be $\frac {1.94925}{3.45} = 0.565$ and then using the rules of powers do $\frac {10^8}{10 ^3} = 10 ^5$
Therefore giving the answer as $0.565 \times 10^5$

A: The multiplied number in scientific notation has to be larger than $0$, but less than $1$. $$1\leq a\leq 10$$
In the form $a\times 10^b$. So $5.65\times 10^4 $ is correct.


text:
Q: Is the power-exponential equation $\bigr(|x|+(-2)^{x-1})^{x-2}=1$ insoluble? Is the power-exponential equation insoluble? If yes, why? If no, what's the solution?
$$\bigr(|x|+(-2)^{x-1})^{x-2}=1$$
I am a grade-7 middle school(Don't mind this, you can answer even if I can't understand it. But I will understand it.) student study in Shanghai, China. We are learning about integer power. And then I met a question on exam:
$$(x-2)^{x-1}=1$$
It is clear that when $x=1$, the equation always stands up except the base $x-2=0$. But we have just defined $x=1$, so $x-2=-1\neq0$. Therefore, one of the solutions is $x=1$.
Then, consider $x-2=1$, since $1^x=1(x\in\Re)$. So we work out another solution $x=3$
After that, consider $x-2=-1$. The equation also stands up if $x-1$ is an even number at the same time, and it is true because $x=1$. But this solution is the same as the first one.
Therefore, this equation has 2 solutions, $x=1$ and $x=3$.
And I begin to think that if there is a power-exponential equation which has only 1 or 0 solutions. It is easy to throw two kind of solutions: The solutions which make the base equal to -1 and the ones can make the exponent equal to 0. When the exponent is an even number, and the base is the same formula as the exponent at the same time, there will be only one kind of solution. And after a lot of time calculating, I worked out a "insoluble" power-exponential equation, and that's the one at the beginning. Nevertheless, when I tried to solve it, I found it is out of my ability. Therefore, I'm looking forward for someone help me calculate it out, and I will be very thankful.


text:
Q: save outputs at a different location R I am looping through all the files in a directory and creating some reports and jpeg files. I would like to save these reports and pictures and a sub folder instead.
Is there a better way to do this without
setwd() back and forth in the loop?
for example:
for (j in 1:length(list.files()))
{
 sp=read.csv(list.files()[j])
#do something
  setwd("H:\test\sub")
  jpeg(paste(list.files()[j],'.jpg',sep=""))
  hist(data)
  dev.off()
  setwd("H:\test")
#do more
}

Thanks

A: Yes, just set the destiny path that you want to save:
jpeg(your_path_here, ...)

Like this
files = list.files()

for(file in files){
  dir = paste("H:\\test\\sub\\", file, ".jpg", sep = "")
  jpeg(dir)
  hist(data)
  dev.off()
}


text:
Q: ArrayList method add error The error is that the customers has different ID, but in readCustomer object of ArrayList class the only ID that is saved is the ID of the last customer.
//reads customer data from register.txt file
//has 2 string as arguments
//returns a ArrayList object with all the customer with the same name

public ArrayList<Customer> readCustomer(String name,String surname){

    Customer temp = new Customer();

    //will hold all the customers with the same name and surname
    ArrayList<Customer> readCustomer = new ArrayList<Customer>();

    try{
        FileInputStream fstream = new FileInputStream("register.txt");
        BufferedReader fbr = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
        while ((strLine = fbr.readLine()) != null)   {

            String line[];
            line = strLine.split(" ");
            if(name.equals(line[1]) && surname.equals(line[2])){

                temp.setCustomerID(Integer.parseInt(line[0]));
                temp.setName(line[1]);
                temp.setSurname(line[2]);
                temp.setAddress(line[3]);
                temp.setAge(Integer.parseInt(line[4]));
                readCustomer.add(temp);

            }
        }
        fbr.close();
    }
    catch(Exception ex){*emphasized text*
        System.out.println(ex.getMessage());
    }

    return readCustomer;
}

A: Create a new object on every iteration and not one which gets filled recuringly. Also, learn to understand object references.
while ((strLine = fbr.readLine()) != null)   {
    Customer temp = new Customer();

    // and so on

A: Use
Customer temp;//instead of doing Customer temp = new Customer();

And inside iteration do
temp = new Customer();

In every loop a new temp instance is created and thus you can add new customers to the array list as needed for your case.

A: You are creating the Consumer object only once all the way at the top. That means, every time you are just updating the same object with different values, and adding it to the list. So, you need to create the Consumer object for each and every record that you read from the text file. (i.e) You need to put the following line with in the while loop,
Customer temp = new Customer();


text:
Q: MySQL specific query performance tuning I have troubles with MySQL query performance.
Table (InnoDB):
+--------------------+---------------------+------+-----+-------------------+-------+
| Field              | Type                | Null | Key | Default           | Extra |
+--------------------+---------------------+------+-----+-------------------+-------+
| st_resource_id     | varchar(32)         | NO   | MUL | NULL              |       |
| st_sub_resource_id | varchar(32)         | YES  |     | NULL              |       |
| st_title           | varchar(500)        | YES  |     | NULL              |       |
| st_resource_type   | varchar(100)        | NO   | MUL | NULL              |       |
| st_site_id         | tinyint(4)          | NO   | MUL | NULL              |       |
| st_time            | timestamp           | NO   | MUL | CURRENT_TIMESTAMP |       |
| st_user_id         | int(10) unsigned    | YES  |     | NULL              |       |
| st_full_access     | tinyint(1) unsigned | YES  |     | NULL              |       |
+--------------------+---------------------+------+-----+-------------------+-------+

Indexes:
+---------------+------------+------------------+--------------+--------------------+-----------+-------------+----------+--------+------+------------+---------+
| Table         | Non_unique | Key_name         | Seq_in_index | Column_name        | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+---------------+------------+------------------+--------------+--------------------+-----------+-------------+----------+--------+------+------------+---------+
| nr_statistics |          1 | resource_id      |            1 | st_resource_id     | A         |     1546165 |     NULL | NULL   |      | BTREE      |         |
| nr_statistics |          1 | resource_id      |            2 | st_sub_resource_id | A         |     1546165 |     NULL | NULL   | YES  | BTREE      |         |
| nr_statistics |          1 | st_time          |            1 | st_time            | A         |     1546165 |     NULL | NULL   |      | BTREE      |         |
| nr_statistics |          1 | st_site_id       |            1 | st_site_id         | A         |          16 |     NULL | NULL   |      | BTREE      |         |
| nr_statistics |          1 | st_resource_type |            1 | st_resource_type   | A         |          16 |       10 | NULL   |      | BTREE      |         |
+---------------+------------+------------------+--------------+--------------------+-----------+-------------+----------+--------+------+------------+---------+

Query:
SELECT st_resource_id AS docId, count(*) AS cnt
FROM nr_statistics
WHERE
  st_resource_type = 'document'
  AND st_sub_resource_id = 'text'
  AND st_time > DATE_SUB(NOW(), INTERVAL 7 DAY)
  AND st_site_id = 1
GROUP BY st_resource_id
ORDER BY cnt DESC
LIMIT 0, 5;

Query plan:
+----+-------------+---------------+-------+-------------------------------------+-------------+---------+------+---------+----------------------------------------------+
| id | select_type | table         | type  | possible_keys                       | key         | key_len | ref  | rows    | Extra                                        |
+----+-------------+---------------+-------+-------------------------------------+-------------+---------+------+---------+----------------------------------------------+
|  1 | SIMPLE      | nr_statistics | index | st_time,st_site_id,st_resource_type | resource_id | 197     | NULL | 1581044 | Using where; Using temporary; Using filesort |
+----+-------------+---------------+-------+-------------------------------------+-------------+---------+------+---------+----------------------------------------------+

Table has ~1,666,383 rows. The query runs extremely slow. In MySQL process list I see this query in "copy to tmp table phase" for a long time (> 1 minute). Query generates heavy I/O load. I can't understand what to do to fix the problem and speed-up query execution.
If the problem is a result of wrong indexes, so what indexes will be right?
UPD. I created new composite index:
| nr_statistics |          1 | st_site_id_2     |            1 | st_site_id         | A         |          16 |     NULL | NULL   |      | BTREE      |         |
| nr_statistics |          1 | st_site_id_2     |            2 | st_resource_type   | A         |          16 |     NULL | NULL   |      | BTREE      |         |
| nr_statistics |          1 | st_site_id_2     |            3 | st_sub_resource_id | A         |      752018 |     NULL | NULL   | YES  | BTREE      |         |
| nr_statistics |          1 | st_site_id_2     |            4 | st_time            | A         |     1504037 |     NULL | NULL   |      | BTREE      |         |
| nr_statistics |          1 | st_site_id_2     |            5 | st_resource_id     | A         |     1504037 |     NULL | NULL   |      | BTREE      |         |

Now query plan is:
+----+-------------+---------------+-------+---------------+--------------+---------+------+-------+-----------------------------------------------------------+
| id | select_type | table         | type  | possible_keys | key          | key_len | ref  | rows  | Extra                                                     |
+----+-------------+---------------+-------+---------------+--------------+---------+------+-------+-----------------------------------------------------------+
|  1 | SIMPLE      | nr_statistics | range | st_site_id_2  | st_site_id_2 | 406     | NULL | 21168 | Using where; Using index; Using temporary; Using filesort |
+----+-------------+---------------+-------+---------------+--------------+---------+------+-------+-----------------------------------------------------------+

The query now runs very fast (as 0.0x sec), but I have to force using new index:
SELECT st_resource_id as docId, count( * ) AS Cnt
FROM nr_statistics
USE INDEX (st_site_id_2)
WHERE st_resource_type = 'document'
AND st_sub_resource_id = 'text'
AND st_time > DATE_SUB( NOW( ) , INTERVAL 7 DAY )
AND st_site_id = 1
GROUP BY st_resource_id
ORDER BY cnt DESC
LIMIT 0 , 5;

While the problem is resolved (not beautiful but effective way), I still have some open questions (see comments).

A: Create a composite index on (st_site_id, st_resource_type, st_sub_resourse_id, st_time, st_resource_id).
However, you will still have temporary and filesort in the plan because you are ordering on COUNT(*) which is not indexable.
If you need to run this query fast and often, you would have to create an aggregate table which would store counts for each site/resource/subresourse/week combination and update it in a trigger.

A: Did you try creating a composite index on st_resource_type, st_resource_id, st_time and st_site_id? It looks to me like you have several indexes, but most are on a single column, or maybe 2 columns. By having a composite index with more of the columns you need, it may improve the performance.

A: When doing queries with multiple where clauses the order in which you write them should match the order in which you wrote your query.
In your particular case it would be:
CREATE INDEX stats_index ON nr_statistics (st_resource_type, st_sub_resource_id, st_time, st_site_id);

This should give you a pretty good speed boost.


text:
Q: How to reset \markright without breaking \sectionmark? I'm using scrbook for a collection of papers. Every chapter has a different author, and is typeset with a custom command. I want the headers alternate between chapter and author (rather than whatever is section) -- so I redefine \markright and afterwards use \rightmark in scrlayer-scrpage's \cohead.
Here's an MWE:
\documentclass[a4paper,10pt,headings=optiontohead,version=last,openany]{scrbook}
\author{Immanuel Kant}
\title{Doubling section titles}
\usepackage{kantlipsum}\date{}
%% make individual papers chapters
\usepackage{suffix}
\renewcommand{\sectionmark}{}%prevent rewriting \markright
\renewcommand{\subsectionmark}{}%prevent rewriting \markright
\newcommand{\chapterauthor}[1]{\authortoc{#1}\printchapterauthor{#1}\markright{#1}}% setting \markright to author

\makeatletter
\newcommand{\printchapterauthor}[1]{%
 {\parindent0pt\vspace*{-10pt}%
 \linespread{1.1}\large\scshape#1%
 \par\nobreak\vspace*{30pt}}
 \@afterheading%
}
\newcommand{\authortoc}[1]{%
 \addtocontents{toc}{\vskip-10pt}%
 \addtocontents{toc}{%
 \protect\contentsline{chapter}%
 {\hskip1.3em\mdseries\scshape\protect\scriptsize#1}{}{}}
 \addtocontents{toc}{\vskip5pt}%
}
\makeatother
%% put authors in headers
%% http://tex.stackexchange.com/a/228219/12934
\usepackage{scrlayer-scrpage}
\clearpairofpagestyles
\renewcommand{\chaptermarkformat}{}
 \cohead{\small{\rightmark}}
 \cehead{\small{\leftmark}}
 \cfoot*{\pagemark}

\begin{document}
\maketitle
\chapter{Erst}
\chapterauthor{Auguste Comte}
\kant[2]
\section{Quite positive}
\kant[3]
\end{document}

Something happens because of fiddling with \sectionmark, and section titles print twice. My question is: What causes doubling of the titles and how to avoid it? Thank you for suggestions!

A: Both \sectionmark and \subsectionmark should take an argument:
\renewcommand{\sectionmark}[1]{}%prevent rewriting \markright
\renewcommand{\subsectionmark}[1]{}%prevent rewriting \markright

The \section command produces
\sectionmark{<title>}

and if you redefine \sectionmark to have no argument, the tokens {<title>} are not removed.

A: Because you are loading scrlayer-scrpage: Remove the (unnecessary) redefinitions of \sectionmark and \subsectionmark and use the possibilities of scrlayer-scrpage.
\usepackage{scrlayer-scrpage}
\automark{chapter}% -> section does not rewrite \markright
\clearpairofpagestyles
\renewcommand{\chaptermarkformat}{}
\addtokomafont{pagehead}{\small}
\chead{\headmark}% -> \rightmark on odd pages, \leftmark on even pages
\cfoot*{\pagemark}

Then the chapter is in the header of even pages and whatever you set as argument of \markright is in the header of odd pages.
Here is a short MWE:
\documentclass[openany]{scrbook}
%\documentclass[openany]{book}
\usepackage{kantlipsum}
\newcommand{\chapterauthor}[1]{\markright{#1}}
%
\usepackage{scrlayer-scrpage}
\automark{chapter}
\clearpairofpagestyles
\renewcommand{\chaptermarkformat}{}
\addtokomafont{pagehead}{\small}
\chead{\headmark}
\cfoot*{\pagemark}
%
\begin{document}
\tableofcontents
\chapter{Erst}
\chapterauthor{Auguste Comte}
\kant[2]
\section{Quite positive}
\kant[1-10]
\chapter{Next}
\chapterauthor{Other author}
\section{Quite positive}
\subsection{Test}
\kant[1-10]
\end{document}


text:
Q: Counting xyz_ids in QWEB I am trying to create a conditional block that will display a table with n>0 records. That is to say that if there are no records, the table is not displayed:
<t t-if="len(order_ids) > 0">

                SO
                Amount

            <t t-foreach="record.order_ids.raw_value" t-as="o">

                    <t t-esc="o.name"/>
                    $<t t-esc="o.amount_total"/>

            </t>

</t>

The model in question is crm.lead, and I am trying to count the order_ids field.
order_ids is a one2many field. The error I am getting is:

TypeError: dict.len is not a function

Though it is
How can count the amount of ids of a one2many field directly in a QWEB template?

A: I think <t t-if="record.order_ids"> or if you put order_ids in a variable  <t t-if="order_ids"> should be enough.