text: Q: using output cache attribute for child actions and AddCacheDependency to it Is there was any solution to expire child action response cache? As i understood output cache for action will expire only if i move on action directly, but i try to find solution to invalidate it with the another item, it dependent. For now if i add cache dependence for response and invalidate cahce, it dependent on - result still have been recieved from cache. Will be gratefull for suggestions. I understood that it possible to substitute output cache module but will be amazing to find solution without it.


text:
Q: CI 2.2.x upgrade to CI 3.0.x core files issues I just followed the upgrade guide for CI2 to CI3 and don't have encountered any other issues so far. Will probably get some because of the project I converted still uses DataMapper and has some other hooks and third party tools.
So the first problem I encountered so far is that my custom core controllers don't work anymore.
I use for example this depth for my front-end and back-end logic:

*

*CI_Controller > MY_Controller > CronController

*CI_Controller > MY_Controller > FrontendController

*CI_Controller > MY_Controller > AdminController

CI3 tells me that my controllers/Account.php controller doesn't know the FrontendController class.
Can I tell CI3 to still include my custom classes or is there a new approach for this?

A: If you used __autoload(){$class} for autoloading your core classes, you should change it with spl_autoload_register(function ($class){}. I.e.:
spl_autoload_register(function ($class) {
    if (substr($class,0,3) !== 'CI_') {
        if (file_exists($file = APPPATH . 'core/' . $class . EXT)) {
            include $file;
        }
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aligning Biblatex items left Similar to this question and this question I am searching for a way to align the numbers on the left. I am using biblatex. Any ideas?

A: The label format is controlled by the bibliography environment. To change the label alignment, change \renewcommand*{\makelabel}[1]{\hss##1} to \renewcommand*{\makelabel}[1]{##1}.
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{csquotes}

\usepackage[backend=biber, style=numeric]{biblatex}

\defbibenvironment{bibliography}
  {\list
     {\printtext[labelnumberwidth]{%
        \printfield{labelprefix}%
        \printfield{labelnumber}}}
     {\setlength{\labelwidth}{\labelnumberwidth}%
      \setlength{\leftmargin}{\labelwidth}%
      \setlength{\labelsep}{\biblabelsep}%
      \addtolength{\leftmargin}{\labelsep}%
      \setlength{\itemsep}{\bibitemsep}%
      \setlength{\parsep}{\bibparsep}}%
      \renewcommand*{\makelabel}[1]{##1}}
  {\endlist}
  {\item}

\addbibresource{biblatex-examples.bib}

\begin{document}
Lorem \autocite{sigfridsson,geer,nussbaum,
worman,knuth:ct:a,aksin,gaonkar:in,
moraux,pines,westfahl:space,jaffe}

\printbibliography
\end{document}


text:
Q: SQL: revoking permissions from public in master By default SQL grants execute permission on stored to public and also select to some table and views in Master to public...I am not 100% sure about this... What is the implication if we have to remove the select privileges on those objects from Public on Master?
Thanks...

A: As long as you have given any account that needs explicit permissions to those objects (views/procedures) you should see no issues. The issue I usually see after altering PUBLIC role permissions is applications that assume the permissions are there instead of just giving explicit permissions to them.
You will find that some Microsoft documentation states to not alter the PUBLIC  role permissions. I work with the IASE database checklist and the permissions given to the PUBLIC role is one of the first things we have to remove/revoke. I always keep the script handy to restore the permissions if needed.
EDIT
Query to find public permissions that I use sometimes:

SELECT o.name AS [Object], p.permission_name AS [Type]
FROM sys.all_objects o
INNER JOIN sys.database_permissions p ON o.object_id = p.major_id
INNER JOIN sys.database_principals u ON u.principal_ID = p.grantee_principal_id
WHERE u.name = 'public'

A: I wouldn't do it for everything.
Most lock down scripts remove or DENY rights selectivity. SQL Server 2005+ is better than older versions too (the script is for SQL Server 2000)
Just run SQL profiler and see what runs when a standard user opens a database using SSMS. For example, spt_values is heavily used but undocumented. Saying that, this will only affect developers or such (db_owner at most, never sysadmin) anyway. End users shouldn't use SSMS


text:
Q: I'm looking for some background on the word "breant" This quote was written by Henry Kelsey in his journal on August 6, 1691: "this river breants away much to ye Southward & runneth through great part of the Country".  Kelsey was born around 1667 in or near London and worked for the Hudson's Bay Company in Western Canada.  I haven't been able to find any reference to "breant" online.  I no longer (unfortunately) have access to the complete OED.  My speculation is that it means "bend."

A: In the following book Three Hundred Prairie Years: Henry Kelsey's "Inland Country of Good Report" they suggests it might mean "branches" probably based on the following:

on 6 August Kelsey recorded an interesting topographical situation: "... this river breants away much to ye Southward & runneth through great part of the Cuntry & is fed by a lake wch feedeth another River wch runneth down to ye Southward of us."
This river must be the Etomami, and Kelsey must have been near the present-day town of Hudson Bay, Saskatchewan when he made his journal entry. Once known as the North Etomami, the Etomami gets its name from the fact that it rises in a lake at the "divide," near which another river rises in a lake in the same valley and flows south. Now known as the Lilian, it joins the Assiniboine near Sturgis, Saskatchewan. In the following days Kelsey recorded his progress up the valley of the Etomami.

Manitoba Historical Society


text:
Q: why a multiline textbox (inside a user control) is not holding its value after a postback? I have a user control that have a gridview, buttons and a multi-line textbox for comments.
When the page posts back, Gridview is behaving normaly (its controls keeps their values after postback). However, the Comment textbox is always empty, no matter what I do.
protected void Page_Load(object sender, EventArgs e)
{
   //This code is in the user ciontrol.
  if (!IsPostBack)
   {
     string test = this.txtDepartmentComments.Text;
   }

}

I put a break point at that line and the value is always empty. I've tried also to set the value in the code behind like:
protected void Page_Load(object sender, EventArgs e)
{
   //This code is in the user ciontrol.
   if (!IsPostBack)
   {
     this.txtDepartmentComments.Text = "Test!";
   }
}

But when the page loads, the control remain empty.
Any idea why this is hapenning?
EDIT
This the ascx code (i.e. user control)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false" >
</asp:GridView>

<asp:TextBox ID="txtComments" runat="server" Columns="45" TextMode= "MultiLine"/>
 <asp:Button ID="btnComplete" runat="server" Text="Completed"/>

And thid id the aspx (i.e. the parent page)
<asp:Repeater ID="rpNewHire" runat="server">
       <HeaderTemplate>

       </HeaderTemplate>
       <ItemTemplate>

                <user:MyUserControl ID = "MyUserControl1" runat = "server"
                 DepartmentID= '<%# Eval("DepID")%>'><user:MyUserControl />

       </ItemTemplate>
       <FooterTemplate>

       </FooterTemplate>
    </asp:Repeater>

A: if(!IsPostBack) is for reading values from controls after postback, you are trying to read text box value on initial load which will always be empty, remove the '!' from your condition. Also it is hard to debug your issue with out the aspx page contents, try posting the design part as well in your question.
EDIT

*

*Your user tag is not well formatted inside repeater, it is missing closing tag and runat attribute
<user:MyUserControl runat="server" ID = "MyUserControl1" DepartmentID= '<%# Eval("DepID")%>'></user:MyUserControl>

*Controls inside repeater cannot be accessed directly, you have to loop through the rows of the repeater and find your child controls and then try reading values from them, that after you bind some data to the repeater.

Check this http://msdn.microsoft.com/en-us/magazine/cc163780.aspx

A: Page's IsPostBack and each user controls' IsPostBack are not same.
When a user control is posted back, that particular control's IsPostBack is true, but other user controls' IsPostBack are still false.
You can use explicitly !Page.IsPostBack inside a user control to check whether its parent page is posted back or not.
if(!Page.IsPostBack){
   // do something
}

Dynamically Loaded Control can not maintain values at PostBack?  It is not directly related to your question, but it might be useful for you.


text:
Q: dealing filenames with shell regex 138.096.000.015.00111-138.096.201.072.38717
138.096.000.015.01008-138.096.201.072.00790
138.096.201.072.00790-138.096.000.015.01008
138.096.201.072.33853-173.194.020.147.00080
138.096.201.072.34293-173.194.034.009.00080
138.096.201.072.38717-138.096.000.015.00111
138.096.201.072.41741-173.194.034.025.00080
138.096.201.072.50612-173.194.034.007.00080
173.194.020.147.00080-138.096.201.072.33853
173.194.034.007.00080-138.096.201.072.50612
173.194.034.009.00080-138.096.201.072.34293
173.194.034.025.00080-138.096.201.072.41741

I have many folders inside which there are many files, the file names are like the above
I want to remove those files with file names having substring "138.096.000"
and sometimes I want to get the list of files with filenames with substring "00080"

A: To delete files with name containing "138.096.000":
find /root/of/files -type f -name '*138.096.000*' -exec rm {} \;

To list files with names containing "00080":
find /root/of/files -type f -name '*00080*'

A: rm $(find . -name \*138.096.000\*)

This uses the find command to find the appropriate files. This is executed within a subshell, and the output (the list of files) is used by rm. Note the escaping of the * pattern, since the shell will try and expand * itself.
This assumes you don't have filenames with spaces etc. You may prefer to do something like:
for i in $(find . -name \*138.096.000\*); do
   rm $i
done

in this scenario, or even
find . -name \*138.096.000\* | xargs rm

Note that in the loop above you'll execute rm for each file, and the xargs variant will execute rm multiple times (dependin gon the number of files you have - it may only execute once).
However, if you're using zsh then you can simply do:
rm **/*138.096.000*

(I'm assuming your directories aren't named like your files. Note the -f flag as used in Kamil's answer if this is the case)


text:
Q: Is PDF version exported from ArcGIS Pro different to PDF from ArcMap? Is there a difference between the PDF version exported from ArcGIS Pro 1.4.1 layouts and that produced by ArcGIS Desktop 10.4.1?
I ask because I am seeing PDFs exported from ArcGIS Pro (600dpi) that look perfect in Adobe Acrobat Reader DC but when sent to either of two printers (no others tested) there are some grid lines (from Create Fishnet) that show up about 10 times as thick as they should.  The same thing happens in the scale bar and there is bad "blockiness" in two picture elements (logos) on the layout too.
Although the two PDFs are created quite differently (ArcGIS Pro vs ArcMap, using ArcPy in each case to do the same map series) these symptoms are not seen in the ArcMap PDFs but are seen in all such maps from Pro.
The hardcopy is from an A0 HP plotter and an A3 printer so I think the problem is the PDF rather than either plotter/printer.
A mobile phone photo of the hardcopy, although quite blurry, illustrates the symptoms.  Note the thick black line on the scale bar at bottom right (the rest is the expected thin lines), the two thick blue lines on the index map at lower left (the rest are the expected thin lines) and two thick grey lines on the grid in the main map (the rest are the expected thin lines).

Curiously, the same layout exported as a TIFF (600dpi) and imported into Adobe Acrobat Pro before being saved as a PDF prints fine from that PDF.  However, this is a workaround that is only viable for a subset of requirements because it requires manual creation of the final PDF (in an otherwise automated system), results if TIFF file sizes that are 10x as big and take 10x as long to create, and require licensing of Adobe Acrobat Pro.

A: I cannot explain why, but after a few more weeks working with this ArcGIS Pro project and ArcPy script, none of it targeted at trying to prevent the thick lines and blockiness, the symptoms of concern all disappeared.
I am hoping that they do not come back.  If they do, for me or anyone else, my plan of attack would be to:

*

*Try exporting a PDF from the ArcGIS Pro layout WITHOUT running any ArcPy code to manipulate it.  This should allow the source of the problem to be isolated to either the project itself or the ArcPy script.

*If it is the project then take a copy of it and on that copy start removing elements not needed to create those where the symptoms manifest to see if something can be shown to be the thing that is added to the project to cause them to appear.

*If it is the script then take a copy of it and on that copy start removing code not needed to create/manipulate the elements where the symptoms manifest to see if some code can be shown to be the thing that is added to the script to cause them to appear.


text:
Q: metadata editing in bash linux for multimedia files(not images) in linux I've searched across stackoverflow, and I've been on google and also duckduckgo and no one seems to have a nice way for me to do this.
The only tool that seems to maybe have worked was Exiftool which only has the read ability for ogg files(which is what I'm using at the moment). I'd like some way to do this via the command line since the mp3s/oggs and their name is the metadata but the metadata is blank. I already know how to parse the file names in bash but I cannot find a way to put it back onto the files. I could manually do this kind of thing but it's hardly worth it since I'd have to do it manually.
Musicbrainz picard also doesn't tag them properly for some odd reason so that's why I'm having to do this.

A: ID3 tags are MP3 specific. For Ogg Vorbis comment field specifications, see: Field Names
vorbiscomment (package vorbis-tools) can modify and query  ogg tag info.
mp3info is one of many tools to work wirh mp3 tags.

.ogg
# Clear all info
printf ''| vorbiscomment -w  test.ogg
           vorbiscomment -l  test.ogg
# modify info
echo ========
printf 'TITLE=The Last Saskatchewan Pirate
ARTIST=Captain Tractor
ALBUM=East of Edson
DATE=2000-01-01
COMMENT=Just another TEST comment
DESCRIPTION=*** Hello ***
'|vorbiscomment -w  test.ogg
  vorbiscomment -l  test.ogg
echo ========

Output (.ogg)
========
TITLE=The Last Saskatchewan Pirate
ARTIST=Captain Tractor
ALBUM=East of Edson
DATE=2000-01-01
COMMENT=Just another TEST comment
DESCRIPTION=*** Hello ***
========

mp3
# Delete the entire ID3 tag
mp3info -d test.mp3
echo  ========
# modify info
mp3info -t "The Last Saskatchewan Pirate" \
        -a "Captain Tractor" \
        -l "East of Edson" \
        -g "Folk/Rock" \
        -y "2000" \
        -n "1" \
        -c "Just another TEST comment" \
        test.mp3
mp3info test.mp3
echo  ========

Output (.mp3)
========
File: test.mp3
Title:   The Last Saskatchewan Pirate   Track:
Artist:  Captain Tractor
Album:   East of Edson                  Year:  2000
Comment: Just another TEST comment      Genre: Folk/Rock [81]

========


text:
Q: CSS Circle around a hyperlink Is possible to create a big circle around a hyperlink using CSS?
I'm trying to achieve it but my circle is very small. I would like that circle size were similar to hyperlink size. If i put the hyperlink inside a div, it's not being centralized inside the circle.
Here is what i'm doing:

    Test test test test

A: The problem with your code is that the a element is an inline element and thus accepts no height.  Change it to a block level element to give it a specified height:
.circle {
    border-radius: 100%;
    background: green;
    display:inline-block;
    line-height:100px;
}

To have the text appear in the middle, use line-height instead of height.
Working sample:
http://jsfiddle.net/7qfbopqj/

A: by using padding you can make the circle just bigger than the link
#circle {
    border-radius: 1000%;
    padding:50px;/* this instead of a set width and height just change this to change how much bigger the circle is than the link*/
    background:black;
    text-align:center;
    vertical-align:center;
}

A: You could put a div around the link and center the link within.

[link name]

.circle {
border: 2px solid red;
border-radius: 25px;
width: 10%;
height: auto;
margin-left: auto;
margin-right: auto;
}

http://jsfiddle.net/yg25us3k/

A: This is possible but you have to set the box size to match you text length, try this:
.circle {
    border-radius: 1000%;
    width: 40px;
    height: 40px;
    background: green;
    display:inline-block;
    line-height:40px;
    vertical-align:center;
    text-align:center;
    color:#ffffff;
}

    Test

try on jsfiddle: http://jsfiddle.net/prt4y7b2/


text:
Q: How to know what is the name in my chosen row in db? I create a login form in c# and I write the code to know whether the username and password is correct or not, and i succeeded.
But now I want to say hello to the person that's logging in.
My Database: Mysql and I use linq for that.
This is my code for the login button:
var query = from r in db.Users
            where r.Username.ToString() == txtusername.Text && r.Password == txtpassword.Text
            select r;

if (query.Count() == 1)
{
    MessageBox.Show("Welcom");
}
else
{
   MessageBox.Show("Wrong Username Or password!!!");
}

This code is working, but I don't know to how to change my message box to this :
MessageBox.Show("Welcom" + Firstname);

My database table's columns:
    Rownumber
    Firstname
    Lasttname
    Username
    Password

A: use below line you
MessageBox.Show("Welcom "+query.FirstOrDefault().Firstname);

A: Check below code
if (query.Count() > 0)
{
    MessageBox.Show("Welcome " + query.FirstOrDefault().Firstname);
}


text:
Q: How do redundant memory cells in DRAM raise yield? I was recently reading Computer Architecture-A Quantitative Approach(6th edition), and I encountered a problem while trying to understand a section from page 34:
Given the tremendous price pressures on commodity products such as DRAM and SRAM, designers
have included redundancy as a way to raise yield. For a number of years, DRAMs have regularly
included some redundant memory cells so that a certain number of flaws can be accommodated.

Doesn't yield actually refer to the number of DRAMs (out of many DRAMs manufactured in bulk) that make through the testing-procedure? If it is the case, how does adding redundant memory cells to a single DRAM increases that DRAM's yield chance. Furthermore, what are some examples of "certain number of flaws" that the line refers to.

A: Say you are making a DRAM chip that requires 64 cells to provide 32GB of RAM (I just made this up; no real numbers/data were harmed in the creation of this response).
If you build 64-cell chips have a defect rate of 0.1 cell defects per chip ( or 0.1/64 = 0.0016 defects per cell), that means that roughly one out of every 10 chips (or 10 out of every hundred) will have to be thrown away as unusable.
If instead you build 65-cell chips, and a small amount of additional circuitry that simply disables one cell chosen after first round testing, then you can tolerate one cell defect and still produce a usable 32GB part that passes testing.
Put another way, out of a batch of 100 chips, instead of throwing away 10 due to one defect, you can do a first round of testing to see if one cell can be identified as failing, activate the circuitry to disable that cell, and then run the chip through final testing to confirm function / quality.  This should let you keep about 9 more chips out of that batch of 100 (the last chip will have 2 defects sometimes) raising your yield from 90% to about 99.5%, despite the fact that you added another cell that could also fail.
The statistics is mildly interesting if you are into that type of thing; I'd be happy to give it a shot if you're curious.
A flaw is generally a failure in the chip production process that results in a portion of the chip not functioning as designed.  That could conceivably be due to impurities in materials, failures in masking, failures in placing the chip material in the chip package... anything.  Not all types of flaws can be mitigated by this approach.


text:
Q: The repository finds three records, and the resulting list returns 6 records The repository finds three entries in the request sending controller, and 6 entries are placed in the list
Please help me why this happens, I do not understand ((((((
Domain class User generated unique ids:
public class User implements UserDetails, Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

Controller methods:
@PreAuthorize("hasAuthority('_2_TEACHER')")
    @GetMapping("/project/{projectId}/party/create")
    public String viewTeacherCreateProjectParty(
            @PathVariable("projectId") Project project,
            Party party,
            Model model) {
        List<User> users = userService.userList(Sort.by("username"));
        model.addAttribute("project", project);
        model.addAttribute("party", party);
        model.addAttribute("users", users);
        return "teacherProjectPartyCreate";
    }

    @PreAuthorize("hasAuthority('_2_TEACHER')")
    @PostMapping("/project/{projectId}/party/create")
    public String processCreateProjectParty(
            @PathVariable("projectId") Project project,
            @Valid Party party,
            @RequestParam(value = "users") List<Long> usersIds,
            BindingResult bindingResult,
            Model model) {
        List<User> users = userService.findUsersByUserIdIn(usersIds);
        model.addAttribute("project", project);
        model.addAttribute("party", party);
        model.addAttribute("users", users);
        Long projectId = projectService.createProjectParty(project, party, users);
        return "redirect:/projects/project/" + projectId;
    }

Methods in service:
public List<User> userList(Sort sort) {
    return userRepo.findAll(sort);
}

public List<User> findUsersByUserIdIn(List<Long> usersIds) {
    return userRepo.findUsersByUserIdIn(usersIds);
}

Methods in repository:
List<User> findAll(Sort sort);

List<User> findUsersByUserIdIn(List<Long> usersIds);

Debug screed:

A: I solved the problem by removing all browser extensions and restarting the project. I noticed that the controller methods were executed twice, but because of what - this is a mystery


text:
Q: php preg_replace problem $strSubject= preg_replace('/\b'.$strWord.'\b/i', ''.$strWord.'', $strSubject);

above code works in php 5.2.6 but not working in php 5.2.9 and get " warning,unknow modifer....." error. please help

A: You probably have a meta character unescaped in $strWord. Try this...
$strSubject= preg_replace('/\b'.preg_quote($strWord, '/').'\b/i', ''.$strWord.'', $strSubject);

Also, you could just use this :)
$strSubject = preg_replace('/\b('.preg_quote($strWord, '/').')\b/i', '$1', $strSubject);


text:
Q: Headless browser unable to navigate between pages I am trying to drive a headless browser to login to cloud-based payroll software that my company uses. But it couldn't even get past the logging-in stage. The code works fine when in 'head' mode. Below are my codes:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("--headless") # Runs Chrome in headless mode.
options.add_argument('--no-sandbox') # Bypass OS security model
# options.add_argument('--disable-gpu')  # applicable to windows os only
options.add_argument('start-maximized') #
options.add_argument('disable-infobars')
options.add_argument("--disable-extensions")
browser = webdriver.Chrome(options=options, executable_path='/Applications/chromedriver')
print("Headless Chrome Initialized on MacOS")

# Navigate to website
browser.get('https://sg.quickhr.co')
print('Navigate to quickHR website')

# Login to quickHR
print('Keying in credentials')
# Define credentials and key-in accordingly
email = 'user@user.com'
password = '********'
browser.find_element_by_id('inputName').send_keys(email)
browser.find_element_by_id('inputPassword').send_keys(password)
browser.find_element_by_id('validate_login_lb').click()
print('Logging in')

# Wait for login to complete and webpage and elements to load before proceeding
try:
    WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'flaticon-payroll')))
finally:
    browser.find_element_by_class_name('flaticon-payroll')

And below is my error code:
Traceback (most recent call last):
  File "/Users/cadellteng/PycharmProjects/Playground/login.py", line 71, in <module>
    browser.find_element_by_class_name('flaticon-payroll').click()
  File "/Users/cadellteng/venv/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/Users/cadellteng/venv/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "/Users/cadellteng/venv/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/Users/cadellteng/venv/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
  (Session info: headless chrome=79.0.3945.130)

So apparently is not interactable. I'm not sure what it means as this routine works when it is not headless.


text:
Q: MSBuild: identity under which a batch script executes I have an MSBuild definition that runs a batch script that attempts to delete some files, but gets "Access is denied" errors. This was working a month ago, the build definition has not changed, and our administrator has given full rights on that folder to the "Build" user.
If I log into the build machine as the user "Build," I am able to run the script without errors. So I thought maybe the script was running as a different user. In the script I added these lines:
SET userDomain=%USERDOMAIN%
SET userName=%USERNAME%

Which generated this output:

*

*2016-11-18T13:48:19.6308977Z D:\vNextBuildAgent\1_work\b2de54b2\Platform>SET userDomain=Contoso

*2016-11-18T13:48:19.6308977Z D:\vNextBuildAgent\1_work\b2de54b2\Platform>SET userName=632766-BUILD$

The domain is right, but I was expecting %USERNAME% to simply be "Build" rather than "632766-BUILD$" as it says.
The name of the build machine is "632766-build" so it looks like the script is running as the local identity of the build machine instead of as the Build service account. How do I specify the identity under which the script executes?


text:
Q: Jquery refreshing multiple variables I am having a very hard time finding a good resources or any idea on how to accomplish the following:

Using jquery get some data

*

*Use jquery to fetch some data. Now what syntax should the data be in. Go to step 2.

*Again using jquery, assign that data to multiple variables and tags on the html page. I know how to replace 1 tag. But I wanna refresh multiple divs, tags, ids. Go to step 3.

*Now go back to step 1 after some time.

I have tried my friend GOOGLE but it can't find the pages that I am looking for. I would really appreciate some code here but a link to a tutorial wouldn't be too bad either.

A: 1) $.ajax() seems like a good idea, use it to fetch data in the JSON-format:
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback //Assign data and stuff here
});

2) Do that in the success-parameter, as a new function. success: function() {}
success: function() {
    $('div#1').html('foo');
    $('h1#1').html('woo');
}

3) Wrap your $.ajax()-call in an interval:
var refresh = setInterval(function()
$.ajax({
      url: url,
      dataType: 'json',
      data: data,
      success: callback //Assign data and stuff here
     });
 }, 60000);

Edit (response to the comment below):
Try doing it the following way, as you're not usin a function() as a callback:
function() {
    $.ajax({
        url: "/admin/ajax/all_data.php",
        dataType: 'json',
        data: data,
        success: function(data) {
            $("#testdiv1").html(data.testdiv1);
            //$("#testdiv2").html(data.testdiv2);
            //$("#testdiv3").html(data.testdiv3);
        }
    });
}), 2000);

Let me know if this works out for you.

A: 1 - See $.ajax and associated high level wrappers such as $.get, $.post, $.load and $.getJSON.
2 - If your server sends JSON to the client and the client understands how to use it, this is trivial. e.g.:
// json from server
{ "newsDiv" : "some html", "imagesDiv", "some html" }

// assuming it is stored in the variable 'data'
$("#newsDiv").html(data.newsDiv);
$("#imagesDiv").html(data.imagesDiv");

3 - setInterval is your friend.

A: Then check out the jquery 'load' function here. With this, you can load data from a server and place it into the matched html element. Very clean and simple.
Then, have a look at how to implement a timer here
I can't see what more you will need


text:
Q: Full outer join issues when using group by @@this may seem like a duplicate. The other post somehow posted as 'Guest' and will not allow me to make edits.@@
I have 4 subqueries and each of the subquery is grouped by 'Group name'. The attempt is to have each subquery as a column all grouped by the 'Group Name'. Here is the query:
select  coalesce(co.group_name, requests.group_Name, incidents.group_Name, problems.group_Name) as 'SD Groups'
, isnull(co.co, '') as 'CO'
, isnull(incidents.incidents, '' ) as 'Inc'
, isnull(problems.problems, '') as 'Prob'
, isnull(requests.requests, '') as 'Rqst'

from
(select
    groups.last_name                        AS Group_Name
    ,count(chg_ref_num)                         AS 'CO'
from chg
left join   ca_contact groups on chg.group_id = groups.contact_uuid
left join   ca_contact assignee on chg.assignee = assignee.contact_uuid
left join   ca_company cc on  assignee.company_uuid = cc.company_uuid
where   groups.last_name in ('8197 Qlikview Support', '8202 OBIEE-BIP'
                        , '8205 BI SAS', '8206 BI CCBI', '8208 BI ePlan Reporting and Support'
                        , '8211 BI Data Quality', '8212 BI EPM Report Architect/Developer'
                        , '8213 BI EPM Framework Architect/Developer', '8214 BI EPM User Experience'
                        , '8215 BI EPM OLAP Architect/Developer', '8219 BI Data Warehouse')
and status = 'CL'
and     convert(varchar, dateadd(hh,-8,dateadd(ss,chg.close_date, '1970')), 101)  >= DATEADD(month, datediff(month, 0, getdate()), 0)
and     parent is NULL
and     cc.company_name = 'XYZ'
group by    groups.last_name) as CO

full outer join
(select
groups.last_name                        AS Group_Name
    ,count(ref_num)                         AS Requests

from call_req cr
left join   ca_contact groups on cr.group_id = groups.contact_uuid
left join   ca_contact assignee on cr.assignee = assignee.contact_uuid
left join   ca_company cc on  assignee.company_uuid = cc.company_uuid
where   groups.last_name in ('8197 Qlikview Support', '8202 OBIEE-BIP'
                        , '8205 BI SAS', '8206 BI CCBI', '8208 BI ePlan Reporting and Support'
                        , '8211 BI Data Quality', '8212 BI EPM Report Architect/Developer'
                        , '8213 BI EPM Framework Architect/Developer', '8214 BI EPM User Experience'
                        , '8215 BI EPM OLAP Architect/Developer', '8219 BI Data Warehouse')
and     cr.status in ('CL')
and     convert(varchar, dateadd(hh,-8,dateadd(ss,cr.close_date, '1970')), 101)  >= DATEADD(month, datediff(month, 0, getdate()), 0)
and     cr.parent is NULL
and     cr.type = 'R'
and     cc.company_name = 'XYZ'
group by    groups.last_name) as Requests
on co.group_name = requests.group_name

full outer join
(select
groups.last_name                        AS Group_Name
    ,count(ref_num)                     AS Problems

from call_req cr
left join   ca_contact groups on cr.group_id = groups.contact_uuid
left join   ca_contact assignee on cr.assignee = assignee.contact_uuid
left join   ca_company cc on  assignee.company_uuid = cc.company_uuid
where   groups.last_name in ('8197 Qlikview Support', '8202 OBIEE-BIP'
                        , '8205 BI SAS', '8206 BI CCBI', '8208 BI ePlan Reporting and Support'
                        , '8211 BI Data Quality', '8212 BI EPM Report Architect/Developer'
                        , '8213 BI EPM Framework Architect/Developer', '8214 BI EPM User Experience'
                        , '8215 BI EPM OLAP Architect/Developer', '8219 BI Data Warehouse')
and     cr.status in ('CL')
and     convert(varchar, dateadd(hh,-8,dateadd(ss,cr.close_date, '1970')), 101)  >= DATEADD(month, datediff(month, 0, getdate()), 0)
and     cr.parent is NULL
and     cr.type = 'P'
and     cc.company_name = 'XYZ'
group by    groups.last_name) as Problems
on  requests.group_name = problems.group_name

full outer join
(select
groups.last_name                        AS Group_Name
    ,count(ref_num)                         AS Incidents

from call_req cr
left join   ca_contact groups on cr.group_id = groups.contact_uuid
left join   ca_contact assignee on cr.assignee = assignee.contact_uuid
left join   ca_company cc on  assignee.company_uuid = cc.company_uuid
where   groups.last_name in ('8197 Qlikview Support', '8202 OBIEE-BIP'
                        , '8205 BI SAS', '8206 BI CCBI', '8208 BI ePlan Reporting and Support'
                        , '8211 BI Data Quality', '8212 BI EPM Report Architect/Developer'
                        , '8213 BI EPM Framework Architect/Developer', '8214 BI EPM User Experience'
                        , '8215 BI EPM OLAP Architect/Developer', '8219 BI Data Warehouse')
and     cr.status in ('CL')
and     convert(varchar, dateadd(hh,-8,dateadd(ss,cr.close_date, '1970')), 101)  >= DATEADD(month, datediff(month, 0, getdate()), 0)
and     cr.parent is NULL
and     cr.type = 'I'
and     cc.company_name = 'XYZ'
group by    groups.last_name) as Incidents
on requests.group_name = incidents.group_name

order by 'SD Groups' asc

Here are the results:
Group_Name                                     CO  Inc Prob Rqst
8197 Qlikview Support                           0   1   0   7
8202 OBIEE-BIP                                  0   4   0   11
8205 BI SAS                                     0   11  1   11
8206 BI CCBI                                   10   17  0   43
8208 BI ePlan Reporting and Support             0   0   0   4
8211 BI Data Quality                            0   0   0   12
8212 BI EPM Report Architect/Developer          0   3   1   5
8214 BI EPM User Experience                     0   2   0   0
8214 BI EPM User Experience                     0   0   1   0
8215 BI EPM OLAP Architect/Developer            0   15  0   2
8219 BI Data Warehouse                         16   71  4   13

Notice two rows for Group 8214. Each group should be represented once and the desired result for Group 8214 should be:
Group_Name                                     CO  Inc Prob Rqst
8214 BI EPM User Experience                     0   2   1   0

What am I doing wrong? I think it has to do with the coalesce function. I tried other methods including
isnull(isnull(isnull(co.group_name, requests.group_Name), incidents.group_Name), problems.group_Name)

but with the same bad result.

A: This is just a shot in the dark based on the code you have posted, but I noticed your joins are inconsistent.
group by    groups.last_name) as Requests
on co.group_name = requests.group_name
group by    groups.last_name) as Problems
on  requests.group_name = problems.group_name
group by    groups.last_name) as Incidents
on requests.group_name = incidents.group_name
I think that it's creating a duplicate for 8214 because of the result set in one of the inline select statements, but I'd have to have access to the data to be sure.
As a minimum, I'd suggest that you format each 'JOIN ON' clause  with "co.group_name = new.group_name"
This may also be because of your full outer join which I'm not sure you need. I'm pretty sure Full Join will provide a line for every group which is encountered in each query and merge the results, however it's your work.


text:
Q: Error: Incorrect syntax near '@variable' in stored procedure in azure sql database I am trying to create a stored procedure with parameters in an Azure SQL Database - Basic Managed Instance, through the Query Editor.
Any time I make reference to any parameter, I get a syntax error, independently of the rest of the SQL code.
I have been successful creating stored procedures without parameters.
Even the simplest code leads to an error:
CREATE PROCEDURE testProcedure
   @masterPassword varchar(50)
AS
BEGIN

    OPEN MASTER KEY DECRYPTION BY PASSWORD = @masterPassword;

END

I would not expect any errors. However, I still receive this error:
Failed to execute query. Error: Incorrect syntax near '@masterPassword'.

A: Try this -
CREATE OR ALTER PROCEDURE testProcedure
   @masterPassword varchar(50)
AS
BEGIN
    DECLARE @SELECT NVARCHAR(MAX);

    SELECT @SELECT=N'OPEN MASTER KEY DECRYPTION BY PASSWORD = ''' + @masterPassword + ''' '; --Expecting String

    EXEC (@SELECT);

END

--UNIT TESTING-
--error
 select ''' + @in + '''

--corrected method
declare @a nvarchar(50),@in varchar(50);
set @in=cast('hi' as varchar(50));
select @a=' select ''' + @in + ''' ';
exec (@a)


text:
Q: VBA Microsoft Outlook Mail Handling - Adding Another Case In 'ThisOutlookSession' I have this sub which catches a specific attachment. How can I add another condition whereby another particular mail item and attachment is picked up?
Private Sub Items_ItemAdd(ByVal item As Object)

    On Error GoTo ErrorHandler

    'Only act if it's a MailItem
    Dim Msg As Outlook.MailItem
    If TypeName(item) = "MailItem" Then
        Set Msg = item

        'Change variables to match need. Comment or delete any part unnecessary.
        If (Msg.SenderName = "Sender") And _
            (Msg.Subject = "Sub") And _
            (Msg.Attachments.Count >= 1) Then

            'Set folder to save in.
            Dim olDestFldr As Outlook.MAPIFolder
            Dim myAttachments As Outlook.Attachments
            Dim Att As String

            'location to save in.  Can be root drive or mapped network drive.
            Const attPath As String = "Z:\Folder\Folder\"

            ' save attachment
            Set myAttachments = item.Attachments
            Att = myAttachments.item(1).DisplayName
            myAttachments.item(1).SaveAsFile attPath & Att

            ' mark as read
            Msg.UnRead = False
        End If

    End If

ProgramExit:
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ProgramExit
End Sub

A: You can use If-Then-Else statements or Case statements to perform a conditional branch in VBA code. Samples are provided below from preceding MSDN links.
If-Then-Else Statement
If dayW = DayOfWeek.Wednesday Then
    If hour = 14 Or hour = 15 Then
        Return True
    Else
        Return False
    End If
ElseIf dayW = DayOfWeek.Thursday Then
    If hour = 12 Then
        Return True
    Else
        Return False
    End If
Else
    Return False
End If

Case Statement
Select Case number
    Case 1 To 5
        Debug.WriteLine("Between 1 and 5, inclusive")
        ' The following is the only Case clause that evaluates to True. Case 6, 7, 8
        Debug.WriteLine("Between 6 and 8, inclusive")
    Case 9 To 10
        Debug.WriteLine("Equal to 9 or 10")
    Case Else
        Debug.WriteLine("Not between 1 and 10, inclusive")
End Select

If your computer isn't on then your VBA code will never get executed.


text:
Q: Set values in Pandas one dataframe based on rows in second dataframe I have two dataframes df1 and df2 and I want to create a new column in df1 and set values in that column to 0 where rows in df1 are contained in df2.  More specifically:
sample_data_1 = {'col1': ['80', '8080'], 'col2': ['0.0.0.0', '143.21.7.165']}
df1 = pd.DataFrame(data=sample_data_1)

sample_data_2 = {'col1': ['80', '8080', '1', '8888'], 'col2': ['0.0.0.0', '143.21.7.165', '1', '5.5.5.5'], 'col3': ['1','2','3']}
df2 = pd.DataFrame(data=sample_data_2)

     col1          col2
0    80         0.0.0.0
1  8080    143.21.7.165

   col1          col2 col3
0    80       0.0.0.0    1
1  8080  143.21.7.165    2
2     1             1    3
3  8888       5.5.5.5    4

I would like to add a column to df1 and set those values to 0 where col1 and col2 in df1 match col1 and col2 in df2.  The resultant dataframe should look like:
    col1          col2    score
0    80         0.0.0.0   0
1  8080    143.21.7.165   0

When the dataframe sizes are the same, I can do a straight comparison using .loc function and logical and's, but when they have different shapes I get "unable to compare series" exceptions.  Thoughts?
Thanks for the help!

A: You can use df.merge:
In [2735]: df1 = df1.merge(df2, on=['col1','col2']).drop('col3',1).assign(score=0)

In [2737]: df1
Out[2737]:
   col1          col2  score
0    80       0.0.0.0      0
1  8080  143.21.7.165      0

A: If the entries in col1 are not identical, you could set col1 as index.
Precisely:
df = df2.set_index('col1').reindex(df1.set_index('col1').index)
df['score']=0
df.reset_index(inplace=True)

A: Check membership by zipping a common column in df1, df2 This returns boolean
Using np.where(condition, if condition, not condition), calculate your desired output
import numpy as np

df1['score']=np.where([x in y for x,y in zip(df1.col1,df2.col1)],0,'not available')

    col1     col2          score
0   80      0.0.0.0         0
1   8080    143.21.7.165    0


text:
Q: Unable to create .tar.gz file from binary buffer in Node.js I am trying to simply read a .tar.gz file from a source (Salesforce) and save it to disk. I am using the jsforce library in Node (5.6.0) to connect to Salesforce. When I retrieve a .txt file and save it -- it works fine with no problems.
conn.requestGet('/services/data/v37.0/sobjects/ContentVersion/XXXX/VersionData', {}, function(err, data) {
  var bitmap = new Buffer(data, 'binary');
  fs.writeFileSync('new_file.txt', bitmap, {
    encoding: 'binary'
  });
});

But I am having problems when using trying to save the file as .tar.gz. If I use the same fs.writeFileSync -- then the file will save but it's not in the right format and I can't open it. In the below code I am using the tar.gz and streamifier to convert my Buffer to a Stream but it doesn't work. I have also tried stream-buffers but I get the same problem.
conn.requestGet('/services/data/v37.0/sobjects/ContentVersion/XXXX/VersionData', {}, function(err, data) {
  var bitmap = new Buffer(data, 'binary');
  var read = streamifier.createReadStream(bitmap);
  var write = targz().createWriteStream('new_file.tar.gz');
  read.pipe(write);
});

The error I get is:
events.js:154
  throw er; // Unhandled 'error' event
  ^
Error: incorrect header check
at Zlib._handle.onerror (zlib.js:363:17)

My problem seems similar to Node.js: Download file from s3 and unzip it to a string but since I am using .tar.gz files, then the suggestions there don't seem to help.

A: The problem in your case is that you want a string or a buffer to be compressed and written to a zip file, while the variable 'read' is actually a normal buffer stream, not a compressed one.
Similarly, the problem with the tar.gz module and the targz() function is that it neither provides a mechanism to write normal data into a compressed stream, nor provides clarity in the documentation. I spent some time reading the documentation and realized that it is designed to work with files and folders only, not with in-memory data.
If you use the zlib module from the node foundation, your problem can be resolved easily, and cleanly.
#cat t.js
var fs = require('fs');
var zlib = require('zlib');

var str = 'hello compressed world!';
zlib.gzip(str, function(err, buffer) {
  if(err) {
    console.log(err);
    return;
  }
  fs.writeFile('./foo.gz', buffer, function(err, b) {
  if(err) {
    console.log(err);
    return;
  }
});
});
#node t.js
#file foo.gz
foo.gz: gzip compressed data, from Unix
#gunzip foo.gz
foo already exists -- do you wish to overwrite (y or n)? y
#cat foo
hello compressed world!#

Hope this helps your case.


text:
Q: Maximum recursion depth exceeded in comparison in python? I'm trying to find each node distance from the starting node and the connections between the nodes is given in a dictionary
My code works well with small dictionary like this example but the problem with  dictionaries with more than 20 nodes I got an error
    if child != parent and child not in my_list:
RecursionError: maximum recursion depth exceeded in comparison

I'm stuck here, can anyone help me?

My code
def compute_distance(node, dic, node_distance, count, parent, my_list):
    children = dic[node]
    node_distance[node].append(count)
    for child in children:
        if child != parent and child not in my_list:
            compute_distance(child, dic, node_distance, count + 1, node, children)
    node_distance_dic = {}
    node_distance_dic = {k: min(v) for k, v in node_distance.items()}
    return node_distance_dic

if __name__ == '__main__':
    starting_node = 9
    dic = {0: [1, 3], 1: [0, 3, 4], 2: [3, 5],
                3: [0, 1, 2, 4, 5, 6], 4: [1, 3, 6, 7],
                5: [2, 3, 6], 6: [3, 4, 5, 7, 8],
                7: [4, 6, 8, 9], 8: [6, 7, 9], 9: [7, 8]}
    print(compute_distance(starting_node, dic, defaultdict(list), 0, 0, []))

Output(key = node, value = distance)
{0: 4, 1: 3, 2: 4, 3: 3, 4: 2, 5: 3, 6: 2, 7: 1, 8: 1, 9: 0}

A: I guess my_list is here to keep track of the nodes already visited, but you never update it. Therefore, you should add the node you are processing in order not to call recursion on nodes that you already went through. Currently, your code goes in infinite loop as soon as there is a cycle in the graph. Plus, don't forget to pass it to the next level:
def compute_distance(node, dic, node_distance, count, parent, my_list):
    my_list.append(node)
    ...
    compute_distance(child, dic, node_distance, count + 1, node, my_list)
    ...

However, this method does not compute the shortest path from the starting node to every other, it just do a simple traversal of the graph (underlying algorithm is DFS).
In order to implement what you want, that is the min distance from the source to every other node, you should look into Breadth-First Search (commonly called BFS).
It will solve your problem in linear time.

A: Doesn't really have anything to do with the graph size. You already have an infinite recursion even for this tiny graph:
dic = {0: [1, 3], 1: [2, 0], 2: [3, 1], 3: [0, 2]}
compute_distance(0, dic, defaultdict(list), 0, 0, [])


text:
Q: File readable but saved in binary mode I wrote a very simple function that saves a file in binary mode with the support of qt. The file is saved correctly and the data inside is correct, however if I open the file with a text editor I can read strings that I shouldn't be reading.
void Game::saveRanking() const
{
    QFile file(".ranking.dat");
    file.open(QFile::WriteOnly);

    QJsonObject recordObject;

    QJsonArray rankingNameArray;
    for (int i = 0; i < 5; i++)
        rankingNameArray.push_back(QJsonValue::fromVariant(QVariant(highscoreName[i])));
    recordObject.insert("Ranking Name", rankingNameArray);

    QJsonArray rankingScoreArray;
    for (int i = 0; i < 5; i++)
        rankingScoreArray.push_back(QJsonValue::fromVariant(QVariant(highscoreValue[i])));
    recordObject.insert("Ranking Value", rankingScoreArray);

    QJsonDocument doc(recordObject);
    file.write(doc.toBinaryData());
}

I've filled the arrays like this, for debugging purposes
highscoreName[0] = "Pippo"; highscoreValue[0] = 100;
highscoreName[1] = "Franco"; highscoreValue[1] = 300;
highscoreName[2] = "Giovanni"; highscoreValue[2] = 200;
highscoreName[3] = "Andrea"; highscoreValue[3] = 4000;
highscoreName[4] = "AI"; highscoreValue[4] = 132400;

I tried to do a hexdump and the result is the following
0000-0010:  71 62 6a 73-01 00 00 00-a4 00 00 00-05 00 00 00  qbjs.... ........
0000-0020:  9c 00 00 00-14 04 00 00-0c 00 52 61-6e 6b 69 6e  ........ ..Rankin
0000-0030:  67 20 4e 61-6d 65 00 00-48 00 00 00-0a 00 00 00  g.Name.. H.......
0000-0040:  34 00 00 00-05 00 50 69-70 70 6f 00-06 00 46 72  4.....Pi ppo...Fr
0000-0050:  61 6e 63 6f-08 00 47 69-6f 76 61 6e-6e 69 00 00  anco..Gi ovanni..
0000-0060:  06 00 41 6e-64 72 65 61-02 00 41 49-8b 01 00 00  ..Andrea ..AI....
0000-0070:  8b 02 00 00-8b 03 00 00-0b 05 00 00-0b 06 00 00  ........ ........
0000-0080:  94 0f 00 00-0d 00 52 61-6e 6b 69 6e-67 20 56 61  ......Ra nking.Va
0000-0090:  6c 75 65 00-20 00 00 00-0a 00 00 00-0c 00 00 00  lue..... ........
0000-00a0:  8a 0c 00 00-8a 25 00 00-0a 19 00 00-0a f4 01 00  .....%.. ........
0000-00ac:  0a a6 40 00-0c 00 00 00-68 00 00 00              ..@..... h...

A: The toBinaryData() gives the internal representation data, not text, so it is normal you have binary data in the file.

QByteArray QJsonDocument::toBinaryData() const

From docs:

Returns a binary representation of the document.

Also it is deprecated:

This function is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

You should use toJson().


text:
Q: Why is z-index ignored with position:static? See this comment from jquery-ui
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned

I see that jquery's zIndex() returns 0 if the element is position: static.
Isn't z-index supported on position:static? (It works for me in Chrome, haven't tested cross-browser)

A: Because position: static means "Ignore all the positioning instructions from left, top, z-index, etc.".
'z-index'
Value:      auto | <integer> | inherit
Initial:    auto
Applies to:     positioned elements

— http://www.w3.org/TR/CSS21/visuren.html#z-index

An element is said to be positioned if its 'position' property has a value other than 'static'.

— http://www.w3.org/TR/CSS21/visuren.html#positioned-element

A: z-index is not ignored for flex-items (immediate children of flex-container, element with display: flex or display: inline-flex) or grid-items (immediate children of grid-container, element with display: grid or display: inline-grid).
Specs quotation
From W3C Flexbox specs:

Flex items paint exactly the same as inline blocks CSS21, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

From W3C CSS Grid Layout specs:

Grid items can overlap when they are positioned into intersecting grid areas, or even when positioned in non-intersecting areas because of negative margins or positioning. The painting order of grid items is exactly the same as inline blocks CSS21, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static (behaving exactly as if position were relative). Thus the z-index property can easily be used to control the z-axis order of grid items.

Flexbox example
So assume we have this layout with overlapping (.flex-item-two overlaps .flex-item-one using e.g. negative margins):

.flex {
  display: flex;
  align-items: center;
}

.flex-item-one {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-right: -50px;
}

.flex-item-two {
  width: 200px;
  height: 200px;
  background-color: green;
}

One

Two

If flex-item-one index is bigger than .flex-item-two's, .flex-item-one then overlaps .flex-item-two.

.flex {
  display: flex;
  align-items: center;
}

.flex-item-one {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-right: -50px;
  z-index: 1;
}

.flex-item-two {
  width: 200px;
  height: 200px;
  background-color: green;
}

One

Two

CSS Grid example

#grid {
  display: inline-grid;
  width: 250px;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr
}

#A {
  grid-column: 1 / span 2;
  grid-row: 2;
  align-self: end;
  background-color: #4f81bd;
}

#B {
  grid-column: 1;
  grid-row: 1;
  z-index: 10;
  background-color: #8064a2;
}

#C {
  grid-column: 2;
  grid-row: 1;
  align-self: start;
  margin-left: -20px;
  background-color: #f79646;
}

#D {
  grid-column: 2;
  grid-row: 2;
  justify-self: end;
  align-self: start;
  background-color: #9bbb59;
}

#E {
  grid-column: 1 / span 2;
  grid-row: 1 / span 2;
  z-index: 5;
  justify-self: center;
  align-self: center;
  background-color: #c0504d;
}

#grid > * {
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 40px;
  font-size: 32px;
}

#C, #D {
  padding: 10px 20px;
}

A

B

C

D

E


text:
Q: How to initialize custom QQuickItem in Qt I have implemented custom QQuickItem which is exposed to QML. Now it becomes more useful item in all platforms but due some reasons in Windows we are not using QML it's pure QT Application.
But I am not able to instantiate custom QQuickItem in Qt, could some one help me out of this?
Here is the code:
customItem.h
#include <QQuickItem>
#include <QQuickWindow>

class CustomItem : public QQuickItem
{
Q_OBJECT
public:
explicit CustomItem(QQuickItem *parent = 0);

signals:

public slots:
void paint();

private slots:
void handleWindowChanged(QQuickWindow * win);

};

customItem.cpp:
#include "customItem.h"

CustomItem::CustomItem(QQuickItem *parent) :
QQuickItem(parent)
{
connect(this, &CustomItem::windowChanged, this, &CustomItem::handleWindowChanged);
}

void CustomItem::paint()
{
QQuickWindow * win = window();
qreal ratio = win->devicePixelRatio();
int w = int(ratio * win->width());
int h = int(ratio * win->height());
glViewport(0, 0, w, h);

glDisable(GL_DEPTH_TEST);
glClearColor(0, 1, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);

}

void CustomItem::handleWindowChanged(QQuickWindow * win)
{
if (win) {
connect(win, &QQuickWindow::beforeRendering, this, &CustomItem::paint, Qt::DirectConnection);
    win->setClearBeforeRendering(false);
}

}

main.cpp:
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQuickView  *view = new QQuickView ();
    QWidget *container = QWidget::createWindowContainer(view);

    CustomItem *customitem = new CustomItem();///how can i set it view
    container->show();

    return app.exec();
}

Issue:
Not able to instantiate CustomItem


text:
Q: How to install gcc 9.X on RHEL8? I see from the documentation here that gcc has been updated on RHEL8, but what I haven't figured out is how to get it.
The documentation indicates that there are now two streams, but I already have both and gcc is still at 8.X.
If I go through dnf with dnf search gcc | grep 9 there are a great deal of references to gcc v9, but no way to actually install it. There is something called gcc-toolset-9, but after checking it out, it is unrelated to the core gcc version.

A: I feel foolish because I figured it out right after posting, but I figured I'd share because it isn't intuitive and hopefully this will save someone some time.
The package you want to install is not gcc. You want to install gcc-toolset-9. You will notice after installation that you will still get 8.x if you do a gcc --version. gcc-toolset-9 installs to /opt. The idea is to give you a separate development environment. See this documentation. After installation you can run the updated gcc with /opt/rh/gcc-toolset-9/<username>/bin/gcc.
As @Stephen Kitt pointed out, you can actually get a shell with the updated toolset by running scl enable gcc-toolset-9 bash. Running this command will open a new bash session with the environment variables appropriately updated.
You can also run gcc v.9 directly with scl enable gcc-toolset-9 gcc <your_gcc_args>. See this documentation for details.


text:
Q: Implementing loops on the basis of condition in C I have a set of statements that need to be executed in two different loops; the loops identified on the result of a check condition. There are multiple such sets of this type.
Set A : statement 1
        statement 2
        statement 3

Set B : statement 4
        statement 5
        statement 6

and so on..

Now they need to be executed as follows:
if(condition 1)
    loop over some Loop A
        execute Set A
else if(condition 2)
    loop over some loop B
        execute Set A

These loops can be completely different from each other.

Now, for the sake of code clarity, I don't wish to write the code as mentioned above. Another reason being I'll have to make multiple sets in order to group them together.
Is there any mechanism by which I could achieve the following:
CHECK_CONDITION_AND_LOOP_HERE
    execute Set A

I've tried using macros to achieve this, using braced-group within expression but could not . I also tried using ternary operators as well as fall through a switch case to achieve this, but could not get the same result.
Is there any way in C using which I could achieve the desired behavior?
Sample code for the problem:
if(condition A)
    for(i=0; i<10; i++, k*=2) {
        execute Set A;  //Operations performed here use variable k
    }
else if(condition B)
    for(j=5; j<75; j+=5, k*=arr[j]) {
        execute Set A;  //Operations performed here use variable k
    }

A: The answer to Version 1 of the question:
Given that the only difference is the range of values over which the statements are executed, you can use a couple of variables to store the range end-points, e.g.
int first = 0;
int last = -1;

if (condition1) {
    first = 1;
    last = 10;
} else if (condition2) {
    first = 3;
    last  = 7;
}

for ( int i = first; i <= last; i++ )
    execute set A

Note that initializing last to be less than first prevents the body of the loop from running if neither condition is met.

The answer to Version 2 of the question:
Here's the code from the question. I've made some changes for clarity, and to make the question more concrete.
if (cond1)
    for (initA;condA;updateA)
        execute SetX
else if (cond2)
    for (initB;condB;updateB)
        execute SetX

Here's the refactored code
int is1 = cond1;
int is2 = is1 ? 0 : cond2;

if (is1)
    initA;
if (is2)
    initB;

while ( (is1 && condA) || (is2 && condB) )
{
    execute SetX
    if ( is1 )
        updateA;
    if ( is2 )
        updateB;
}

A: A function, maybe?
void func_A() {
    printf("Here0\n");
    printf("Here1\n");
}

...

if(a < b) {
    for(i = 1; i <= 10; i++) {
        func_A()
    }
}
else if(a == b) {
    for(i = 3; i <= 7; i++) {
        func_A()
    }
}

Or if you want to only make one call/block:
if(a < b) {
    min = 1; max = 10;
}
else if(a == b) {
    min = 3; max = 7;
}
for(i = 3; i <= 7; i++) {
    printf("Here0\n");
    printf("Here1\n");
}


text:
Q: calling an method in a view controller from a child view In my ViewController I have created a view which contains a button and a bunch of other elements.  When the button is pressed I want to call a method from the parent ViewController.  I tried:
[self.superview buttonPressedMethod];

But the superview is no the ViewController but UIView.  Is there anyway to do this?

A: This is exactly what the target/action mechanism is for. Make the method in the view controller an IBAction. Set the view controller as the button's target, and set the method as its action. That should be all you need to do.

A: At ParentViewController.h
-(void)ParentMethod;

At ParentViewController.m
-(IBAction)button:(id)sender {
       [self ParentMethod];
}

At IBAction of Play Button on child view controller do this:
-(IBAction)ChildMethod:(id)sender {
       ParentViewController *parent=self.parentViewController;
       [parent ParentMethod];
}

A: Better create delegate in view controller and set delegate in child view, so when something occur call delegate method according to it.


text:
Q: Replace specific char in string How can I replace this char \\ by \ by using javascript or jQuery? I tried this:
var string = "ABC\\testUserName"
var newString = string.replace("\\", "\")

I get this error:

Uncaught SyntaxError: Unexpected token ILLEGAL

A: The \ is the escape character, so you need to double them in your replace() call for them to be taken as a single instance. Try this:

var string = "ABC\\testUserName"
var newString = string.replace("\\\\", "\\");
console.log(newString);


text:
Q: Cannot create stored procedure mysql syntax error I'm experiencing a serious headache while trying to create a stored procedure.
DELIMITER $$
create PROCEDURE insertDummyUser(rank int unsigned)

BEGIN
INSERT INTO tbl (name, rank) VALUES ('DummyUser', rank);
END$$

It gives me the following error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5
I just cant wrap my head around this. It looks fine to me.
I'm just starting out with these stored procedures, so any help at all is greatly appreciated :)

A: The following stored procedure runs smoothly:
DELIMITER $$

CREATE PROCEDURE `insertDummyUser`(`p_rank` INT UNSIGNED)
BEGIN
  INSERT INTO `tbl` (`name`, `rank`) VALUES ('DummyUser', `p_rank`);
END$$

DELIMITER ;


text:
Q: How to display an image in every page of a table in MIcrosoft Report rdlc I was wondering if anyone has an idea of how to display an image in every page of a Microsoft Report rdlc that has a table.
I'm using Visual Studio 2013 ultimate, c#, asp.net 4.5, sql 2008
This is a very simple report: ReportS4.rdlc
It has one image at the top of the body, (not a header) and a tablix after it.
Everything works fine, except the image is only displayed in the first page of the report.
I tried setting the RepeatWith to the tablix id with no success.
Thanks for the help
rubenc


text:
Q: How to pull all data from couch DB into R Need help to pull all data from couch DB.
Inside Couch DB I have one database named "resume"
    Inside that resume database number of id contain data.
    I need all id data inside a data frame.
Need help, any snipped code will be very helpful for me.

A: One way to do it is transform the output to CSV right in CouchDB. I did this in a project once (not R, but also a tool to do statistics) and it worked quite well. You can use list functions of CouchDB for that: it gives you an iterator over the view's output plus methods for writing to the HTTP response. The following link gives you a lot of information on this: http://docs.couchdb.org/en/1.6.1/couchapp/ddocs.html#list-functions
Hope this helps - let us know...


text:
Q: How to pop characters from the list and make them variable name in Python? How do I pop character from a certain list and make it my variable name?
For example:
list1=['a','b','h','j']

In this case, how do I remove 'a','b','h','j' from the list and make it a variable?
a=input("Enter a name")
b=input("Enter a name")
h=input("Enter a name")
j=input("Enter a name")

I have dynamically created the list in my project where the contents of the list are appended from some other action.

A: Depending on if you want these variables as local or global. For global you can use:
while list1:
    variable = list1.pop()
    globals()[variable]=input("Enter a name")

For local, just replace globals() with locals()

Or you can go with a dictionary. Pop the items from list to be keys and assign value to those keys.


text:
Q: Logging to MySQL without empty rows/skipped records? I'm trying to figure out how to make Squid proxy log to MySQL. I know ACL order is pretty important but I'm not sure if I understand exactly what ACLs are or do, it's difficult to explain, but hopefully you'll see where I'm going with this as you read!
I have created the lines to make Squid interact with a helper in squid.conf as follows:
external_acl_type mysql_log %LOGIN %SRC %PROTO %URI php /etc/squid3/custom/mysql_lg.php
acl ex_log external mysql_log
http_access allow ex_log

The external ACL helper (mysql_lg.php) is a PHP script and is as follows:
error_reporting(0);

if (! defined(STDIN)) {
    define("STDIN", fopen("php://stdin", "r"));
}

$res = mysql_connect('localhost', 'squid', 'testsquidpw');
$dbres = mysql_select_db('squid', $res);

while (!feof(STDIN)) {
    $line = trim(fgets(STDIN));
    $fields = explode(' ', $line);
    $user = rawurldecode($fields[0]);
    $cli_ip = rawurldecode($fields[1]);
    $protocol = rawurldecode($fields[2]);
    $uri = rawurldecode($fields[3]);

    $q = "INSERT INTO logs (id, user, cli_ip, protocol, url) VALUES ('', '".$user."', '".$cli_ip."', '".$protocol."', '".$uri."');";
    mysql_query($q) or die (mysql_error());

    if ($fault) {
            fwrite(STDOUT, "ERR\n");
    };

    fwrite(STDOUT, "OK\n");
}

The configuration I have right now looks like this:
## Authentication Handler
auth_param ntlm program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp
auth_param ntlm children 30

auth_param negotiate program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-basic
auth_param negotiate children 5

# Allow squid to update log
external_acl_type mysql_log %LOGIN %SRC %PROTO %URI php /etc/squid3/custom/mysql_lg.php
acl ex_log external mysql_log
http_access allow ex_log

acl localnet src 172.16.45.0/24
acl AuthorizedUsers proxy_auth REQUIRED

acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https

acl CONNECT method CONNECT

acl blockeddomain url_regex "/etc/squid3/bl.acl"

http_access deny blockeddomain
deny_info ERR_BAD_GENERAL blockeddomain

# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# Allow the internal network access to this proxy
http_access allow localnet

# Allow authorized users access to this proxy
http_access allow AuthorizedUsers

# FINAL RULE - Deny all other access to this proxy
http_access deny all

From testing, the closer to the bottom I place the logging lines the less it logs. Oftentimes, it even places empty rows in to the MySQL table. The file-based logs in /var/log/squid3/access.log are correct but many of the rows in the access logs are missing from the MySQL logs. I can't help but think it's down to the order I'm putting lines in because I want to log everything to MySQL, unauthenticated requests, blocked requests, which category blocked a specific request.
The reason I want this in MySQL is because I'm trying to have everything managed via a custom web-based frontend and want to avoid using any shell commands and access to system log files if I can help it. The end result is to make it as easy as possible to maintain without keeping staff waiting on the phone whilst I add a new rule and reload the server!
Hopefully someone can help me out here because this is very much a learning experience for me and I'm pretty stumped.
Many thanks in advance for any help!

A: the correct php code for you is:
#!/usr/bin/php

<?php

error_reporting(0);

if (! defined(STDIN)) {
    define("STDIN", fopen("php://stdin", "r"));
}

$res = mysql_connect('127.0.0.1', 'root', 'kbpbdxgh9j');
$dbres = mysql_select_db('intranet', $res);

while (!feof(STDIN)) {
    $line = trim(fgets(STDIN));
    $fields = explode(' ', $line);
    $user = rawurldecode($fields[0]);
    $cli_ip = rawurldecode($fields[1]);
    $protocol = rawurldecode($fields[2]);
    $uri = rawurldecode($fields[3]);

    if ($user!="") {

        $q = "INSERT INTO log (usuario, ip, protocolo, url) VALUES ('".$user."', '".$cli_ip."', '".$protocol."', '".$uri."');";
        mysql_query($q) or die (mysql_error());

    if ($fault) {
                fwrite(STDOUT, "ERR\n");
        };

    }

    fwrite(STDOUT, "OK\n");
}

A: I would suggest following these instructions on how to enable logging of all ACL requests/allows/denies. From these you should be able to figure out which ACL rules are being applied correctly/incorrectly.


text:
Q: Difference between Graphql with non-Graphql React-Mongoose App Why should I use graphql if I setup a react frontend and mongo db backend?
And Why should i put graphql server between mongo db and react?

A: Since you didn't mention what is your alternative API style I will just assume it's REST. GraphQL gives you many features a plain old REST api won't have out of the box.
This is probably the best answer listing advantages and disadvantages of both.
You already have validation(via mongoose schemas), but using GQL you can get:

*

*excellent documentation for your API generated for you

*avoid underfetching/overfetching on frontend

*ability to batch FE requests easily

*you can tap into a very rich ecosystem of GraphQL tooling which only gets better as time passes

*easier testing-you can just execute your graphql queries on backend even without sending them over the network saving a little bit of performance overhead

I believe you should use GraphQL for any non trivial API, because it adds ton of typesafety and the price you pay as a developer is very low.


text:
Q: Git Diff Indent/Pretty Print/Beautify Before Diff Is there a way to make Git indent/beautify/pretty print two versions of C++ source files before diffing them?
I don't want Git to show me the myriads of changes introduced after someone auto-formatted the code.
Example usage: I hit git difftool --indent-before-diffing path/to/file and get the changes after both the original version of path/to/file and the modified version of path/to/file have been indented.

A: If you can find an application that does the indenting for you, you could use the method described here for odt files:

Add the following line to your .gitattributes file:
*.odt diff=odt
Now set up the odt diff filter in .git/config:
[diff "odt"]
    binary = true
    textconv = /usr/local/bin/odt-to-txt

So for C++ files it would be something like this:
*.cpp diff=cpp

And in the .git/config:
[diff "cpp"]
    textconv = /path/to/indenter

As pointed out in the comments, GNU Indent can be used for indenting.


text:
Q: How to check if a TypedPipe or a ValuePipe are empty in Scalding? In Scalding, suppose you have a TypedPipe[Long] or ValuePipe[Long]. How would you go about checking whether they are empty in the most elegant/efficient way?
Currently testing the following:
val isTPEmpty: Boolean = typePipe.equals(TypedPipe.empty)
val isVPEmpty: Boolean = valuePipe.equals(EmptyValue)

Or, to make it more generic:
def isTypedPipeEmpty[A](typedPipe: TypedPipe[A]): Boolean = {
  val emptyTP: TypedPipe[A] = TypedPipe.empty
  typedPipe.equals(emptyTP)
}

UPDATE: this doesn't work (will return false for an empty TypedPipe). Appreciate any inputs.

A: After speaking to several people on this, there is no straight solution simply because a TypedPipe is distributed, and checking whether it is empty is "expensive", therefore one should avoid this as much as possible.
If you absolutely have no choice, what worked for me was something "ugly" as creating a temporary empty TypedPipe, then calling mapWithValue on my ValuePipe, and if it is empty do X, otherwise do Y. Something like:
TypedPipe.from(List()).mapWithValue(valuePipe) { case (temp, valuePipe) => if (valuePipe.isEmpty) doX else doY }

But again, cumbersome.


text:
Q: How to run Selenium tests against Internet Explorer under Play? We've got some good selenium tests running against Firefox with Play 2.1
http://www.playframework.com/documentation/api/2.0/scala/play/api/test/Helpers
However even though webdriver does support Internet Explorer, i dont see an IE helper.  Is there any way around this?

A: Based on the Fluentlenium documentation, your test class should extend FluentTest. You can then simply override the getDefaultDriver() method to change the browser:
public class IntegrationTest extends FluentTest {

    @Override
    public WebDriver getDefaultDriver(){
        return new InternetExplorerDriver();
    }

}

You should be able to return any Selenium WebDriver in this method (only tested with IE and FF).


text:
Q: Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState when opening pyspark I ran into a new error today when opening Spark the way I always do. I've never seen the error, but now it is preventing me from running my python scripts.
I have pyspark aliased in my .bash_profile and when I open pyspark from my terminal I get this error:
pyspark.sql.utils.IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"

I found this post: Apache Spark with Python: error
which seemed to be what I needed so I went down the line and tried using sudo and I made sure the mentioned jar file was in place, but I am still receiving the error.
Here are the relevant lines in my .bashrc:
 export PYSPARK_DRIVER_PYTHON=ipython

export SPARK_HOME=/usr/local/spark
export PYTHONPATH=$SPARK_HOME/python:$PYTHONPATH

export HADOOP_HOME=/usr/local/hadoop
export LD_LIBRARY_PATH=$HADOOP_HOME/lib/native/:$LD_LIBRARY_PATH

alias sudo='sudo '
alias pyspark="/usr/local/spark-2.1.0-bin-hadoop2.7/bin/pyspark \
--conf spark.sql.warehouse.dir='file:///tmp/spark-warehouse' \
--packages com.databricks:spark-csv_2.11:1.5.0 \
--packages com.amazonaws:aws-java-sdk-pom:1.10.34 \
--packages org.apache.hadoop:hadoop-aws:2.7.3 \
--packages org.mongodb.spark:mongo-spark-connector_2.10:2.0.0"

Any suggestions?


text:
Q: positioned elements disappear under next positioned element in the flow in MSIE7 sometimes got into this problem but I have always avoided it using some alternative code.
Unfortunately, this time I need a hand.
in IE7 if two brother DIVS have "position:relative" absolute-positioned children of them disappear under the "next brother DIV"
http://jsfiddle.net/qN74X/

XXX

ZZZ

YYY

how can I solve this?
thanks

A: When hovering over the element, set it's z-index as well (not just the tip). Here's the main change:
body > div{
    position:relative;
    z-index:1;
}
body > div:hover{
    z-index:5;
    border:0 none;
}

Basically, on the outer container (where the background was) was what needed to have it's z-index changed. I am also unsure of why I needed to put border:0 none but without it, it didn't work.
jsfiddle: http://jsfiddle.net/qN74X/3/


text:
Q: Kubernetes NLB TLS Termination and re-encryption with TLS as the backend protocol - what certificate is used for SSL with the backend? I have created a kubernetes service that uses an NLB with the following annotations
service.beta.kubernetes.io/aws-load-balancer-type: nlb
service.beta.kubernetes.io/aws-load-balancer-ssl-cert: arn...
service.beta.kubernetes.io/aws-load-balancer-backend-protocol: ssl

I am able to see that the NLB is able to terminate TLS, it presents the correct certificate and completes the handshake with the client. However, I get an empty response from my backend. When I don't terminate TLS at the NLB everything is fine, I get a valid response, and my backend presents the certificate instead.
My suspicion is that communication is breaking down between the NLB and the backend pods serving the traffic. What certificate is being used for TLS between the backend pods and the NLB in Kubernetes?


text:
Q: OS Heap and OS stack in an multicore OS I am writing a small smp kernel and now I am adding support for the second core.
Here are a few questions that are cropping up
a) I believe each core would have its own stack and that has the be defined in lds file
b) I believe each core would have its own heap (for malloc) and that has the be defined in lds file
c) common data structures should go in bss section
d) For per cpu variables a _per_cpu_area for each core to be set in lds file and a register say r0 would always point to  per cpu section
e) locks across cores to be help in bss section
Are these assumptions correct ?
Please verify or raise any problem

A: Functions have stacks,
Processes have heaps,
   where they all shared by those nasty threads...
Only zero initialized data goes into BSS,
   and you should see Linux's per_cpu...

A: Assuming a preemptive multitasker:

a) I believe each core would have its own stack and that has the be
  defined in lds file

Cores don't have stacks, they have stack pointers that get swapped aroung on thread context-changes.  Threads have stacks.

b) I believe each core would have its own heap (for malloc) and that
  has the be defined in lds file

Cores don't have heaps.  Processes have heaps.

c) common data structures should go in bss section

Maybe, depends if read-only.

d) For per cpu variables a _per_cpu_area for each core to be set in
  lds file and a register say r0 would always point to per cpu section

CPU's don't generally have variables, unless you mean hardware registers, which it appears you do not.

e) locks across cores to be help in bss section

Cores don't have bss sections.  Applications have bss sections. Vars in bss may need locks if multiple threads can access them, no matter whether one core or more.
You need to Google/read more about OS operation - you have some things rather confused.


text:
Q: How to get the structure of JSON in scala I have a lot of JSON files which are not structured and I want to get a deeper element and all the element to get to it.
For example :
{
"menu": {
    "id": "file",
    "popup": {
        "menuitem": {
                  "module"{
                      "-vdsr": "New",
                      "-sdst": "Open",
                      "-mpoi": "Close" }
        ...
    }
}

In this case the result would be :
menu.popup.menuitem.module.-vdsr
menu.popup.menuitem.module.-sdst
menu.popup.menuitem.module.-mpoi

I tried Jackson and Json4s and they are efficient to go the last value but, I don't see how I can get the whole structure.
I want this to run a job with apache spark on very huge JSON files and the structure will be very complex for each. I also tried sparkSQL but if I don't know the entire structure I can't get it.

A: What you're asking to do is essentially a tree traversal of an object, where JSON objects are considered nodes with named branches and other JSON types are considered leaves.  There are many ways to do this.  You might consider making a recursive function that explores the entire tree.  Here is an example that works in PlayJson, but it shouldn't be very different in other libraries:
import play.api.libs.json._
def unfold(json: JsValue): Seq[String] = json match {
    case JsObject(kvps) => kvps.flatMap {
        case (key, value) => unfold(value).map(path => s"$key.$path")
    }
    case _ => Seq("")
}

A: The beauty of the new DataFrame API is that it infers schema automatically, as you load the data.
It does so by doing a one-time pass over the whole data set.
I suggest that you load your json and then play with transformations and see what you can come up with. You can remove or select a subset of columns, filter rows, aggregate, map over them, anything really.
E.g:
// you can use globing to load multiple files
val jsonTbl = sqlContext.load("path to json file", "json")

// print the inferred schema
jsonTbl.printSchema

// now you can use the DataFrame API to transform the data set, e.g.
val outputTbl = jsonTbl
    .filter("menu.popup.menuitem.module.-vdsr = 'Some value'")
    .groupBy("menu.popup.menuitem.module.-vdsr").count
    .select("menu.popup.menuitem.module.-sdst", "other fields/columns")

outputTbl.show


text:
Q: PyStemmer: ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed I'm using the Python package Bag of Words, bow.py (https://github.com/dmiro/bagofwords/blob/master/bow.py).
Basically I'm running the command:
dc = bow.DefaultDocument()
dc.read_text("paragraph string here")

I get the following trace:
Traceback (most recent call last):
  File "bag_of_words.py", line 93, in <module>
    if __name__ == "__main__": main()
  File "bag_of_words.py", line 27, in main
    bag_of_words_classifier_test("item", "category_1", "category_2")
  File "bag_of_words.py", line 73, in bag_of_words_classifier_test
    dc.read_text("paragraph string here")
  File "C:\Users\User Name\Anaconda3\lib\site-packages\bow.py", line 339, in read_text
    self._read(None, text)
  File "C:\Users\User Name\Anaconda3\lib\site-packages\bow.py", line 326, in _read
    words = self.tokenizer(text)
  File "C:\Users\User Name\Anaconda3\lib\site-packages\bow.py", line 306, in tokenizer
    words = self.after_tokenizer(WordFilters, words)
  File "C:\Users\User Name\Anaconda3\lib\site-packages\bow.py", line 517, in after_tokenizer
    words = wordfilters.stemming(self.lang, self.stemming, words)
  File "C:\Users\User Name\Anaconda3\lib\site-packages\bow.py", line 250, in stemming
    import Stemmer as stemmer
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

I thought it might be an issue with PyStemmer, so I tried forcing a pip3 reinstall/upgrade but got the same error. Any thoughts?

A: Okay, so this doesn't really solve the problem, but it is a work-around:
If you open bow.py you can replace line 250 with import snowballstemmer as stemmer (instead of import Stemmer as stemmer) and then replace line 252 with stemmer = stemmer.stemmer(lang) (instead of stemmer = stemmer.Stemmer(lang)). The equivalent methods just require a change from uppercase to lowercase.


text:
Q: Detecting when user leaves page in Page_Load event When a user leaves a page it fires of the Page_Load event again. How can I tell in code_behind that this is happening so in can avoid running the custom functions as the code in the Page_Load does not really need to be ran when leaving the page?

A:
When a user leaves a page it fires of the Page_Load event again

What do you mean by leaving a Page? Closing the browser or clicking Back button on browser? Or moving to another Page? Page_Load method is fired when on Loading Page or when Postback occurs on the same Page, but not leaving it.
Before you start any operations, you can (and you should) ensure that client is still connected and use HttpResponse.IsClientConnected property.
The IsClientConnected property returns false when the following conditions are true:

*

*The connection to the client was terminated. This can occur if the Close method was invoked, or if the client stopped execution of the Web page or browsed to another page.

*The HttpWorkerRequest object that is handling the request is null or the HttpWorkerRequest.IsClientConnected method returns false. If a custom HttpWorkerRequest object handles the request, then the HttpWorkerRequest.IsClientConnected method might be set based on custom criteria. For example, the custom worker request might force a time-out after a period of time.

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx
EDIT
Switching tabs usually fires normal Postback, to detect it you should use:
private void Page_Load(object sender, System.EventArgs e)
{
    if (!Page.IsPostback)
    {
       //this is first load of this page
    }
}

A: If I understand the question correctly, you're looking for the IsPostBack property:

 private void Page_Load()
 {
    if (!IsPostBack)
    {
        // Any code here will only run the first time the page is loaded
    }
}


text:
Q: Turning off Eclipse Validation I want to completely switch off Eclipse validation for all languages.
This is not the same as disabling validation of various patterns, I don't want Eclipse to even try to validate.
Version is Juno.

A:
Click Window > Preferences and select Validation in the left pane. The
  Validation page of the Preferences window lists the validators
  available in your project and their settings.
To disable individual validators, clear the check boxes next to each
  validator that you want to disable. Each validator has a check box to
  specify whether it is enabled for manual validation or on a build.

see here

A: Update for Mac Eclipse:
Disable validation options as per your requirement (you may disable all also).
Eclipse => Preferences => Validation => Disable checkbox (or Disable All) => Apply
Reference screen shot:

A: It might also help to disable Validation Builders:
Project Properties - Builders

A: *

*Click Window > Preferences,

*select Validation in the left pane.

*Check Suspend all validators (2nd check box on the right pane for Juno)

*Click Apply, Click OK


text:
Q: Apache velocity engine 1.7.x tests failure We work on improving smth' in Apache Velocity Engine Source Code, but we have a problem with its tests when we build it.
We cloned the source code from Apache/Velocity on github.
Then we tried to build the engine, but we got this error.
Failed tests:   testVelTools66(org.apache.velocity.test.issues.VelTools66TestCase): Method object does not match! expected:<public abstract java.lang.String org.apache.velocity.test.issues.VelTools66TestCase$TestInterface.getTestValue()> but was:<public java.lang.String org.apache.velocity.test.issues.VelTools66TestCase$TestObject.getTestValue()>
  testResourceLoaderInstance(org.apache.velocity.test.ResourceLoaderInstanceTestCase): Processed template did not match expected output

Tests in error:
  testClasspathResource(org.apache.velocity.test.ClasspathResourceTestCase): Unable to find resource 'template/test1.vm'
  testContextSafety(org.apache.velocity.test.ContextSafetyTestCase): Unable to find resource 'context_safety.vm'
  testHighByteChinese2(org.apache.velocity.test.EncodingTestCase): Unable to find resource 'encodingtest3.vm'
  testChineseEncoding(org.apache.velocity.test.EncodingTestCase): Unable to find resource 'encodingtest.vm'
  testHighByteChinese(org.apache.velocity.test.EncodingTestCase): Unable to find resource 'encodingtest2.vm'
  testRussian(org.apache.velocity.test.EncodingTestCase): Unable to find resource 'encodingtest_KOI8-R.vm'
  testMultiLoader(org.apache.velocity.test.MultiLoaderTestCase): Unable to find resource 'template/test1.vm'
  testSharedRepo(org.apache.velocity.test.StringResourceLoaderRepositoryTestCase): Unable to find resource 'foo'
  testAlternateStaticRepo(org.apache.velocity.test.StringResourceLoaderRepositoryTestCase): Unable to find resource 'foo'
  Arithmetic(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'arithmetic.vm'
  Array(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'array.vm'
  Block(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'block.vm'
  Comment(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'comment.vm'
  Equality(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'equality.vm'
  Escape(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'escape.vm'
  Foreach-array(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'foreach-array.vm'
  Foreach-method(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'foreach-method.vm'
  Foreach-variable(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'foreach-variable.vm'
  Formal(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'formal.vm'
  If(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'if.vm'
  Logical(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'logical.vm'
  Loop(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'loop.vm'
  Method(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'method.vm'
  Quotes(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'quotes.vm'
  Sample(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'sample.vm'
  Shorthand(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'shorthand.vm'
  Test(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'test.vm'
  Diabolical(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'diabolical.vm'
  Pedantic(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'pedantic.vm'
  Subclass(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'subclass.vm'
  Foreach-map(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'foreach-map.vm'
  Include(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'include.vm'
  Escape2(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'escape2.vm'
  Parse(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'parse.vm'
  Velocimacro(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'velocimacro.vm'
  Reference(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'reference.vm'
  Interpolation(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'interpolation.vm'
  Vm_test1(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'vm_test1.vm'
  Map(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'map.vm'
  Literal(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'literal.vm'
  Ifstatement(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'ifstatement.vm'
  Math(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'math.vm'
  Range(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'range.vm'
  Get(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'get.vm'
  Velocimacro2(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'velocimacro2.vm'
  Foreach-type(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'foreach-type.vm'
  Foreach-introspect(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'foreach-introspect.vm'
  Settest(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'settest.vm'
  Newline(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'newline.vm'
  Logical2(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'logical2.vm'
  String(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'string.vm'
  Stop1(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'stop1.vm'
  Stop2(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'stop2.vm'
  Foreach-null-list(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'foreach-null-list.vm'
  Curly-directive(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'curly-directive.vm'
  Comment-eof(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'comment-eof.vm'
  Commas(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'commas.vm'
  Stop3(org.apache.velocity.test.TemplateTestCase): Unable to find resource 'stop3.vm'

Tests run: 444, Failures: 2, Errors: 58, Skipped: 0

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-test) on project velocity: There are test failures.

Please refer to C:\apache\velocity-engine\target\surefire-reports for the individual test results.
-> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

As we think, Generally this message means that failed tests were not able to find templates resources.
Note: these error occurs without any line of editing from us. if you cloned the 1.7.x engine which is in the prev. URL you will get the same error.
I hope that someone has the solution of this issue.
Thanks.

A: It seems it is because of TemplateTestBase.java
public static final String TEST_COMPARE_DIR = "@test.dir@";
public static final String TEST_RESULT_DIR = "@build.test@";

And from build.properties

test.dir=      ${velocity.dir}/test
build.test=      ${build.dir}/test

So if you run tests with ant, you don't have to change the TEST_COMPARE_DIR and TEST_RESULT_DIR, otherwise you may change these string constants to the absolute path accordingly.


text:
Q: is there a "is oneOf" in typescript? I have the following code:
export type Environments = 'live' | 'test' | 'app' | 'localhost'
export const definedEnvironments: Environments[] = ['app', 'live', 'localhost', 'test']

and I have the following function:
export default function verifyEnvironment(env: Environments): boolean {
  return definedEnvironments.includes(env)
}

I am creating a command-line application with node and typescript, where the user has an input to write the environment, the user might input "live", "test", or even "ksvksdbvkjsdv".
So my role is to verify that the user input is correct, that's why I created the function verifyEnvironment.
Now, when I use the function in my code as follows, typescript complains:

const environment = await waitForUserInput("enter the environment name: ")
if (!verifyEnvironment(environment)) {
  return console.error('Allowed options are: ' + definedEnvironments.join(', '))
}

it says:

Argument of type 'string' is not assignable to parameter of type
'Environments'.

it happens in the line 2.
So typescript is correct, the user might input any string.
and I was reading the documentation, and I saw in the Using type predicates section that there's a similar case to mine, they used the is operator to make a function which is used for validation.
Is there a way I can write something like this in typescript, or what is the solution?
export default function verifyEnvironment(env: Environments): env is oneOf Environments {
  return definedEnvironments.includes(env)
}

A: You're trying to assert just env is Environments, but env shouldn't be required to already be an Environments in that case.
You might also be interested in as const to avoid redundancy, and the singular Environment for consistency:
const definedEnvironments = ['live', 'test', 'app', 'localhost'] as const
type Environment = typeof definedEnvironments[number]

function verifyEnvironment(env: string): env is Environment {
  return (definedEnvironments as readonly string[]).includes(env)
}


text:
Q: Display next array items on click I tried to write a click function to display next array items on click function in jquery but it did not work. Please advice:)

  var array = [one, two, three, four, five];

  $('#countButton').click(function(){
        for(var i = 0; i < array.length; i++){
         $('#displayCount').html(array[i++]);
        }
      });

<input type="button" value="Count" id="countButton" />

The button was pressed 0 times.

A: Not necessary to use a loop here. Just access the next element in your array after you click:
  var array = ['one', 'two', 'three', 'four', 'five'];
  var count = 0;
  $('#countButton').click(function(){
    if(count <= array.length){
      count++;
    } else{
      count = 0
    }
    $('#displayCount').html(array[count]);
   });

A: You dont need to loop it. just have a global variable use the same increment method

var array = ['one', 'two', 'three', 'four', 'five'];
var i = 0;
$('#countButton').click(function() {
  $('#displayCount').html(array[i++%5]);
});

<input type="button" value="Count" id="countButton" />

The button was pressed 0 times.


text:
Q: Jedis does not delete keys I have just installed redis' last version on Ubuntu 18.04.3. I have tried out writing values directly with redis-cli.
127.0.0.1:6379> set myket somevalue

I am now trying to delete all values from Jedis:
    Jedis jedis = new Jedis("localhost", 6379);
    Set<String> names=jedis.keys("NAME:*");
    System.out.println("There are " + names.size() +  " keys to delete");
    Iterator<String> it = names.iterator();
    while (it.hasNext()) {
        String s = it.next();
        jedis.del(s);
        System.out.println(s + " has been deleted");
    }

However, it always says that there are 0 keys right now. When I query it from redis-clidirectly, it is still there. How can I delete the keys from Jedis?

A: Your key name is myket and your pattern is NAME:*. The pattern NAME:* doesn't match myket. That's why you're finding 0 matching keys.


text:
Q: php while loops not executing properly I have three wards A,B,C in my database and 4 Employees (3 on ward A, 4 on B and 1 on C) and the below script prints out all the Wards correctly and prints out the 3 employees that works on ward A but nothing more (I:E it only compares against ward A and not the other 2)
Can you see any obvious error in the order that the php is executing that causes this? I'm new to PHP so thats why I don't quite understand the syntax =)
while ( $row = mysql_fetch_array($wardNames) ) {

        echo("

" . $row['Name'] . "

");

        while ( $employeerow = mysql_fetch_array($Employees)) {//Only prints out employees on ward A and not B or C. Why?
            if($employeerow['Ward']==$row['Name']){
                echo("
" . $employeerow['Name'] . "
");
            }
        }
    }

A: After iterating over a resultset it's exhausted and thus not iterable anymore. Store it in an array before the outer loop:
$all_employees = array();
while($row = mysql_fetch_array($Employees)) {
    $all_employees[] = $row;
}

while ( $row = mysql_fetch_array($wardNames) ) {

    echo("

" . $row['Name'] . "

");

    foreach($all_employees as $employeerow)
        if($employeerow['Ward']==$row['Name']){
            echo("
" . $employeerow['Name'] . "
");
        }
    }
}