Q: Making special combinations (C++) I need some help with a C++ problem. User enters how many numbers he want to enter, then all the numbers and a special value. Program must find and write all the combinations of numbers whose sum equals to the special value. Example:
Input

12
1 5 7 3 10 8 9 2 4 6 11 13
15

Output:
4 11
2 13
9 6
9 2 4
3 2 4 6
3 8 4
3 10 2
7 2 6
7 8
5 4 6
5 8 2
5 10
5 7 3
1 8 6
1 8 2 4
1 10 4
1 3 11
1 3 9 2
1 7 3 4
1 5 9
1 5 3 6
1 5 3 2 4
1 5 7 2
Code
Here's the code that writes all the combinations that consist of 2 elements:
#include <iostream>
using namespace std;

int main(int argc, const char * argv[])
{
    int size;
    cout << "Enter size: ";
    cin >> size;
    int *numbers = new int[size];
    cout << "Enter numbers: ";
    for (int i = 0; i < size; i++)
        cin >> numbers[i];
    int target;
    cout << "Enter target: ";
    cin >> target;
    int sum = 0;
    for (int i = 0; i < size-1; i++)
    {
        for (int j = i+1; j < size; j++)
        {
            sum = numbers[i];
            sum += numbers[j];
            if (sum == target)
                cout << numbers[i] << " " << numbers[j] << "\n";
        }
    }
    return 0;
}

If I replace that for loop with this one, the program will write all the combinations that consist of 3 elements:
for (int i = 0; i < size-2; i++)
{
   for (int j = i+1; j < size-1; j++)
   {
      for (int k = j+1; k < size; k++)
      {
         sum = numbers[i] + numbers[j];
         sum += numbers[k];
         if (sum == target)
         cout << numbers[i] << " " << numbers[j] << " " << numbers[k] << "\n";
       }
    }
}

Here's my question: how to make a program that writes ALL the possible combinations?

A: *

*Take the first number from your list (e.g., 1).

*Remove this number from your list, as well as deduct it from your "destination" total.

*Now you have a new list and a new destination total.  Repeat.

*If your total exceeds your destination, skip the current number (i.e., retain the number within the list, don't update the destination) and move to the next.

*If none of the remaining items in the list let you reach your destination, pop the last number you added to your destination total, and update it with the next number in the list.

*If you reach your destination total, you have a subset of numbers from your original list (with a size that is anything between 1 and the number of elements in the list) that add up to your intended total.


Q: Pulling Data Out of A ComboBox I have a ComboBox that is being populated by a table, but when I have my ComboBox populated I have it concatenated with some formatting.
Do
    strValue = "Loc: " & .Fields(0).Value & " Weight : " & .Fields(1).Value

    cbAlloys.AddItem strValue
    rsDB1.MoveNext

Loop Until rsDB1.EOF

So now that it's like this I need to take just the weight value and output it without anything but the weight number.
I tried this:
siBinWeightDescription.Value = cbBinAndWeight.Value
siBinWeightDescription.Value = InStr(6, cbBinAndWeight.Value)

But, later realized that Instr only outputs the count.
How would I go about getting the weight value I need from the ComboBox?

A: To answer the multicolumn comobobox part of the question:
Use an array for AddItem (put it in a loop if you want)
  Dim Arr(0 To 1) As String
  Arr(0) = "Col 1"
  Arr(1) = "Col 2"
  cmb.AddItem Arr

and to retrieve data for the selected item:
cmb.List(cmb.ListIndex, 1)

you can also set up an enumeration for your column numbers like this:
Enum ColList
  Loc=0
  Weight=1
End Enum

then to retrieve data it would look like this (much more readable code)
cmb.List(cmb.ListIndex, ColList.Weight)

also, you dont have to use the word Fields... you can address your recordset like this:
rsDB1!Weight

A: split string into an array (zero based)
 debug.print split("Loc: abc Weight : 1234"," ")(4)  ' the second argument is the separator character

 debug.print split("Loc: abc Weight : 1234")(4)      ' space is the default separator

both print 1234


Q: Temporarily untrack files from git I have a base install of ExpressionEngine (a CMS) which I clone for new projects.
The base install has hundreds of core files that will never change, unless I install an update of expressionengine. Tracking all these files makes git very slow.
So, I want to untrack all of them for during my development, and only track them when I install an update. What would be the best way to do this?
I have tried using .gitignore, but this isn't meant to ignore files that are already being tracked. Should I use exclude or assume-unchanged, or something else?

A: If your project use an external library, you may want to use git submodule to include it in your repository, then go in that directory to git checkout the tag (or branch, or sha1) you want to use.
git init newproject
cd newproject
git submodule add https://url-or-path/to/base/ee-repository target_dir
cd target_dir
git checkout sometag
cd -
git add target_dir
git commit


Q: Angular 4 TypeError: Cannot read property 'IndustrySegments' of undefined I'm fairly new to Angular 4 and am having a problem with this error coming up in Chrome:
ERROR TypeError: Cannot read property 'IndustrySegments' of undefined
    at Object.eval [as updateDirectives] (IndustrialComponent.html:15)
    at Object.debugUpdateDirectives [as updateDirectives] (
I'm trying to populate a dropdown.  The dropdown does populate though it does have a blank entry at the top that I don't want.  I wonder if that is due to the error I'm getting.
Here's my component HTML code:
<select formControlName="drpIndustrySegments">
                    <option value="-">Industry Segment</option>
                    <option *ngFor="let industrySegment of industrialDropdown.IndustrySegments" value="{{ industrySegment }}">{{ industrySegment }}</option>
                </select>

The contents of the dropdown is coming from a JSON file called industrial-dropdown.json:
{
  "IndustrySegments": [ "Amusement and Theme Parks", "Construction Equipment", "Conveyor Equipment", "Hot Mix Asphalt", "Industrial & Commercial Facilities", "Locomotive & Rail Car", "Portable & Modular Buildings", "Portable and Modular Buildings", "Propane Gas", "Ready Mix Concrete", "Right of Way Equipment", "Short Line Rail Road", "Ski Resorts" ]
}

Here's my industrial.component.ts code:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/min';

import { IndustrialService } from '../../services/industrial.service';
import { IndustrialDropdown } from '../../shared/industrial-dropdown';

@Component({
    selector: 'industrial',
    templateUrl: './industrial.component.html'
})
export class IndustrialComponent implements OnInit {
    heroForm: FormGroup;
    industrialDropdown: IndustrialDropdown;
    constructor(
        private fb: FormBuilder,
        private industrialService: IndustrialService,
        private router: Router) {
        this.createForm();
    }
    ngOnInit() {
        this.getIndustrialDropdowns();
    }
    getIndustrialDropdowns(): void {
        this.industrialService.getIndustrialDropdown().then(industrialDropdown => this.industrialDropdown = industrialDropdown);
    }
    createForm() {
        this.heroForm = this.fb.group({
            drpIndustrySegments: '',
            drpItemsPainted: '',
            drpEnvironments: '',
            drpSurfaces: '',
            drpVOCs: ''
        });
    }
    onSubmit() {
        this.router.navigate(['/industrial-search', this.heroForm.value.drpIndustrySegments, this.heroForm.value.drpItemsPainted, this.heroForm.value.drpEnvironments, this.heroForm.value.drpSurfaces, this.heroForm.value.drpVOCs ]);
    }
}

Does anyone know what I'm doing wrong here?  I appreciate any suggestions.

A: try this using the ? operator:
<option *ngFor="let industrySegment of industrialDropdown?.IndustrySegments" value="{{ industrySegment }}">{{ industrySegment }}</option>

industrialDropdown is not present when template is rendered


Q: Is it bad practice to have a function that doesn't return if it throws an exception? I have some computational functions for configurations for software that will drive a hardware setup. In some cases, the user may input invalid configuration values. I handle this by throwing an exception if invalid values are used, or simply returning my calculated value if the configuration works:
def calc_exhale_dur(breath_rate, inh_dur, breath_hold_dur):
    """Calculate exhalation duration.

    Args:
        breath_rate (float): animal breath rate (br/min)
        inh_dur (float): animal inhalation duration (ms)
        breath_hold_duration (float): animal breath hold duration (ms)
    """

    single_breath_dur = calc_breath_dur(breath_rate)
    exhale_dur = single_breath_dur - (inh_dur + breath_hold_dur)

    if (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur:
        raise error.ConfigurationError
    elif exhale_dur <= 0:
        raise error.ConfigurationError
    else:
        return exhale_dur

Is it considered bad practice to do it this way? Do I always need to have some valid return value if there is a return value to begin with? I'm trying to learn how best to write Pythonic code while still satisfying the needs of my computational methods.

A: The purpose of raising an exception is to provide an alternate exit point in the event where a valid return value can't be found. You are using exceptions exactly as they are intended.
However, I would probably check if exhale_dir is non-positive first, which would save you from performing a calculation with an invalid value.
if exhale_dur <= 0:
    raise error.ConfigurationError
elif (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur):
    raise error.ConfigurationError

# You can also omit the else, since the only way to reach this point
# is to *not* have raised an exception. This is a matter of style, though.
return exhale_dur

A: No. Exceptions are either handled in a piece of code, or thrown, and leave it to the caller to decide what to do with them. If you return something, you have to choose the first option. You chose the second. Makes perfect sense. That's the whole idea of throwing an exception


Q: How to use function recursively in javascript? I have one form where on keyup function I am showing amount in words below that input. It's working as expected with my function. Now O have another input with 2 radio buttons. Onchange this radio buttons also I have to work my function of ShowAmountInWords. I am stuck here.   Suppose, I have 2 radio buttons with FD and RD. Limit for FD is 10 digits and Limit for RD is 11 digits.

$(document).ready(function() {
  $('#amount').on('keyup', function() {
    var amountInWrods = $('#amount').val();
    var words = changeToWord(amountInWrods); //calling that function to show amount in words
    $('#words').val(words);

  });
});

function changeToWord(amount) {
  //code to convert number to word
  return amountInWrods;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='amount' id='amount'>
<label id='words'>To show Amount in words</label>
<input type="radio" id="FD" name="tyoeofdeposit" value="FD">
<input type="radio" id="RD" name="tyoeofdeposit" value="RD">

I am adding my code for radio button validation inside above function.

function changeToWord(amount) {
  $('input[type=radio][name=typeofDeposit]').change(function() {
    if (this.value == 'FD') {
      if (amount > 10) {
        return 'input less amount';
      }
    } else if (this.value == 'RD') {
      if (amount > 11) {
        return 'input less amount';
      }
    }
  });
  //code to convert number to word
  return amountInWrods;
}

User will input amount and it will go to onkeyup event and from here it will go to function changetowords in that it will check for deposit type  If user input 10 digits with FD then it will show amount in words  If user input 11 digits with FD then it will return error msg. same for RD. But problem is  when FD is selected and user will add 11 digits so it returns errormsg but now, user want to change deposit type to RD so in this case that errormsg should be gone and Amountinwords should return proper response.I am stuck here.I tried with recursion function but it shows me error of max size exceeded.


Q: Red5 application debug i'm trying to deploy my red5 app to the webapps folder.  But! I've got some errors in my output.
    Exception in thread "Launcher:/myApp" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'web.context' defined in ServletContext resource [/WEB-INF/red5-web.xml]: Unsatisfied dependency expressed through bean property 'clientRegistry': : Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1147)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1040)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)
    at org.red5.server.tomcat.TomcatLoader$1.run(TomcatLoader.java:594)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1208)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:568)
[INFO] [Launcher:/myApp] org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1af1915: defining beans [placeholderConfig,web.context,web.scope,web.handler]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@46136
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:302)
    at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:185)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:805)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:762)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:680)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1132)
    ... 11 more
Caused by: java.lang.ClassNotFoundException: org.red5.core.Application
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1484)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1329)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1200)
    ... 19 more

After all of that i've got my app folder in webapps, but there is no .class file in the classes folder of my project. So, i can't use server-side app in my client app.
What's wrong?
App was built by default. Here is my red5-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

    <!--
    Defines a properties file for dereferencing variables
    -->
    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="/WEB-INF/red5-web.properties" />
    </bean>

    <!--
    Defines the web context
    -->
    <bean id="web.context" class="org.red5.server.Context"
        autowire="byType" />

    <!--
    Defines the web scopes
    -->
    <bean id="web.scope" class="org.red5.server.WebScope"
         init-method="register">
        <property name="server" ref="red5.server" />
        <property name="parent" ref="global.scope" />
        <property name="context" ref="web.context" />
        <property name="handler" ref="web.handler" />
        <property name="contextPath" value="${webapp.contextPath}" />
        <property name="virtualHosts" value="${webapp.virtualHosts}" />
    </bean>

    <!--
    Defines the web handler which acts as an applications endpoint
    -->
    <bean id="web.handler"
        class="org.red5.core.Application"
        singleton="true" />

</beans>

And my Application class
package org.red5.core;

/*
 * RED5 Open Source Flash Server - http://www.osflash.org/red5
 *
 * Copyright (c) 2006-2008 by respective authors (see below). All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any later
 * version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.IScope;
import org.red5.server.api.service.ServiceUtils;

/**
 * Sample application that uses the client manager.
 *
 * @author The Red5 Project (red5@osflash.org)
 */
public class Application extends ApplicationAdapter {

    /** {@inheritDoc} */
    @Override
    public boolean connect(IConnection conn, IScope scope, Object[] params) {
        return true;
    }

    /** {@inheritDoc} */
    @Override
    public void disconnect(IConnection conn, IScope scope) {
        super.disconnect(conn, scope);
    }

}

I did all of that with Red5 plugin in Eclipse. So... i have no idea what could be wrong..

A: I had the exact same problem.  Sounds like you're trying to follow the tutorial videos only using the new Red5_1.0, Like I was.  After many days, beers, and bruises from banging my head against my desk, I discovered that if you change your class to "org.red5.server.scope.WebScope" in your red5-web.xml file it should work correctly (bean id="web.scope").  Also, you may need to change your org.red5.core source imports from "import org.red5.server.api.IScope;" to "import org.red5.server.api.scope.IScope;".  Apparently there has been some class refactoring in the newer versions of Red5

A: I was getting a similar error, although when I checked my class was already set to "org.red5.server.scope.WebScope" as mentioned in Ninth Realm Matt's answer. I later found that I was missing the lib directory under webaps/chat/WEB-INF/.
This may be useful if anyone else has a similar problem.


Q: Javascript to jquery a document.get with children What is the equivalent of this to jquery and how can I shorten it using children (both in jquery and javascript as I'm really curious why mine didn't work)? I tried children actually but didn't get a result I wanted.
document.getElementById('ShowRow').getElementsByClassName('value')[0].getElementsByTagName('a')[0].innerHTML

Thanks in advance

A: Something like this:
$('#ShowRow').find('.value:first a:first').html()

A: You can do:
$('#ShowRow').find('.value:first a:first').html()


Q: How to open page in new tab from GridView? I want to open page in new tab while clicking on the gridview link button. But I want to open new page based on alert type. For example, from the given below grid I clicked link button of Alert1 then it should open alert1.aspx page, if it is Alert2 then alert2.aspx. etc
Help me to find a proper solution. Thank you.
GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeader="False">
    <Columns>
    <asp:TemplateField HeaderText="Alert Type" SortExpression="Alert_Type">
    <EditItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Alert_Type") %>'>
    </asp:Label>
    </EditItemTemplate>
    <ItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Alert_Type") %>'>
    </asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Created_Time" HeaderText="Created Time"
    ReadOnly="True" SortExpression="Created_Time" />
    <asp:TemplateField >
    <ItemTemplate>
    <asp:LinkButton ID="lnk" runat="server" Text="Click" OnClick="lnk_Click">
    </asp:LinkButton>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
 </asp:GridView>

C#:
protected void lnk_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_newtab');", true);
}

A: Here's the solution that you looking for:
 protected void lnk_Click(object sender, EventArgs e)
 {
      LinkButton lnk = sender as LinkButton;
      Label Label1 = lnk.NamingContainer.FindControl("Label1") as Label;

      if (Label1.Text == "Alert1")
      {
          Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);
      }
      else if (Label1.Text == "Alert2")
      {
          Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert2.aspx','_blank');", true);
      }
 }

Also, Give unique names to controls inside GridView.

A: Replace '_newtab' to '_blank'
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);

A: You need to set target attribute to _blank
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);

The second argument in window.open is to specify whether you want to open page in new tab or in existing tab. So you need to set it to _blank to open page in new tab

A: set CommandName to alert type and access it  in click event
 <asp:LinkButton ID="lnk" runat="server" Text="Click" OnClick="lnk_Click" CommandArgument='<%# Bind("Alert_Type") %>'>
</asp:LinkButton>

Click event
protected void lnk_Click(object sender, EventArgs e)
{
string alerttype=e.CommandArgument.ToString();
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open("+alerttype+"'.aspx','_newtab');", true);
}


Q: Replace image with different image/button - javascript within a function, I'm trying to replace a image/button with another image/button.

But I have the problem that there is two of the same button, (button 2) when it is replaced! (one at the top of the page, and one where it is meant to be). I was wondering if there is a way of getting rid of the extra button at the top, or creating the button element within the javascript function?
Thanks for any help.

A: You can remove an element in javascript using
var el = document.getElementById('id');
var remElement = (el.parentNode).removeChild(el);

A: I'd suggest something akin to the following:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum).src;
    }
    else {
        var next = document.getElementById(nextElemId).src;
    }

    elem.src = next;
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

Edited to add that, while it is possible to switch the src attribute of an image it seems needless, since both images are present in the DOM. The alternative approach is to simply hide the clicked image and show the next:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum);
    }
    else {
        var next = document.getElementById(nextElemId);
    }
    if (!next){
        return false;
    }
    elem.style.display = 'none';
    next.style.display = 'inline-block';
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

Edited to offer an alternate approach, which moves the next element to the same location as the clicked image element:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum);
    }
    else {
        var next = document.getElementById(nextElemId);
    }
    if (!next){
        return false;
    }
    elem.parentNode.insertBefore(next,elem.nextSibling);
    elem.style.display = 'none';
    next.style.display = 'inline-block';
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

A: You can hide the first button, not only change the image source. The code below shows one way of doing that.


Q: Global instance method I created a an instance method in my MainMenu init.
-(NSString*) iPhoneiPadConversionString: (NSString*) fileNameHold : (char) fileType {

....My Code.
}

All I want to do is reuse this method in my other classes....
fileName = [self iPhoneiPadCOnversionString: @"background.png": 'B'];

But I can't seem to figure out what the right stuff to do is... I have been trolling the board and can't quite put all the information together.  Any Help would be greatly appreciated.

A: What you want is a called a "category". With categories you can extend NSString (and add your method).
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html


Q: creating separate rules for horizontal and vertical alignment in css The plunkr link is https://plnkr.co/edit/mv3lL1vwu2LxoeFZw0TX
I want to position a div at the center of a page (vertically and horizontally). The div has a button which should be at the center of the div. I found a solution in Vertically center in viewport using CSS but it doesn't work for me. Also, I want to create two separate rules, one for vertical alignment and one for horizontal alignment and use them together (or separately) so that I can pick which element should be aligned in which way.
I do not want to use Flex, Bootstrap etc. as I am trying to understand CSS concepts.
the horizontal alignment rule is straightforward.
.center-horizontally-common-styles {
    display: block;
    margin: auto auto;
}

The vertical alignment rule is (modified from the SO link)
.centre-vertical-common-styles {
   position: fixed;
    right: 50%;
    top: 50%;
    transform: translateY(-50%);
    transform: translateX(50%);
}

.debug-border-common-styles {
    border: 3px solid black;
    height:40px;
    width:200px;
}

HTML
<div class="debug-border-common-styles centre-vertical-common-styles center-horizontally-common-styles">
    <button type="button"> Click Me! </button>
</div>

My understanding is that right: 50%; top: 50%; will use the browser's window (viewport?) as the reference and move the div's top edge and right edge to the location which is 50% mark of the browser's respective edge's location. TranslateY and TranslateX should now move the div upwards (-50%) and towards left(50%) respectively to align the button's center to the middle of the page thus centering the button. The issues I am facing are:
1) The translateY doesn't seem to work. If I change the height of the div to say 200px. the div starts growing downwards (i.e. its top edge seem to be fixed!) It doesn't happen if the width is changed to say 200px.
.debug-border-common-styles {
    border: 3px solid black;
    height:200px;
    width:200px;
}

2) The button inside the div is not at the center of the div. I created the following css rule for the button but translateY doesn't seem to work on this one as well.
.centre-button-vertical-common-styles {
   position: absolute; /*use absolute so that the origin is no the parent div*/
   right: 50%;
   top: 50%;
   transform: translateY(-50%);
   transform: translateX(50%);
}

3) Ideally, I would like to create two separate rules, say .center-vertical and .center-horizontal and combine them to use the desired effect. But If I do something like follows, it doesn't work. Is it possible to create two separate rules?
.center-horizontally-common-styles {
    display: block;
    margin: auto auto;
}

Not use right here because horizontal rule should place the item in middle
.centre-button-vertical-common-styles {
   position: absolute;
   top: 50%;
   transform: translateY(-50%);
}

A: Bro, you need few arrows of style. Do like this:)
 .centre-vertical-common-styles {
       position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
    .debug-border-common-styles {
        border: 3px solid black;
        height:40px;
        width:200px;
        display:flex;
        align-items:center;
        justify-content:center;
    }


Q: Perl Vs Python variable Scoping - gotchas to be aware of While investigating scoping in Perl and Python, I came across a silent scoping related behavior of Perl that can cause bugs very difficult to trace.  Specifically for programmers who are new to the language and not fully aware of all it's nuances.  I have provided example code for both Perl and Python to illustrate how scoping works in both the languages
In Python if we run the code:
    x = 30
    def g():
        s1 = x
        print "Inside g(): Value of x is %d" % s1

    def t(var):
        x = var
        print "Inside t(): Value of x is %d" % x
        def tt():
            s1 = x
            print "Inside t()-tt(): Value of x is %d" % x
        tt()
        g()

   t(200)

The resulting output is:
Inside t(): Value of x is 200
Inside t()-tt(): Value of x is 200
Inside g(): Value of x is 30

This is the usual lexical scoping behavior.  Python treats an assignment in a block by default as the definition and assignment to a new variable, not to the global variable that may exist in the enclosing scope.  To override this behavior, the keyword global needs to be used explicitly to modify the global variable x instead. The scope of the variable x in the function g() is determined by the place in the program where it is defined, not where the function g() gets called.  As a result of lexical scoping behavior in Python when the function g() is called within the function t() where another lexically scoped variable x is also defined and set to the value of 200, g() still displays the old value 30, as that is the value of the variable x in scope where g() was defined.  The function tt() displays a value of 200 for the variable x that is in the the lexical scope of tt().  Python has only lexical scoping and that is the default behavior.
By contrast Perl provides the flexibility of using lexical scoping as well as dynamic scoping.  Which can be a boon in some cases, but can also lead to hard to find bugs if the programmer is not careful and understands how scoping works in Perl.
To illustrate this subtle behavior, if we execute the following Perl code:
use strict;
our $x = 30;
sub g {
    my $s = $x;
    print "Inside g\(\)\: Value of x is ${s}\n";
}
sub t {
    $x = shift;
    print "Inside t\(\)\: Value of x is ${x}\n";
    sub tt {
        my $p = $x;
        print "Inside t\(\)-tt\(\)\: Value of x is ${p}\n";
    }
    tt($x);
    g();
}
sub h {
    local $x = 2000;
    print "Inside h\(\)\: Value of x is ${x}\n";
    sub hh {
        my $p = $x;
        print "Inside h\(\)-hh\(\)\: Value of x is ${p}\n";
    }
    hh($x);
    g();
}
sub r {
    my $x = shift;
    print "Inside r\(\)\: Value of x is ${x}\n";
    sub rr {
        my $p = $x;
        print "Inside r\(\)-rr\(\)\: Value of x is ${p}\n";
    }
    rr($x);
    g();
}
g();
t(500);
g();
h(700);
g();
r(900);
g();

the resulting output is:
Inside g(): Value of x is 30
Inside t(): Value of x is 500
Inside t()-tt(): Value of x is 500
Inside g(): Value of x is 500
Inside g(): Value of x is 500
Inside h(): Value of x is 2000
Inside h()-hh(): Value of x is 2000
Inside g(): Value of x is 2000
Inside g(): Value of x is 500
Inside r(): Value of x is 900
Inside r()-rr(): Value of x is 900
Inside g(): Value of x is 500
Inside g(): Value of x is 500

The line our $x defines/declares a global variable $x visible throughout the Package/code body.  The first call to t() the global variable $x is modified and this change is visible globally.
Perl as opposed to Python by default just assigns a value to a variable, whereas Python by default defines a new variable and assigns a value to it within a scope.  That is why we have the different results in the Python and the Perl code above.
That is why even the call to g() within t() prints the value 500.  The call to g() immediately after the call to t() also prints 500 and proves that the call to t() indeed modified the global variable $x in the global scope.  $x within function t() is lexically scoped, but not displaying the expected behavior as the assignment at line 8 makes a global change to the variable $x in the global scope.  This results in the call to g() within t() displaying 500 instead of 30.
In the call to the function h() where g() is called (line 25), the function g() prints 2000, similar to the output from function t().  However when the function h() returns and we again call g() immediately after it, we find that
$x has not changed at all.  That is the change to $x within h() did not change $x in it's global scope but only within the scope of h().  The change to $x is somehow temporarily confined to within the current scope where the local keyword is used.  This is dynamic scoping in practice in Perl.  The call to g() returns the value of the variable $x in the current execution scope of g() instead of the value of $x where g() is defined within the code a.k.a lexical scope.
Finally in the call to function r() at line 28, the keyword my forces the creation of a new lexically scoped local variable, identical to the behavior within function t() in the Python code snippet.  This is in stark contrast to what happened within h() or t() where no new variable was ever created.  Within function r() we observe that the call to g() actually prints the value of $x as 500, the value $x has in the lexical scope where g() has been defined and not the value in the current execution scope of g() (as opposed to dynamic scope result in h()).  The Perl function r() is the closest match in terms of scoping behavior to the original Python function t().
By default Perl modifies the global variable $x instead of creating a new lexically scoped $x variable as in Python, and this can be some times a source of confusion and errors to a Perl newbie.  For statically typed languages, this is not an issue as variables need to be declared explicitly and the chances of any confusion of whether an existing variable is being assigned to or a new variable is being defined and assigned to does not arise.  In dynamically typed languages, that do not require explicit declaration and where the programmer is unaware of the consequences of not using scoping syntaxes appropriately (as in use of my in Perl), it can often lead to unintended consequences if one is not careful.   The programmer might think that a new variable is being declared at line 8, but actually the global variable $x is being modified.  This is exactly the way Perl intends it to be used, but can lead to interesting effects if the programmer is not careful and not fully aware of what it means.  This kind of error could get difficult to catch and debug in a large program of several hundreds or thousands of lines of code.  The thing to remember is that without a my prefix, Perl treats assignments to variables as just assignments not a definition + assignment.
Perl treats assignment in a block by default as assignment to the global variable of the same name and requires explicit override by using my to define + assign to a lexically scoped local variable.
Python has opposite default behavior and treats all assignments in a block by default as defining and assigning to a local lexically scoped variable.  The use of the global key word needs to be explicitly used to override this default behavior.
I feel Python's default behavior is safer and maybe kinder to novice and intermediate level programmers than Perl's default scoping behavior.
Please add any other subtle scoping related issues to be aware of for both Perl and Python that you may be aware of.

A: The line $x = shift in your second Perl example just overwrites a global, lexically-scoped variable, same as if you would add global x to your Python code.
This has nothing to do with dynamic scoping, and there are many other languages with the same behaviour as Perl - I'd consider Python the odd man out here for requiring to explicitly import a variable name visible at lexical scope.
The real problem with the Perl code is not lexical scoping, but lack of declared parameters. With declared parameters, it would be impossible to forget the my, and the problem would go away as well.
I find Python's approach to scoping (as of Python 2) far more problematic: it's inconsistent (explicit imports for globals to get a read-write binding, whereas lexicals in nested functions are bound automatically, but read-only) and makes closures secon-class citizens.


Q: kernel gets stuck if I train/test split by 55% and 45% I am trying to train a neural net on a dataset. Everything works. There is no issue with the code if I specifiy 70% or 50% percent of the data as training and the rest as testing. But as I specify 55% and 45% for training and testing, the kernel gets stuck and gives the following error:
Error in plot.nn(nnet, rep = "best"): weights were not calculated
Traceback:

1. plot(nnet, rep = "best")
2. plot(nnet, rep = "best")
3. plot.nn(nnet, rep = "best")
4. stop("weights were not calculated")

Here is the code that I have written so far:
library(neuralnet)
    Main <- read.table("miRNAs200TypesofCancerData.txt", header = TRUE,stringsAsFactors = T ) # reading the dataset
    for(i in 1:ncol(Main)){
      Main[is.na(Main[,i]), i] <- mean(Main[,i], na.rm = TRUE)
    }
    set.seed(123)
# in the following line, if you replace p=0.55 by p=0.5, no problem is reported and everything works smoothly
    indexes = createDataPartition(Main$Type, p=0.55, list = F)

    # Creating test and train sets.
    train = Main[indexes, ]
    test = Main[-indexes, ]
    xtest = test[, -1]
    ytest = test[, 1]

    nnet = neuralnet(Type~., train, hidden = 5, linear.output = FALSE)

    # Plotting
    plot(nnet, rep = "best")

    # Predictions
    ypred = neuralnet::compute(nnet, xtest)

    yhat = ypred$net.result
    yhat=data.frame("yhat"=ifelse(max.col(yhat[ ,1:4])==1, "Mesenchymal",
                                  ifelse(max.col(yhat[ ,1:4])==2, "Proneural",
                                         ifelse(max.col(yhat[ ,1:4])==3, "Classical","Neural"))))

    # Confusion matrix
    cm = confusionMatrix(as.factor(yhat$yhat),as.factor(ytest))
    print(cm)

Here is a link to the: Dataset

A: By adding just act.fct = "tanh" parameter in the model, everything runs smoothly.
Here is the working version:
    library(neuralnet)
    Main <- read.table("miRNAs200TypesofCancerData.txt", header = TRUE,stringsAsFactors = T ) # reading the dataset
    for(i in 1:ncol(Main)){
      Main[is.na(Main[,i]), i] <- mean(Main[,i], na.rm = TRUE)
    }
    set.seed(123)
    # in the following line, if you replace p=0.55 by p=0.5, no problem is reported and everything works smoothly
    indexes = createDataPartition(Main$Type, p=0.55, list = F)

    # Creating test and train sets.
    train = Main[indexes, ]
    test = Main[-indexes, ]
    xtest = test[, -1]
    ytest = test[, 1]

    nnet = neuralnet(Type~., train, hidden = 5, act.fct="tanh", linear.output = FALSE)

    # Plotting
    plot(nnet, rep = "best")

    # Predictions
    ypred = neuralnet::compute(nnet, xtest)

    yhat = ypred$net.result
    yhat=data.frame("yhat"=ifelse(max.col(yhat[ ,1:4])==1, "Mesenchymal",
                                  ifelse(max.col(yhat[ ,1:4])==2, "Proneural",
                                         ifelse(max.col(yhat[ ,1:4])==3, "Classical","Neural"))))

    # Confusion matrix
    cm = confusionMatrix(as.factor(yhat$yhat),as.factor(ytest))
    print(cm)


Q: yolov4-tiny on Colab. ConverterError: Variable constant folding is failed I'm trying to convert the tensorflow weights to tensorflow lite. First of all, I converted.tflite from generating TensorFlow SavedModel. I do this in Google colab. Can I execute this code?
%cd /content/tensorflow-yolov4-tflite
!python convert_tflite.py --weights ./checkpoints/yolov4-tiny-pretflite-416 --output ./checkpoints/yolov4-tiny-416.tflite

then the result
`tensorflow.lite.python.convert_phase.ConverterError`: Variable constant folding is failed. Please consider using enabling `experimental_enable_resource_variables` flag in the TFLite converter object. For example, converter.experimental_enable_resource_variables = True

btw, this my file convert_tflite.py
    import tensorflow as tf
from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
import cv2
from core.yolov4 import YOLOv4, YOLOv3, YOLOv3_tiny, decode
import core.utils as utils
import os
from core.config import cfg

flags.DEFINE_string('weights', './checkpoints/yolov4-416', 'path to weights file')
flags.DEFINE_string('output', './checkpoints/yolov4-416-fp32.tflite', 'path to output')
flags.DEFINE_integer('input_size', 416, 'path to output')
flags.DEFINE_string('quantize_mode', 'float32', 'quantize mode (int8, float16, float32)')
flags.DEFINE_string('dataset', "/Volumes/Elements/data/coco_dataset/coco/5k.txt", 'path to dataset')

def representative_data_gen():
  fimage = open(FLAGS.dataset).read().split()
  for input_value in range(10):
    if os.path.exists(fimage[input_value]):
      original_image=cv2.imread(fimage[input_value])
      original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
      image_data = utils.image_preprocess(np.copy(original_image), [FLAGS.input_size, FLAGS.input_size])
      img_in = image_data[np.newaxis, ...].astype(np.float32)
      print("calibration image {}".format(fimage[input_value]))
      yield [img_in]
    else:
      continue

def save_tflite():
  converter = tf.lite.TFLiteConverter.from_saved_model(FLAGS.weights)

  if FLAGS.quantize_mode == 'float16':
    converter.optimizations = [tf.lite.Optimize.DEFAULT]
    converter.target_spec.supported_types = [tf.compat.v1.lite.constants.FLOAT16]
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
    converter.allow_custom_ops = True
  elif FLAGS.quantize_mode == 'int8':
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
    converter.optimizations = [tf.lite.Optimize.DEFAULT]
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
    converter.allow_custom_ops = True
    converter.representative_dataset = representative_data_gen

  tflite_model = converter.convert()
  open(FLAGS.output, 'wb').write(tflite_model)

  logging.info("model saved to: {}".format(FLAGS.output))

def demo():
  interpreter = tf.lite.Interpreter(model_path=FLAGS.output)
  interpreter.allocate_tensors()
  logging.info('tflite model loaded')

  input_details = interpreter.get_input_details()
  print(input_details)
  output_details = interpreter.get_output_details()
  print(output_details)

  input_shape = input_details[0]['shape']

  input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)

  interpreter.set_tensor(input_details[0]['index'], input_data)
  interpreter.invoke()
  output_data = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))]

  print(output_data)

def main(_argv):
  save_tflite()
  demo()

if __name__ == '__main__':
    try:
        app.run(main)
    except SystemExit:
        pass

I save this file in folder tensorflow-yolov4 tflite.

Can someone know how to solve this problem? I need you guys. Thank you

A: Add two lines before tflite_model = converter.convert() in save_tflite() function like this
converter.experimental_enable_resource_variables = True
converter.experimental_new_converter = True

tflite_model = converter.convert()


Q: onbackpressed make my app close without confirmation I'm new android developer, my app closes when I press back from any page in menu. I added this code with dialog but it is not working
@Override
public void onBackPressed() {
    super.onBackPressed();

    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();

    if(count == 0) {
        // Do you want to close app?
    }

}

A: Have you tried putting the super call in an else block so it is only called if the key is not KEYCODE_BACK ?
/* Prevent app from being killed on back */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // Back?
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Back
            moveTaskToBack(true);
            return true;
        }
        else {
            // Return
            return super.onKeyDown(keyCode, event);
        }
    }

That should work for now! Feel free to comment if you have any problems.

A: try this:
@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();
    if(count == 0) {
       // Do you want to close app?
       showDialog();
    }
}

public void showDialog() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Do you want to close the app");
    alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
              finish();  //or super.onBackPressed();
        }
    });
    alert.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
    });
    alert.show();
}

A: Override activity's onBackPressed with the following in case you have for instance made changes in some values and forgot to update those afterwards, but in stead pressed the back button :
@Override
  public void onBackPressed() {
    if( <condition>) {
      AlertDialog.Builder ad = new AlertDialog.Builder( this);
      ad.setTitle("Changes were made. Do you want to exit without update?");
      ad.setPositiveButton(
              "OK",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  backPress();
                }
              }
      );
      ad.setNegativeButton(
              "Update the changes",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  <Update the changes>;
                  Toast.makeText(getApplicationContext(), "Changes were updated", Toast.LENGTH_SHORT).show();
                  backPress();
                }
              }
      );
      ad.setCancelable( false);
      ad.show();
    } else {
      backPress();
    }
  }

  private void backPress() {
    super.onBackPressed();
  }


Q: Cacti graph not showing properly Hoping to reach all of you Cacti experts right there. I have tried posting the same issue on the Cacti forums website, but after nearly a week had no answer. Hoping to have more luck here.
I'm pretty new to Cacti, and in the past days I've worked my way through to installation, configuration, etc.
I am now at a stage where I need to hook up the system I need to monitor (called Diffusion) into cacti. Diffusion is a java-based push engine, and my aim is to graph specific MBeans the server exposes.
I have created Perl scripts that give me the info I need in a correct fashion, and built a graph template to display data from 4 data sources pertaining a threadpool.
As of now the values are fixed, hence the outcome is always 0, 3, 8 and 10 (4 data sources, dumping on 4 rrds).
For some reason, though the only line I can see is the one returning 0, and the graph is sized between 0 and 1, wehreas I'd expect to see the other lines as well and the graph being sized between 0 and some value above 10.

Just to make it clear, logs (DEBUG level) do not show any warning, data gathering seems to work well, and I have no "complain" from cacti when creating sources, templates, etc.
Any help would be appreciated.
Thanks.

A: After a few attempts with changing a variety of parameters, I managed to solve the issue by simply changing the graph type to GAUGE.
Seems to wrk pretty well now.


Q: Jupiternote book on iPad / makrdown cells / how to drag a picture? I use JUNO connect to run cocalc on my iPad.
How can I get a picture in my picture file on the iPad into a markdown cell?
Thanks a lot for any help!


Q: In an IntelliJ Kotlin project, when I try to run a java class, I get a "Could not find or load main class" error I try to run the class from the green arrow in IntelliJ and I get the "Could not find or load main class"  error. If I try to run the class from the terminal by running
javac <filename.java>
java <filename>

it works. I tried to do "rebuild project" and to make a new project and it did not change anything.
Here is a photo of my project:

Here is a photo of my Run-Edit configurations

A: Your java code needs to be placed in src/main/java directory instead of src/main/kotlin.
Kotlin compiler doesn't compile Java files in Kotlin source roots, Java compiler doesn't compile Java files in Kotlin source roots, therefore .class files are not created by any of the compilers and you get this error.
The solution is to move *.java files into src/main/java directory. Create this directory manually if it doesn't exist.


Q: How to call a setter method in the Data Assignments I/O in a jbpm task? I have a process in jBPM. The process has a Human Task.
Also there are Data Objects: SrcData, CalcInter.
In the Human Task's Assignment Data I/O panel I need to read properties from the objects in Data Inputs section, and write a calculated variable in the property of CalcInter object in Data Outputs section (see picture).
Screenshot of Assignment Data I/O panel
Objects' properties reading in Data Inputs works as intended. As suggested here:
How to call a getter method in the Data Assignments I/O in a jbpm task?
But writing Object property in Data Outputs in such way doesn't work.
I've tried:
#{CalcInter.setAxx(axx)}
#{CalcInter.setAxx((int)axx)}
#{CalcInter.setAxx(#{axx})}

How to solve this? (And why is it so complicated?)

A: I've found that the issue can be solved by using MVEL notation instead of pure Java.
If in Data Outputs as a Target we use following expression:
#{CalcInter.axx}

The jBPM engine correctly updates the object property.
(How to use a Java style in the case and if it is possible — I still don't know.)


Q: what is the significance of " #!flask/bin/python " in flask? why this line #!flask/bin/python is added on the top of this code?
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(debug=True)

I got following error when I removed it
from: can't read /var/mail/flask
./app.py: line 3: syntax error near unexpected token `('
./app.py: line 3: `app = Flask(__name__)'

A: #! is a shebang. On UNIX/UNIX like operating systems it basically tells your shell which executable (python in your case) to execute the script with. Without it, the shell is executing the script directly and since it does not understand Python code, it raises an error.


Q: Adding rows to tables of datasets? I created a data set within VS2012 and created some tables for it. But i am unable to fill the tables using C#.
This runs without errors:

Database1DataSet.LocationRow newLocationRow;
newLocationRow = database1DataSet.Location.NewLocationRow();
newLocationRow.LocationID = 1;
newLocationRow.LocationName = "Test";
newLocationRow.LocationInfo = "Test";
database1DataSet.Location.Rows.Add(newLocationRow); //<- i get an error here ONLY if i use a row with a incorrect foreign key.
this.tableAdapterManager.UpdateAll(database1DataSet);

When i insert a simple row into a table like this i cannot find it in the database explorer, it still shows a single row with NULL. Am i doing something wrong?


Q: Array.length seemingly not working; console.log shows otherwise I want to eventually write contactList to the page but even though console.log is showing that contactList is properly receiving contacts being pushed from localStorage, its length remains at 1! And when I do try to iterate over contactList to write to the page, it doesn't work as expected and I see undefined where values should be.
var contactList = [];
window.onload = init;
function init(){
    var data = window.localStorage.getItem("contacts");
    if(data){
        myData = JSON.parse(data);
        console.log("This is local storage:\n");
        console.log(myData);
        console.log("This is contact list before I push local storage:\n");
        console.log(contactList);
        contactList.push(myData);
        console.log("This is contact list after I push local storage:\n");
        console.log(contactList);
        var j = contactList.length;
        console.log("This is the length of contact list:\n");
        console.log(contactList.length);

    }
}

Here's an example of my console window:

This is local storage:
form.js (line 12)
[[[Object { firstname="hi",  lastname="hi",  number="hi"}], Object {
firstname="hi",  lastname="hi",  number="hi"}], Object{ firstname="hi",  lastname="hi",  number="hi"}]
form.js (line 13)
This is contact list before I push local storage:
form.js (line 14)
[]
form.js (line 15)
This is contact list after I push local storage:
form.js (line 17)
[[[[Object { firstname="hi",  lastname="hi",  number="hi"}], Object { firstname="hi",  lastname="hi",  number="hi"}], Object { firstname="hi",  > lastname="hi",  number="hi"}]]
form.js (line 18)
This is the length of contact list:
form.js (line 20)
1

A: That is the expected outcome with push. It looks like you want to use concat.
push will append whatever the argument is to a new element at the end of the array. If you add a string it will add the string. If you add an array it will add an array...as the last element. It will not flatten the resultant array. On the other hand concat will concat the two arrays and return a new array. The original array will be unchanged though.

A: var a = [1]

console.log(a.length) // 0

var b = [2]

var c = a.push(b)

console.log(c) // [1, [2]]

console.log(c.length) // 2

Try using concat():
var a = [1]

console.log(a.length) // 1

var b = [2]

var c = a.concat(b)

console.log(c) // [1, 2] <<< Desired behaviour

console.log(c.length) // 2


Q: [MySQL]Insert a value depending on a condition I'm studying MySQL so I'm a bit new to all this stuff, but the last time I asked you guys, you proved to be really helpful, so perhaps you can help me again because I haven't been able to find the answer on my own.
Ok, so the thing is, I need to add a new column to an already existing table, and it should be like:
ALTER TABLE `medicos`
ADD COLUMN `tipo_medico` VARCHAR(20) NOT NULL DEFAULT 'indiferente' AFTER `sueldo`;

Now I'm supposed to run an INSERT instruction to add the data there. After adding that column, the table looks like this:

These values equal to: Medic_number, Surnames, Speciality, Day of birth, University, Wage and Medic_type (the new column I've added). The data I add on all the columns except the last one doesn't really matter, but the last column must be filled following the next conditions:
-By default, it'll be "indiferente" (that's working).
-If a medic has studied in an university ending in -a (i.e. Valencia), it'll say "Excellent".
-If a medic is 40 years old or older, it'll say "Expert".
Now, I know how to do these conditions ("... university like = '%a'", etc), but I don't know how to add that into the INSERT instruction. This is what I've gotten so far:
insert into medicos values ('A021', 'Apellidos :D', 'Loquesealogia', '1970-03-14', 'Valencia', '3500');

That adds everything but the last column, which is the one where I'm lost. What can I do to tell the INSERT instruction to, depending on which of the previously named conditions are true, add one value or another?
I hope I've been clear enough, I'm not a native English speaker so I'm sorry if that wasn't good enough. Also I've tried to format the codes this time, I hope that'll work.
Thanks.

A: This seems to be a case when we need to apply a logic on column values before a record is inserted. I would suggest creating a BEFORE INSERT trigger on this table, which will be automatically executed by MySql before each record is inserted.
We can write the logic to determine the value of last column depending upon values supplied for the other columns. Have a look at this link for trigger example.
If the requirement here is to do a one time bulk insert then, we can drop this trigger once insertion is complete.

A: I would advise you to do it either with BEFORE INSERT trigger as Darshan Mehta recommends, or do your logic in the programming side, or with a stored procedure.
Still it is doable at query time, so to answer your question specifically, try something like this:
INSERT INTO medicos (num_colegiado, apellidos, especialidad, fecha_nac, universidad, sueldo, tipo_medico) SELECT 'A021', 'Apellidos :D', 'Loquesealogia', '1970-03-14', 'Valencia', '3500', IF('Loquesealogia' like '%a','Excellent',IF(DATE_ADD('1970-03-14', interval 40 YEAR)>NOW(),'Expert','indiferente'))


Q: Caling procedure in conversion.asm from main .asm I have two asm files, one is conversion.asm and one is main.asm, I am using conversion.asm in main.asm. I am using floating point stack but I am not getting the right output.
main.asm
Include conversion.asm

.386
.stack 4096

ExitProcess PROTO, dwExitCode:DWORD

.data
Cel DD 25
Faren DD ?

.code
main PROC
  push dword ptr Cel
  fld dword ptr [esp]

  call C2F

  fstp dword ptr [Faren]
  mov ebx, [Faren]
  INVOKE ExitProcess, ebx
main ENDP
END main

conversion.asm

.model flat, stdcall

ExitProcess PROTO, dwExitCode:DWORD
.stack 4096

.data
Cfirst DD 2
Csecond DD 1
common DD 32

C2F PROC
    push dword ptr Cfirst
    fld dword ptr [esp]
    add esp,4
    fmulp
    sub esp,4
    push dword ptr Csecond
    fld dword ptr [esp]
    add esp,4
    fdivp
    sub esp,4
    push dword ptr common
    fld dword ptr [esp]
    add esp,4
    faddp
    sub esp,4
    RET
C2F ENDP

Please help me out

A: fmul, fdiv, fadd edit data in floating stack directly, so instead of pulling from stack to register, do operation directly in floating stack.
Correct usage of floating point stack in conversion.asm:
.DATA
five DWORD 5.0
nine DWORD 9.0
ttw DWORD 32.0

.CODE
C2F proc
    fmul nine
    fdiv five
    fadd ttw
    ret
C2F ENDP

For reading float and writing float I used Irvine library, which uses floating point stack:
Include Irvine32.inc
Include conversion.asm

.data
Celprompt BYTE "Enter a value in C:",0
Cel DWORD 0
Resprompt BYTE "In Farenheit that value is - "
Faren DD ?

.code
main PROC
  mov edx, OFFSET Celprompt
  call WriteString
  call Crlf
  call ReadFloat
  call C2F
  call Crlf
  mov edx, OFFSET Resprompt
  call WriteString
  call WriteFloat
main ENDP
END main


Q: Copy tables form schema in another schema in Oracle I want to write a procedure or a cursor.
Input data  -- NAME OWNER.
We know name  (OWNER) AND from table  ALL_OBJECTS
Take the name of the table.
Tables > 30.
How to write correctly ?

CREATE OR REPLACE PROCEDURE USER_NAME
(

  v_USER VARCHAR2
)
AS
  v_sysdate VARCHAR2(10) := to_char(SYSDATE ,'MMDDYYYY');
  v_table_name VARCHAR2(50);

BEGIN

  SELECT
  TABLE_NAME INTO v_table_name
  FROM
    ALL_OBJECTS F   -- Table with two columnsю. OWNER AND NAME TABLES
  WHERE
    F.OWNER  = v_USER;

   --Name of tables and owner ALL_OBJECTS

EXECUTE IMMEDIATE 'CREATE TABLE USER_BANCU.'||v_USER||'_'||v_table_name||'__'||v_sysdate||to_char(sysdate,'HH24_MI_SS')||'    AS
             SELECT *
             FROM '||v_USER||'.'||v_table_nam;
COMMIT;
END;
/

A: Try DBMS_METADATA_GET_DDL.
enter link description here


Q: Uninstall / remove a Homebrew package including all its dependencies I have a Homebrew formula that I wish to uninstall/remove along with all its dependencies, skipping packages whom other packages depend upon (a.k.a. Cascading package removal in Package manager parlance).
e.g. Uninstall package a which depends on packages b & c, where package d also depends on package c. The result should uninstall both a & b, skipping c.
How can I do that?
There must be a way to uninstall a package without leaving unnecessary junk behind.

A: EDIT:
It looks like the issue is now solved using an external command called brew rmdeps or brew rmtree.
To install and use, issue the following commands:
$ brew tap beeftornado/rmtree
$ brew rmtree <package>

See the above link for more information and discussion.

[EDIT] see the new command brew autoremove in https://stackoverflow.com/a/66719581/160968

Original answer:
It appears that currently, there's no easy way to accomplish this.
However, I filed an issue on Homebrew's GitHub page, and somebody suggested a temporary solution until they add an exclusive command to solve this.
There's an external command called brew leaves which prints all packages that are not dependencies of other packages.
If you do a logical and on the output of brew leaves and brew deps <package>, you might just get a list of the orphaned dependency packages, which you can uninstall manually afterwards. Combine this with xargs and you'll get what you need, I guess (untested, don't count on this).

EDIT: Somebody just suggested a very similar solution, using join instead of xargs:
brew rm FORMULA
brew rm $(join <(brew leaves) <(brew deps FORMULA))

See the comment on the issue mentioned above for more info.

A: brew rmtree doesn't work at all. From the links on that issue I found rmrec which actually does work. God knows why brew doesn't have this as a native command.
brew tap ggpeti/rmrec
brew rmrec pkgname

A: You can just use a UNIX pipe for this
brew deps [FORMULA] | xargs brew rm

A: A More-Complete Bourne Shell Function
There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time.
Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies.
unbrew () {
    local formula
    for formula in "$@"; do
        brew deps "$formula" |
        xargs brew uninstall --ignore-dependencies --force
        brew uninstall --force "$formula"
    done
    brew missing | cut -f2 -d: | sort -u | xargs brew install
}

It was tested on Homebrew 1.7.4.
Caveats
This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim).

A: The goal here is to remove the given package and its dependencies without breaking another package's dependencies. I use this command:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | xargs brew install

Note: Edited to reflect @alphadogg's helpful comment.

A: Other answers didn't work for me, but this did (in fish shell):
brew remove <package>
for p in (brew deps <package>)
    brew remove $p
end

Because brew remove $p fails when some other package depends on p.

A: By the end of 2020, the Homebrew team added a simple command brew autoremove to remove all unused dependencies.
First, uninstall the package:
brew uninstall <package>
Then, remove all the unused dependencies:
brew autoremove

A: Based on @jfmercer answer (corrections needed more than a comment).
Remove package's dependencies (does not remove package):
brew deps [FORMULA] | xargs brew remove --ignore-dependencies

Remove package:
brew remove [FORMULA]

Reinstall missing libraries:
brew missing | cut -d: -f2 | sort | uniq | xargs brew install

Tested uninstalling meld after discovering MeldMerge releases.

A: Using this answer requires that you create and maintain a file that contains the package names you want installed on your system.  If you don't have one already, use the following command and delete the package names what you don't want to keep installed.
brew leaves > brew_packages

Then you can remove all installed, but unwanted packages and any unnecessary dependencies by running the following command
brew_clean brew_packages

brew_clean is available here: https://gist.github.com/cskeeters/10ff1295bca93808213d
This script gets all of the packages you specified in brew_packages and all of their dependancies and compares them against the output of brew list and finally removes the unwanted packages after verifying this list with the user.
At this point if you want to remove package a, you simply remove it from the brew_packages file then re-run brew_clean brew_packages.  It will remove b, but not c.

A: Save the following script as brew-purge
#!/bin/bash
#:Usage: brew purge formula
#:
#:Removes the package and all dependancies.
#:
#:
PKG="$1"
if [ -z "$PKG" ];then
   brew purge --help
   exit 1
fi
brew rm $PKG
[ $? -ne 0 ] && exit 1
while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null
  do :
done
echo Package $PKG and its dependancies have been removed.
exit 0

Now install it with the following command
sudo install brew-purge /usr/local/bin

Now run it
brew purge package

Example using gpg
$ brew purge gpg
Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB)
Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB)
Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB)
Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB)
Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB)
Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB)
Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB)
Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB)
Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB)
Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB)
Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB)
Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB)
Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB)
Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB)
Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB)
Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB)
Package gpg and its dependancies have been removed.
$

A: The answer of @jfmercer must be modified slightly to work with current brew, because the output of brew missing has changed:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | cut -f1 -d: | xargs brew install

A: Slightly refined; can supply multiple packages; has usage when none supplied.
#!/bin/bash
# Removes the package and all dependancies.

if [ $# -eq 0 ]; then
   echo "$(basename $0) <pkg> [<pkg> [...]]"
   exit 1
fi

function tree() {
    pkg="$1"
    join <(brew leaves) <(sort <(brew deps ${pkg}; echo ${pkg}))
}

let e=0
for pkg in "$@"; do
    printf "Purging %s and its dependencies...\n" "${pkg}"
    deps=( $(tree ${pkg}) )
    while (( ${#deps[@]} > 0 )); do
        brew rm "${deps[@]}"
        deps=( $(tree ${pkg}) )
    done
done


Q: Waking up thread from signal handler I understand that about the only thing, a signal handler in ISO/C++11 is allowed to do is to read from or write to a lock free atomic variable or a volatile sig_atomic_t (I believe, POSIX is a little bit more permissive and allows to call a bunch of system functions).
I was wondering, if there is any way, to wake up a thread that is waiting on a condition variable. I.e. something like:
#include <mutex>
#include <atomic>
#include <condition_variable>

std::mutex mux;
std::condition_variable cv;

std::atomic_bool doWait{ true };

void signalHandler(int){
    doWait = false;
    cv.notify_one();
}

int main() {
    //register signal handler
    //Do some stuff

    {//wait until signal arrived
        std::unique_lock<std::mutex> ul(mux);
        cv.wait(ul, []{return !doWait; });
    }

    //Do some more stuff
}

Which has at least two problems:

*

*I believe, I'm not allowed to call notify_one() in a signal handler (corrct me if I'm wrong)

*The signal could arrive just between the check for doWait and when the thread goes to sleep, so it would never wake up (obviously, I can't lock the mutex in the signalHander to avoid that).

So far, the only solution I can see is to implement busy waiting on the doWait variable (probably sleep for a couple of milliseconds in each iteration), which strikes me as quite inefficient.
Note that even though, my program above has only one thread, I labeled my question with multithreading, because it is about thread control primitives. If there is no solution in standard c++ I'd be willing to accept a solution using Linux/POSIX specific functions.

A: Assuming that your vendor's standard library uses the pthread_cond_* functions to implement C++11 condition variables (libstdc++ and libc++ do this), the pthread_cond_* functions are not async-signal-safe so cannot be invoked from a signal handler.
From http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_broadcast.html:

It is not safe to use the pthread_cond_signal() function in a signal handler that is invoked asynchronously. Even if it were safe, there would still be a race between the test of the Boolean pthread_cond_wait() that could not be efficiently eliminated.
Mutexes and condition variables are thus not suitable for releasing a waiting thread by signaling from code running in a signal handler.

If you're comfortable using semaphores, sem_post is designated async-signal-safe. Otherwise, your options for signal handling are the usual ones: the classic self-pipe, a signal handling thread blocked on sigwait/sigwaitinfo, or platform-specific facilities (Linux signalfd, etc.).


Q: Website layout is broken,  is empty and I can't access wp-admin (wp-login) My site's https://www.beckers-trier.de layout and code is sort of broken. I don't code, but the theme is self-developed and I also don't remember changing anything about the site, except for adding the facebook pixel code in the . The Problem is that a few errors are given, which you can see in the wp-login site of my site. I can't login either, being warned that the cookie settings are closed because of a 'surprising output'

A: The error itself is quite self-explainatory, the server is trying to send some headers but some output has already started.
The warnings at start of the page are very likely to be generated from the PHP interpreter on your machine, either you have a weird display_errors directive in your php.ini or the constant WP_DEBUG on your wp-config.php is set to true.
Double check both configuration files and make sure the display of the errors are set to off and WP_DEBUG to false.


Q: Python return value prints only one value from the object instead of all the values I have a Python file with two class A and B, and I am inheriting temp from class A to B. In my class A function temp, I am getting the id value from an XML file which has values like this,
[1,2,3,4,5]

My Class A with temp function
class A:
        def temp(self):
        id = []
        for child in root:
            temp_id=child.get('id')
            id.append(temp_id)
        return id

and I am getting the function value in class B,
class B (A):
           fun=A
           value = fun.temp()
           for x in value:
             return x

While printing the return value instead of printing all the values, I am getting only the first value
[1,1,1,1,1]

Can some one please let me know on how to solve this, thanks.

A: Standard functions can only return a single value. After that, execution continues from where that function was called. So, you're trying to loop through all the values, but return upon seeing the first value, then the function exits and the loop is broken.
In your case, you could simply return fun.temp(). Or, if you want to process each value, then return the new list, you could run something like:
new_list = []
value = fun.temp()
for x in value:
   # do something with x here
   new_list.append(x)
return new_list

Also, it appears you may be a bit confused about how inheritance works. DigitalOcean has a  great article on it, if you want to take a look.


Q: Cost Query with having and > I have the next query :
select code
  from user
  group by code
  having
    sum(case when name= 'A' then 1 end) >
    sum(case when name= 'A' then 1 end)

If i check the cost of the query it says it's 180, but if I use '=' instead of >, the cost is 1 , so does anyone have any idea why this is happening? why it's only using the index with '=' and not with '<'

A: Is this a real query? I'm asking because the query is invalid - having clause is equal to writing 1 > 1, so always False... And if you replace '>' with '=' the query is always true unless the result from sum() is NULL...


Q: How to change the id format of field in a model? For example I have a field of customer IDs going from
1, 2, 3, 4, 5, ...

However I want to change the format to
010101, 010102, 010103, 010104, 010105, ...

As it display on my database and templates.
Is there any way of doing that?
I am using PostgreSQL version 12 and pgadmin 4.
I have been using of the below on the query editor

SELECT concat('0101', lpad(id, 2, '0')) from public.accounts_customer

However receiving the error below
ERROR:  function lpad(integer, integer, unknown) does not exist
LINE 1: SELECT concat('0101', lpad(id, 2, '0')) from public.accounts...
                              ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
SQL state: 42883
Character: 23

A: You can' t add  leading 0 to an integer and store  in db  you can manage only the selecting result  .. eg
 select concat('0101', lpad(yourcol,2,'0'))
 from your_table

or try force the cast
 select concat('0101', lpad(yourcol,2,'0'::text))
 from your_table


Q: What does "self-describing" in reference to Web Services really mean? I've heard a lot of buzz through the years about "Self Describing" web services and I'm curious what it means. I've flipped through the W3C standard and it doesn't really help.
I understand you can say "Give me this argument and call this functionality and I'll return something like this", but how is that actually helpful? How can software know what is relevant to a client given some context?
Can anyone give real world examples of this concept, and explain how it's better than some other alternative? Or maybe how useful/useless it is?

A: It's really designed as a standard for describing in a cross-platform cross-language manner an interface that a developer can use to develop a SOAP based way to exchange information with a web service.
Another alternative would be providing a library that provides a local interface to a blackbox communcation scheme, which is fraught with compatability/security issues.
Or providing documentation, which may be difficult to find, have compatibility issues, be out of date, or incomplete.
In short, it's very useful.


Q: Is PGSQL not executing my index because of the ORDER BY clause? I have a rails query that looks like this:
Person.limit(10).unclaimed_people({})

def unclaimed_people(opts)
  sub_query = where.not(name_id: nil)
  if opts[:q].present?
    query_with_email_or_name(sub_query, opts)
  else
    sub_query.group([:name_id, :effective_name])
             .reorder('MIN(COALESCE(kudo_position,999999999)), lower(effective_name)')
             .select(:name_id)
  end
end

Translating to SQL, the query looks like this:
SELECT  "people"."name_id" FROM "people"
  WHERE ("people"."name_id" IS NOT NULL)
GROUP BY "people"."name_id", "people"."effective_name"
  ORDER BY MIN(COALESCE(kudo_position,999999999)), lower(effective_name) LIMIT 10

Now when I run an EXPLAIN on the SQL query, what's returned shows that I am not running an index scan. Here is the EXPLAIN:
     QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=728151.18..728151.21 rows=10 width=53) (actual time=6333.027..6333.028 rows=10 loops=1)
   ->  Sort  (cost=728151.18..729171.83 rows=408258 width=53) (actual time=6333.024..6333.024 rows=10 loops=1)
         Sort Key: (min(COALESCE(kudo_position, 999999999))), (lower(effective_name))
         Sort Method: top-N heapsort  Memory: 25kB
         ->  GroupAggregate  (cost=676646.88..719328.87 rows=408258 width=53) (actual time=4077.902..6169.151 rows=946982 loops=1)
               Group Key: name_id, effective_name
               ->  Sort  (cost=676646.88..686041.57 rows=3757877 width=21) (actual time=4077.846..5106.606 rows=3765261 loops=1)
                     Sort Key: name_id, effective_name
                     Sort Method: external merge  Disk: 107808kB
                     ->  Seq Scan on people  (cost=0.00..112125.78 rows=3757877 width=21) (actual time=0.035..939.682 rows=3765261 loops=1)
                           Filter: (name_id IS NOT NULL)
                           Rows Removed by Filter: 317644
 Planning time: 0.130 ms
 Execution time: 6346.994 ms

Pay attention to the bottom part of the query plan. There is a Seq Scan on people. This is not what I was expecting, in my development and production database, I have placed an index on the foreign name_id field. Here is the proof from the people table.
"index_people_name_id" btree (name_id) WHERE name_id IS NOT NULL

So my question is why would it not be running the index. Could it perhaps be from the ORDER BY clause. I read that it could affect the execution of an index. This is the web page where I read it from. Why isn't my index being used?
In particular here is the quote from the page.

Indexes are normally not used for ORDER BY or to perform joins. A sequential scan followed by an explicit sort is usually faster than an index scan of a large table. However, LIMIT combined with ORDER BY often will use an index because only a small portion of the table is returned.

As you can see from the query, I am using ORDER BY combined with LIMIT so I would expect the index to be used. Could this be outdated? Is the ORDER BY really affecting the query? What am I missing to get the index to work? I'm not particularly versed with the internals of PGSQL so any help would be appreciated.


Q: PowerShell executing exe with arguments I wrote a PowerShell script to execute exe with arguments which has spaces but it keeps failing, not reading the full path.
$now     = Get-Date -format "MM_dd_yyyy"
$onepath ="C:\Program Files (x86)\GoFileRoom\IWMUploadDocuments\logs\"
$scpath  = "F:\Program Files\NSClient++\scripts\"
$onefile = "IWMUploadDocumentsLog$now.txt"
$script  = "check_log3.exe"

& "$scpath$script" -p "Error Logging into GFR" -l "$onepath$onefile" -c 1
Write-Output "$onepath$onefile"

Here is the output:

PS C:\Windows\system32> F:\Program Files\NSClient++\scripts\onesource.ps1
    Cannot read 'C:\Program'
    C:\Program Files (x86)\GoFileRoom\IWMUploadDocuments\logs\IWMUploadDocumentsLog10_22_2018.txt

A: Looks to me like you need an additional set of quotes around the argument for the parameter -l:
& "$scpath$script" -p "Error Logging into GFR" -l "`"$onepath$onefile`"" -c 1

Or try splatting the arguments:
$params = '-p', 'Error Logging into GFR',
          '-l', "$onepath$onefile",
          '-c', 1

& "$scpath$script" @params


Q: CSS displaying elements when thumbnails are hovered over i am attempting to display images when the corresponding thumbnail is hover over using only css and am having trouble with the logic and don't know if it is even possible. i can do it in javascript if absolutely necessary.
Here is my latest attempt.

And the CSS
#img-container{
    position:relative;
    top:0px;
    left:0px;
    height:950px;
}
.slide-images{
    position:absolute;
    top:0px;
    left:0px;
 }
 .thumbnail > img{
    margin-left:auto;
    margin-right:auto;
    display: inherit;
}
img#thumb4:hover ~ #img4>#image4{
    display:none;
}

A: I believe this is possible using CSS alone, however it is not very scaleable and it might end up being easier and more appropriate to use Javascript for this. For example:
img#thumb1:hover ~ #img4>#image4{
    display:none;
}

Your selector here is incorrect. The general sibling selector selects only elements after the first match. In this case, your image thumb is after your image, but this selector is looking for an image after an image thumb. This is the opposite of what you have. There is no 'sibling before' selector in CSS.
An easier solution, rather than fiddling around with CSS selectors, would just be to bind each thumbnail to a click event that changes the source of a single image tag each time (or alternatively, scrolls across/fades, whatever animation you're looking for). This way, you save on markup, don't need to worry about positioning as much, and can dynamically generate the image display.
For example, to get the ID of an image, you could bind a click event to each thumbnail and then grab the ID of the image which could stored in a data attribute:
$('.thumbnail').on('hover', function() {
    var activeImg = $(this).data('imgid');
    // From here, set the main image to have the associated image source
}

A: This is very possible to achieve with just CSS. The layout of your HTML is what needs to change. In this example:

*

*Each thumbnail and full-size image is placed inside a div container

*The full-size image is hidden with opacity: 0;

*When the div container is hovered, the full-size image is given opacity: 1 and will fade-in thanks to the transition

*z-index: 1 keeps the full-size images above the thumbnails
Full Example

.item {
  float: left;
  position: relative;
}
img {
  display: block;
  cursor: pointer;
  margin: 5px;
}
.fullsize {
  position: absolute;
  opacity: 0;
  transition: opacity 0.6s;
  z-index: 1;
  top: 0;
  left: 0;
  pointer-events: none;
}
.item:hover .fullsize {
  opacity: 1;
}


Q: Apply type projection to a refined type Consider the following example:
trait T3

trait T2{
  type TT4
  type TT3 <: T3
}

trait T1{
  type TT2 <: T2
}

now I want to write a function the roughly speaking looks as
def test[T <: T1](t: T#TT2{type TT4 = Int}#TT3) = println(t)  //invalid syntax

which unfortunately is not a valid syntax. It is perfectly possible to write a function like this
def test[T <: T1](t: T#TT2#TT3) = println(t)

But I'd like to add a bit stricter restriction on T#TT2 making it to be a refined type T#TT2{ type TT4 = Int}.
Is there any workaround?

A: Try wrapping type T#TT2 { type TT4 = Int } in parenthesis before the final projection like so
def test[T <: T1](t: (T#TT2 { type TT4 = Int })#TT3) = ???

Types can always be wrapped in parentheses
SimpleType        ::=  SimpleType TypeArgs
                      |  SimpleType ‘#’ id
                      |  StableId
                      |  Path ‘.’ ‘type’
                      |  Literal
                      |  ‘(’ Types ‘)’      <======= note the parentheses

for example
scala> val xs: (List[(Int)]) = List(42)
val xs: List[Int] = List(42)


Q: How to add a folder Jetty will run a site from? I have Jetty running on an Oracle VBox VM (Win7) Guest. I need Jetty to run a site from a shared folder, so I can edit it on the host. How can I do that?
Edit: The site is HTML/JS, not a war file. I see from the docs I can copy a war to $JETTY_HOME. What I'm wondering is if I can add a path to $JETTY_HOME for Jetty to look in?
The path is \\VBOXSVR\MyCoolSite


Q: VBA for altering PowerPoint 2003 Presentations- Active not new If I set up a template on PowerPoint slides, that contain all the text boxes I need, the what Visual Basic do I use to enter text that I want into those text boxes?
It is easier for me to use a template, because these ppt briefs contain (or need to contain) a lot of data:

*

*how do I enter text into those text boxes

*how do you alter the font, size, fontbold, etc of a particular text box?

*is there a way for determining the "name" of a text box/shape ("text box 52") other than recording macros after macros and selecting the text box, just to get the object name from selection?

*if I use a macro to determine the vba, why will it not work to use that as vba? the vb I get from a macro seems to have active.selection which just doesn't seem to work as a vba procedure because it doesn't know what to select???? i think

what i am looking to do is create the end game ppt from access, using the template. on an access form I want to have multiple text boxes that relay the information into the ppt text boxes on the slide.
i know how to launch a template (or new presentation) from access, and how to add new items (slides, graphs, charts, text) but I do not know how to alter pre-existing text boxes!!
Please help....my work is needing this like yesterday!
Thanks as always!

A: You can access shapes by name, as in:
Dim oSlide As Slide
Set oSlide = ActivePresentation.Slides(1)

Dim oShape As Shape
Set oShape = oSlide.Shapes(strShapeName)

Dim oTextRange As TextRange
Set oTextRange = oShape.TextFrame.TextRange

oTextRange.Text = "this is some text"

oTextRange.Font.Bold = msoTrue

Note that whatever you're looking to do, just record a macro of you doing it via the UI, and copy that. You're right that the recorded macro will use the Selection object a lot, but that's easily fixed - just get a reference to the appropriate Shape object (or whatever) and then subsitute that in the generated code.
So, for example, if the recorded macro for changing the fill color of a shape is this:
With ActiveWindow.Selection.ShapeRange
    .Fill.Visible = msoTrue
    .Fill.Solid
    .Fill.ForeColor.RGB = RGB(255, 0, 0)
    .Fill.Transparency = 0#
End With

... and you want to apply the fill color to a shape which you already have a reference to as oShape, then change the code to this:
With oShape
    .Fill.Visible = msoTrue
    .Fill.Solid
    .Fill.ForeColor.RGB = RGB(255, 0, 0)
    .Fill.Transparency = 0#
End With

To get the current name of a shape, you can enter this in the "immediate" window in the VBA editor:
?ActiveWindow.Selection.ShapeRange(1).Name

You could turn that into a (single) macro very easily:
Sub ShowMeTheName()
    MsgBox ActiveWindow.Selection.ShapeRange(1).Name
End Sub

Note that I would personally rename the shapes to something meaningful rather than using the default names. Simply turn do this in the immediate window:
ActiveWindow.Selection.ShapeRange(1).Name = "MyName"

...or create a macro to prompt for a name.

A: When I need to automate Word or Excel (nobody I know or work with has any use for PowerPoint), I open the app in question, turn on Macro recording and do the task I want to automate. Then I use the generated code as the basis for my Access code. It's often a pretty straightforward process, sometimes as simple as copying and pasting and then prefacing each line with the application object I'm using from Access.
If I had to do what you're doing, that's exactly how I'd start, by doing recording the task being performed interactively, and then experimenting with what part of the code is essential.


Q: How to compound a series of consequential subscriptions in RxJS I have approach according to the below.
this.service1.info
  .subscribe(a => this.service2.getDetails(a.id)
    .subscribe(b => {
      this.doStuff(b);
    })
  );

Recently, I noticed that we're going to have quite a few steps that gradually push more details to the client, so I'm anticipating the following atrocious pattern emerge.
this.service1.info
  .subscribe(a => this.service2.getDetails(a.id)
    ...
            .subscribe(z => {
              this.doStuff (z);
            })
  );

Is there a nice trick in RxJS to handle such situations? I only need to perform an operation once all the steps in the consequential chain have been emitted/received. I've browsed through the docs but didn't find something that felt quite right. I suspect that it's there, just that my ignorance confuses me so I'm missing it.

A: Yes, you are right. It is indeed an anti-pattern within RxJS to chain multiple subscribes.
A more elegant way of chaining these observable calls would be to make use of pipeable operators. In this scenario, the switchMap() operator would suffice.
As stated on the documentation, switchMap() will

Map to observable, complete previous inner observable, emit values.

this.service1.info
  .pipe(
    switchMap((a) => this.service2.getDetails(a.id)),
    switchMap((a) => this.service3.getDetails(a.id)),
    // switchMap((a) => this.service4.getDetails(a.id)),
    // subsequent chained methods
  ).subscribe(z => {
    // handle the rest when observables are returned
    this.doStuff(z);
  });

As you can see from the above pipe statement, we only call subscribe() once, and that will return the observable values. That is when we call the doStuff method.


Q: TransactionScope not rolling back although no complete() is called I'm using TransactionScope to rollback a transaction that fail
bool errorReported = false;
Action<ImportErrorLog> newErrorCallback = e =>
{
    errorReported = true;
    errorCallback(e);
};

using (var transaction = new TransactionScope())
{
    foreach (ImportTaskDefinition task in taskDefinition)
    {
        loader.Load(streamFile, newErrorCallback, task.DestinationTable, ProcessingTaskId);
    }
    if (!errorReported)
        transaction.Complete();
}

I'm sure there is no TransactionScope started ahead or after this code.
I'm using entity framework to insert in my DB.
Regardless the state of errorReported the transaction is never rolled back in case of error.
What am I missing ?

A: TransactionScope sets Transaction.Current. That's all it does. Anything that wants to be transacted must look at that property.
I believe EF does so each time the connection is opened for any reason. Probably, your connection is already open when the scope is installed.
Open the connection inside of the scope or enlist manually.
EF has another nasty "design decision": By default it opens a new connection for each query. That causes distributed transactions in a non-deterministic way. Be sure to avoid that.


Q: multiple pages are overlapping in ngx-extended-pdf-viewer I am using ngx-extended-pdf-viewer for my angular app and looks like multiple pdf pages are overlapping during viewing. here is my viewer code
<ngx-extended-pdf-viewer
        *ngIf="isVisible"
        [src]="pdfData"
        useBrowserLocale="true"
        [textLayer]="true"
        [showPrintButton]="true"
        [showDownloadButton]="true"
        [showOpenFileButton]="false"
        [showBookmarkButton]="false"
        [showPresentationModeButton]="false"
        height='90%'
        [zoom]="'100%'">
</ngx-extended-pdf-viewer>

I tried setting stylesheets for page and viewer classes but no luck.

A: Sounds like you've got CSS rules interfering with the CSS rule of ngx-extended-pdf-viewer. Create a greenfield project to check if it's a general problem:

*

*Open a terminal and navigate to the root folder of your project.

*Run this command and accept the defaults:

ng add ngx-extended-pdf-viewer

*Add the new component <app-example-pdf-viewer> to your <app-component> to display the PDF file.

Now you've got a working project that almost certainly does not suffer from your bug. Use the developer tools of your browser to compare the CSS code of the two projects to hunt down the bug.


Q: no sound in a push notification on Android(Ionic capacitor) I have a problem when i implemented a plugin PushNotification in capacitor, the problem is that when te phone receive a push notification don´t make any sound.
This is my code.
PushNotifications.addListener('pushNotificationReceived',
  (notification: PushNotification) => {
    console.log('Push received: ',JSON.stringify(notification));

  }

this is the settings in capacitor.config.json
"PushNotifications": {
  "presentationOptions": ["badge", "sound", "alert"]
}

thanks for your help.

A: show me the created the Notification channel Details.  Then don't test in Redmi or mi Phones.
addListenersForNotifications = async () => {
   await PushNotifications.addListener('registration', 'registration Name');
await PushNotifications.addListener('registrationError', 'error');
await PushNotifications.createChannel({
  id: 'fcm_default_channel',
  name: 'app name',
  description: 'Show the notification if the app is open on your device',
  importance: 5,
  visibility: 1,
  lights: true,
  vibration: true,
});
await PushNotifications.addListener('pushNotificationReceived', this.pushNotificationReceived);
await PushNotifications.addListener('pushNotificationActionPerformed', this.pushNotificationActionPerformed);

};


Q: Pandas Regression Model Replacing Column Values I have a data frame "df" with columns "bedrooms", "bathrooms", "sqft_living", and "sqft_lot".

I want to create a regression model by filling the missing column values based on the values of the other columns. The missing value would be determined by observing the other columns and making a prediction based on the other column values.
As an example, the sqft_living column is missing in row 12. To determine this, the count for the bedrooms, bathrooms, and sqft_lot would be considered to make a prediction on the missing value.
Is there any way to do this? Any help is appreciated. Thanks!

A: import pandas as pd
from sklearn.linear_model import LinearRegression

# setup
dictionary = {'bedrooms': [3,3,2,4,3,4,3,3,3,3,3,2,3,3],
              'bathrooms': [1,2.25,1,3,2,4.5,2.25,1.5,1,2.5,2.5,1,1,1.75],
              'sqft_living': [1180, 2570,770,1960,1680,5420,1715,1060,1780,1890,'',1160,'',1370],
              'sqft_lot': [5650,7242,10000,5000,8080,101930,6819,9711,7470,6560,9796,6000,19901,9680]}
df = pd.DataFrame(dictionary)

# setup x and y for training
# drop data with empty row
clean_df = df[df['sqft_living'] != '']
# separate variables into my x and y
x = clean_df.iloc[:, [0,1,3]].values
y = clean_df['sqft_living'].values

# fit my model
lm = LinearRegression()
lm.fit(x, y)

# get the rows I am trying to do my prediction on
predict_x = df[df['sqft_living'] == ''].iloc[:, [0,1,3]].values

# perform my prediction
lm.predict(predict_x)
# I get values 1964.983 for row 10, and 1567.068 row row 12

It should be noted that you're asking about imputation. I suggest reading and understanding other methods, trade offs, and when to do it.
Edit: Putting Code back into DataFrame:
# Get index of missing data
missing_index = df[df['sqft_living'] == ''].index
# Replace
df.loc[missing_index, 'sqft_living'] = lm.predict(predict_x)