text:
Q: Looping numpy array to raster puts the wrong bands into new rasters I have a number of GeoTiffs for which I need to apply an equation (Y=Aexp(BX)) to each band. There are 5 rasters, so 15 bands total. I would essentially like to split the rasters apart, do the math then recomposite them the way they were. Below is my code, but the rasters it produces are all in correct. The Red band of image one is in the red band of image five instead, for example. I'm still new to Python and learning as I go so the looping is very rough and I would like to eventually set it up so that I don't need to individually load each raster.
The purpose of this script is to avoid the need to apply calibration equations manually using map algebra. As you might guess, doing that 15 times takes a long time and since I am using different A & B coefficients all the time the workload is too much to carry on like that.
*Note: I edited out the original script for all 5 rasters to save space.
*Edit: solved the first script by moving the 'calibrated_data.append()' statement out one indentation. Still looking for a solution to the second script using lists instead of loading files individually as in script #2.
<!-- language: lang-py -->

    import arcpy
    import numpy as np
    import os
    import time

    # Set raster directory
    print('Setting raster directory...')
    arcpy.env.workspace = "E:/ArcGIS_Work/NIR_rasters"
    rasterpath = "E:/ArcGIS_Work/NIR_rasters)"
    outputFolder = "E:/ArcGIS_Work/calibrated_rasters"
    print('Done...')

    # Get input Raster properties
    nir_d1 = arcpy.Raster("E:/ArcGIS_Work/NIR_rasters/NIR_d1.tif")
    lowerLeft_1 = arcpy.Point(nir_d1.extent.XMin, nir_d1.extent.YMin)
    cellSize_1 = nir_d1.meanCellWidth
    spatialReference_1 = nir_d1.spatialReference

    # List the raster properties
    lowerLeft = [lowerLeft_1, lowerLeft_2, lowerLeft_3, lowerLeft_4, lowerLeft_5]
    cellSize = [cellSize_1, cellSize_2, cellSize_3, cellSize_4, cellSize_5]
    print "Done..."

    # Convert Raster to numpy array
    print "Converting rasters to NumPy arrays..."
    d1 = arcpy.RasterToNumPyArray(nir_d1, nodata_to_value=-10000)
    d1.astype(float)
    print "Done..."

    # all the images (in numpy arrays in a list)
    dates = [d1]

    # all coefficients and intercepts in lists for easy looping
    print "Configuring coefficients..."
    A = np.array([[0.0248262,0.0260896,0.0233547],dtype=np.float32)
    B = np.array([[0.0000609, 0.0000637, 0.0000648],dtype=np.float32)
    print "Done..."

    print "Starting calibration calculations..."
    calibrated_data = []
    for date,numpyarray in enumerate(dates): #with enumerate now dates will be 1,2,3,4,5
        arrayshape = numpyarray.shape
        Y = np.zeros_like(numpyarray, np.float32)
        Y_rescaled = np.zeros_like(numpyarray, np.float32)
        for i in range (0,3):
            Y[i,:,:] = A[date,i]*np.exp(B[date,i]*numpyarray[i,:,:]) # B[date,i] should be a scalar
            print Y
            Y_rescaled[i,:,:] = (Y[i,:,:]-Y[i,:,:].min())/(Y[i,:,:].max()-Y[i,:,:].min())
        calibrated_data.append(Y_rescaled)#_rescaled) # this has two members in it, the first is however many dates I have.
    print "Done..."
    print calibrated_data, type(calibrated_data)
    print "Saving reflectancemaps as 32-Bit GeoTiff"
    nir_calibrated1 = arcpy.NumPyArrayToRaster(calibrated_data[0], lowerLeft_1, cellSize_1)
    arcpy.DefineProjection_management(nir_calibrated1,spatialReference_1)
    nir_calibrated1.save(outputFolder+"//cal_nir_d1.tif")

    print "Done..."
    print "time elapsed: {:.2f}s".format(time.time() - start_time)

Edit: Here is a new attempt at shorter scripting with loops. The only puts out one singleband file so there's still something wrong with how I assign transformed arrays to image channels
import arcpy
import numpy as np
import os
import time
import glob

print('Setting raster directory...')
arcpy.env.workspace = "E:/ArcGIS_Work/NIR_rasters"
rasterpath = "E:/ArcGIS_Work/NIR_rasters/"
outputFolder = "E:/ArcGIS_Work/calibrated_rasters"
print('Done...')

# Set coefficients for Y=A*exp(B*raster_channel)
print "Listing coefficients..."
A = np.array([[0.0248262,0.0260896,0.0233547],[0.0065193, 0.0068043,0.0018543],[0.0173419,0.0159686,0.0089509], [0.0166572,0.0161596,0.0109827],[0.0377285,0.0582130,0.0319386]],dtype=np.float32)
B = np.array([[0.0000609, 0.0000637, 0.0000648], [0.0001313,0.0001401,0.0001643],[0.0000772,0.0000845,0.0000900], [0.0000707,0.0000763,0.0000782],[0.0000482,0.0000431,0.0000508]],dtype=np.float32)
print "Calibrating numpy arrays..."
calibrated_data = []

# List rasters in rasterpath
print "Listing rasters and their properties..."
rasters = arcpy.ListRasters("*", "TIF")
for raster in rasters:
    ras = arcpy.Raster(rasterpath+raster)
    lowerLeft = arcpy.Point(ras.extent.XMin, ras.extent.YMin)
    cellSize = ras.meanCellWidth
    spatialReference = ras.spatialReference
    LL = []
    LL.append(lowerLeft)
    CS = []
    CS.append(cellSize)
    SR = []
    SR.append(spatialReference)
    print LL,CS,SR
    numpyarray = arcpy.RasterToNumPyArray(ras, nodata_to_value=-10000)
    numpyarray.astype(float)
    arrays = []
    arrays.append(numpyarray)
    for date,numpyarrays in enumerate(arrays):
        arrayshape = numpyarray.shape
        Y = np.zeros_like(numpyarray, np.float32)
        Y_rescaled = np.zeros_like(numpyarray, np.float32)
        for i in range (0,3):
            Y[i,:,:] = A[date,i]*np.exp(B[date,i]*numpyarray[i,:,:]) # B[date,i] should be a scalar
            print Y
            Y_rescaled[i,:,:] = (Y[i,:,:]-Y[i,:,:].min())/(Y[i,:,:].max()-Y[i,:,:].min())
            calibrated_data.append(Y_rescaled[i,:,:])#_rescaled) # this has two members in it, the first is however many dates I have.
for arrays in calibrated_data:
    nir_calibrated = arcpy.NumPyArrayToRaster(arrays, lowerLeft, cellSize)
    nir_calibrated.save(outputFolder + "//" + raster[:-4] + ".tif")
print "Done..."

A: Solved finally! Here's the code:
print "Beginning imports..."
import time
start_time = time.time()
import arcpy
import numpy as np
import os
import glob
print "Done importing..."

# Set Infolder/Outfolder
print 'Setting raster directory...'
arcpy.env.workspace = "E:/ArcGIS_Work/NIR_rasters"
rasterpath = "E:/ArcGIS_Work/NIR_rasters/"
outputFolder = "E:/ArcGIS_Work/calibrated_rasters"
print 'Done...'

# Set empty lists to fill while looping
nirs=[]
lowerLeft =[]
cellSize =[]
spatialReference =[]

# List rasters in rasterpath. Note: Could use arcpy.ListRasters
# but this method is more generic to Python, thus easy to adapt
# to GDAL, OpenCV, Rasterio, etc.
print "Listing rasters and their properties..."
raster_names = []
for root, dirs, files in os.walk(rasterpath):
    for file in files:
        if file.endswith('.tif'):
            raster_names.append(file)
print raster_names
for name in raster_names:
    rasters = arcpy.Raster(rasterpath + os.sep + name)
    # rasters = arcpy.Raster(rasterpath + name)
    nirs.append(rasters)
    lowerLeft.append(arcpy.Point(rasters.extent.XMin, rasters.extent.YMin))
    cellSize.append(rasters.meanCellWidth)
    spatialReference.append(rasters.spatialReference)
print rasters
print "Converting rasters to numpy arrays..."
nparrays = []
for raster in nirs:
    nparrays.append(arcpy.RasterToNumPyArray(raster, nodata_to_value=-10000).astype(float))
print nparrays
print "time elapsed: {:.2f}s".format(time.time() - start_time)
print "Done..."
# Set coefficients for Y=A*exp(B*raster_channel)
print "Listing coefficients..."
A = np.array([
        [0.0248262,0.0260896,0.0233547],
        [0.0065193, 0.0068043,0.0018543],
        [0.0173419,0.0159686,0.0089509],
        [0.0166572,0.0161596,0.0109827],
        [0.0377285,0.0582130,0.0319386]
    ],dtype=np.float32)
B = np.array([
        [0.0000609, 0.0000637, 0.0000648],
        [0.0001313,0.0001401,0.0001643],
        [0.0000772,0.0000845,0.0000900],
        [0.0000707,0.0000763,0.0000782],
        [0.0000482,0.0000431,0.0000508]
    ],dtype=np.float32)
print "Done..."
# Apply the calibration equations
print "Starting array calibrations..."
calibrated_data = []
for date, numpyarrays in enumerate(nparrays):
    Y = np.zeros_like (numpyarrays, np.float32)
    Y_rescaled = np.zeros_like (numpyarrays, np.float32)
    for i in range (0,3):
        Y[i,:,:] = A[date,i]*np.exp(B[date,i]*numpyarrays[i,:,:]) # B[date,i] should be a scalar
        Y_rescaled[i,:,:] = (Y[i,:,:]-Y[i,:,:].min())/(Y[i,:,:].max()-Y[i,:,:].min())
        print Y_rescaled
    calibrated_data.append(Y_rescaled) # this has two members in it, the first is however many dates I have.
print "time elapsed: {:.2f}s".format(time.time() - start_time)
print "Done..."
# Save rasters back to GeoTiff
print "Saving nparray to raster..."
for i, data in enumerate(calibrated_data):
    calibrated = arcpy.NumPyArrayToRaster(data, lowerLeft[i], cellSize[i])
    arcpy.DefineProjection_management(calibrated,spatialReference[i])
    calibrated.save(outputFolder + "//" + (raster_names[i])[:-4] + ".tif")
print "Done..."
print "time elapsed: {:.2f}s".format(time.time() - start_time)


text:
Q: Where should I call functions with side effects like Date.now or random? For example I need a current date or shuffle a list in reducer. Should I use effects for that?
 @Effect()
  foo$: Observable<Action> = this.actions$.pipe(
    ofType('Foo'),
    map(action => {
      //create result with Date.now or shuffle
      return {type: 'Foo_Result', payload: result}
    }

    )
  );

It feels like overkill. What is the best practice?

A: I think the answer is already provided in the comments but for the completeness let me provide a "real" answer here.
Like @cartant said, you can put these side effects inside an action creator. These action creators don't have to be pure, meaning you could so something like:
const addTodo = ({
    id = uuid(),
    description = '',
    createDate = Date.now
  } = {}) => ({
    type: 'ADD TODO',
    payload: { id, description, createDate }
  })

Doing this has an extra benefit, which is easier tests:

*

*In your action test, you test if the id and createDate is there but you dont test the values

*To test your reducer you can set these values, addChat({id: 4654, description: 'a random todo', createDate: 111}).

These are the reasons why I'm more in favor of doing this inside an action creator, you could do it inside an effect if you like but just don't do it inside the reducer functions.
A reducer function must remain pure.
For more info, I refer you to Let's have a chat about Actions and Action Creators within NgRx

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does Tree(Int,Int) mean in haskell? I am learning data structures in Haskell right now. I saw something like:
  Tree(Int,Int)

Does that mean tuple of trees? I'm trying to write something like:
  data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Eq,Show)

  weight :: (Tree Integer) -> Tree(Integer,Integer)

  weight (Node left leaf right) = Node (leaf, (sum left) + (sum right))
                          where
                          sum (Leaf a) = 0
                          sum (Node left leaf right) = leaf + sum left + sum right

But I am getting couldn't match error.
What I want to get is the weight of each Node and return it as a tuple, and a single leaf doesn't have a weight.

A: To fix the immediate error, you need to provide three arguments to the Node constructor:
weight (Node left leaf right) = Node (weight left)
                                     (leaf, (sum left) + (sum right))
                                     (weight right)
                          where
                          sum (Leaf a) = 0
                          sum (Node left leaf right) = leaf + sum left + sum right

and perhaps a base case
weight (Leaf a) = Leaf (a,0)

..but I'm not sure this is what you intended:
ghci> weight (Node (Leaf 100) 10 (Node (Leaf 20) 30 (Leaf 40)))
Node (Leaf (100,0)) (10,30) (Node (Leaf (20,0)) (30,0) (Leaf (40,0)))

The values at the leaves are ignored and the second element in each pair is the subtree total.
Sum less frequently
There's a lot of repetition in summing the left and right subtrees, when you're calculating their weight too. Why not reuse the value?
We can read off the sum of a subtree by taking the second element of the top pair:
topsecond :: Tree (a,a) -> a
topsecond (Leaf (x,y)) = y
topsecond (Node _ (x,y) _) = y

So let's use that to get the sum
weigh (Leaf a) = Leaf (a,0)
weigh (Node left value right) = Node newleft (value,total) newright where
       newleft = weigh left
       newright = weigh right
       leftsum = topsecond newleft
       rightsum = topsecond newright
       total = leftsum + value + rightsum

Add up differently
In a comment you mention we should have (10,190) for the node tagged 10. That's the sum of everything below, but not including the current item. This means that the total weight of a subtree can be obtained by adding its subtrees' weight to the current value:
addTopPair :: Num a => Tree (a,a) -> a  -- or Tree (Integer,Integer) -> Integer
addTopPair (Leaf (x,y)) = x+y
addTopPair (Node _ (x,y) _) = x+y

and then
weighUnder (Leaf a) = Leaf (a,0)
weighUnder (Node left value right) = Node newleft (value,total) newright where
       newleft = weighUnder left
       newright = weighUnder right
       leftsum = addTopPair newleft
       rightsum = addTopPair newright
       total = leftsum + rightsum

giving
ghci> weighUnder (Node (Leaf 100) 10 (Node (Leaf 20) 30 (Leaf 40)))
Node (Leaf (100,0)) (10,190) (Node (Leaf (20,0)) (30,60) (Leaf (40,0)))

and
ghci> > weighUnder $ Node (Node (Leaf (-8)) (-12) (Node (Leaf 9) 3 (Leaf 6))) 5 (Node (Leaf 2) 14 (Leaf(-2)))
Node (Node (Leaf (-8,0)) (-12,10) (Node (Leaf (9,0)) (3,15) (Leaf (6,0)))) (5,12) (Node (Leaf (2,0)) (14,0) (Leaf (-2,0)))

as required.


text:
Q: Powershell script using xPath .SelectSingleNode not working on extracting values from web.config file xmlns I have slightly diff xml from normal xml like below, xmlns is not at the root level, it is 2 level depth from the root, for which i'm unable to use below solution. Can anyone please help me select the node. Thanks in advance.
I'm unable to use below snippet to select the node
$ns = New-Object System.Xml.XmlNamespaceManager($WebConfigXml.NameTable)
$ns.AddNamespace("ns", $WebConfigXml.DocumentElement.NamespaceURI)
$node = $WebConfigXml.SelectSingleNode("//ns:add[@key='SiteDomain']", $ns)

XML :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<app1>
</app1>
<assembly>
<runtime xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<location path="." inheritInChildApplications="false">
<appSettings>
<!--IT Ops-->
<add key="SomeOtherKey" value="SomeOtherValue" />
<add key="SiteDomain" value="somedomain.com" />
<add key="SomeOtherKey" value="SomeOtherValue" />
....
</appSettings>
</location>
</runtime>
</assembly>
</configuration>

A: Your namespace is not initialized correctly in $ns. You need to drill down to the node that contains the namespace definition:
$ns.AddNamespace('ns',$WebConfigXml.configuration.assembly.runtime.NamespaceURI)


text:
Q: Regex for validating alphabetics and numbers in the localized string I have an input field which is localized. I need to add a validation using a regex that it must take only alphabets and numbers. I could have used [a-z0-9] if I were using only English.
As of now, I am using the method Character.isLetterOrDigit(name.charAt(i)) (yes, I am iterating through each character) to filter out the alphabets present in various languages.
Are there any better ways of doing it? Any regex or other libraries available for this?

A: Since Java 7 you can use Pattern.UNICODE_CHARACTER_CLASS
String s = "Müller";

Pattern p = Pattern.compile("^\\w+$", Pattern.UNICODE_CHARACTER_CLASS);
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(m.group());
} else {
    System.out.println("not found");
}

with out the option it will not recognize the word "Müller", but using Pattern.UNICODE_CHARACTER_CLASS

Enables the Unicode version of Predefined character classes and POSIX character classes.

See here for more details
You can also have a look here for more Unicode information in Java 7.
and here on regular-expression.info an overview over the Unicode scripts, properties and blocks.
See here a famous answer from tchrist about the caveats of regex in Java, including an updated what has changed with Java 7 (of will be in Java 8)

A: boolean foundMatch = name.matches("[\\p{L}\\p{Nd}]*");

should work.
[\p{L}\p{Nd}] matches a character that is either a Unicode letter or digit. The regex .matches() method ensures that the entire string matches the pattern.

A:
Some people, when confronted with a problem, think "I know, I'll use
  regular expressions." Now they have two problems.

-- Jamie Zawinksi
I say this in jest, but iterating through the String like you are doing will have runtime performance at least as good as any regex — there's no way a regex can do what you want any faster; and you don't have the overhead of compiling a pattern in the first place.
So as long as:

*

*the validation doesn't need to do anything else regex-like (nothing was mentioned in the question)

*the intention of the code looping through the String is clear (and if not, refactor until it is)

then why replace it with a regex just because you can?


text:
Q: Can a Wordpress fixed footer be changed to a responsive one? We are a small art gallery building a wordpress website - you can see the work in progress here:http://kiraaskaroff.com/BB_Test2/
The footer looks great on a computer but with its fixed layout it looks rubbish on a mobile device (part disappears etc)
* footer */

#footer-content { margin-top: 60px; max-width:978px; min-width:320px;  height:230px;     overflow:hidden; padding-top:0px;  padding-left:200px; font-family:Georgia; color:#3F3F3F;  font-size:12px; text-align:left; }

#footer-left { float:left; width:199px;  height:182px; overflow:hidden;  }
#footer-mid1 { float:left; width:230px; height:182px; overflow:hidden; }
#footer-mid2 { float:left; width:138px;  height:182px; overflow:hidden; }
#footer-right { float:left; width:180px;  height:182px; overflow:hidden; }

.footer-header { font-family:Georgia, font-size:14px ; font-weight: bold; display:block;     color:#3F3F3F; padding-bottom:16px;text-align:left; }

.footer-social-a { display:inline; padding-right:5px; padding-top:18px;text-align:left; }

.styles #page .site-info a {
font-size: 12px;}

Any help making it look better on a mobile would be amazing!

A: You'll need to do some research into media queries, which will allow you to apply different CSS at different screen sizes.  Because even if you get it looking correct on mobile-sized screens, it'll still look broken on sizes between mobile and desktop (try resizing your browser on desktop to see what I mean).
For example, your desktop footer has for columns - there might be some screen sizes where you want two rows of two columns, while on mobile you probably want one column with four rows.
To get you started, adding this at the bottom of your stylesheet should help with your specific question (one column with four rows):
@media only screen and (max-width: 620px) {
    #footer-content {
        height: auto; /* Remove the fixed height - that's the reason not all the footer is visible */
        padding-left: 2%; /* On desktop you have a lot of space on the left - it's not needed on mobile */
    }

    #footer-left,
    #footer-mid1,
    #footer-mid2,
    #footer-right {
        width: 100%; /* Make each column takes the full width available */
        height: auto; /* If you leave the fixed heights from the desktop version you'll have strange gaps */
        padding-bottom: 10px; /* Make sure you have a minimum gap between the rows */
    }
}

I haven't fully tested, but it should do as a starting point.


text:
Q: Java 2D ArrayList so every time i run the program and enter the 2nd choice, it tells me rangecheck error , index0 , size 0.
what i understand from this after research is that the arraylist is empty, how do i use the add function in the 2D arraylist?
|ABCDEFGHIJKLMNOPQRSTUVWX
--+------------------------
01|gggggggggggggggggggggggg
02|gGGGGGGGGGGGGGGGGGGGGGGg
03|gGggggggggggggggggggggGg
04|gGgYYYYYYYYYYYYYYYYYYgGg
05|gGgYggggggggggggggggYgGg
06|gGgYggggggggggggggggYgGg
07|gGgYggYYYYYYYYYYYYggYgGg
08|gGgYggYggggggggggYggYgGg
09|gGgYYYYggggggggggYYYYgGg
10|gGggggggggggggggggggggGg
11|gGGGGGGGGGGGGGGGGGGGGGGg
12|gggggggggggggggggggggggg
package map;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;
import java.util.ArrayList;

public class MapMain
{
    public static void main(String [ ] args)
    {
        Scanner input = new Scanner(System.in);
        InputStream is = null;
          int i;
          char c;
          String T;
          ArrayList<ArrayList<String>> Contain = new ArrayList<ArrayList<String>>();
          for(int L = 0; L < 30; L++)
          {
              Contain.add(new ArrayList<String>());
          }

          try{
              do{
            int a=0;
            String Elements;
            System.out.print("To load map enter 1\nTo print loded map enter 2\nTo change specific elements press 3  ");
            a=input.nextInt();
            switch (a){
            case 1 :
                System.out.print("What is the file dest?");
                T=input.nextLine();
                is = new FileInputStream(T);
                while((i=is.read())!=-1)
                {
                   c=(char)i;
                   String O = "ankosh";
                   //Contain.add(Contain.O);
                }
                break;
            case 2:
                while(true)
                {
                   String U = Contain.get(16).get(0);
                   //System.out.print(Contain);
                   break;
                }
                break;
            case 3:
                System.out.print("What do you want to insert?");
                Elements=input.nextLine();
                //switch (Elements){
                //case
                }
                break;
            } while(true);
          }catch(Exception e){

        // if any I/O error occurs
        e.printStackTrace();
     }finally{
     }
    }
}

A: You created the array of arrays, and the arrays it contains, so far it's ok.
Now, on case 2 you are trying to reach the first element of the 16th array (basically of type String) which is null since you didn't add anything yet to this array.
What you need to do before trying the get(index), is to check that the length of the array is bigger than the index.
In order to add to the array:content.get(16).add(str);.


text:
Q: [C++14]I'm using pair but no output I was writing a code to sort and output the number by using "pair".
I tried some cases bat there was no output.
How should I rewrite the code?
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

int main()
{
    int k, i, n;
    cin >> n;
    pair<int, int> a[n];
    for (i = 0; i < n; i++) {
        cin >> k;
        a[i].first = -k;
        a[i].second = i + 1;
    }
    sort(a, a + n);
    for (i = 0; i++; i < n) {
        cout << a[i].second;
    }
}

A: for(i=0;i++;i<n){

You meant to write this as:
for(i=0;i<n;i++){


text:
Q: Is the behavior of a functor created by std::bind well-defined when the bound object expires? Is the behavior of the following code well defined? How does the f() call behave?
#include <functional>
#include <iostream>

struct A
{
  void shout()
  {
      std::cout <<"shout";
  }
};

int main()
{
    std::function<void()> f;
    {
        A a;
        f = std::bind(&A::shout, &a);
    }

    f();  // what happens here?
}

A: Your code ends up storing a dangling reference (to an object that no longer exists) inside the function wrapper, and invoking the function results in undefined behaviour.
If the original object doesn't live as long as the wrapper, you can always store a copy of the object in the wrapper:
f = std::bind(&A::shout, a);
//                      ^^^ copy

A: To show this is undefined, note that the address stored becomes an invalid pointer value - [basic.stc]/3:

When the end of the duration of a region of storage is reached, the
  values of all pointers representing the address of any part of the
  deallocated storage become invalid pointer values ([basic.compound]).

In the call to the bound functor, that pointer is dereferenced to perform the member function call, where [basic.stc.dynamic.deallocation]/4 applies:

Indirection through an invalid pointer value and passing an invalid
  pointer value to a deallocation function have undefined behavior.

Instead, you could bind a per value (omit the ampersand).


text:
Q: Powershell - Error while exporting Term store I'm trying to export the terms from the term store using PowerShell but I am receiving following error:
This is the directory where you need to export the term set as a .csv file.
Please ensure that this folder exists before trying to export the term set.

Here is script I am using::
$outPutDir = "c:\success"
#This should be the url of the Central Administration Site of the farm from where we would like to export the term set.
$siteURL = "http://ussecavdspdwk27:2010"
#This is the name of the Metadata Service Instance. e.g. "Managed Metadata Service"
$mmsServiceName = "Managed Metadata Service "
#This is the group name where the term set exists.
#In case the group does not exists, the script will create a new group with this name under the term store.
$grpName = "EandYBusiness"
#This is the term set name which we are going to export.
$termSetName = "General Business Taxonomy"
#This is the name of the csv file which will contain the exported term set data.
$fileName = "Export.csv"
try
{
  $taxonomySite = Get-SPSite $siteURL
  $taxSession = Get-SPTaxonomySession -site $taxonomySite
  try
  {
    $termStore = $taxSession.TermStores[$mmsServiceName];
    if ($termStore -ne $null)
    {
      try
      {
        $termGroup = $termStore.Groups[$grpName];
        if ($termGroup -ne $null)
        {
          try
          {
            $termSet = $termGroup.TermSets[$termSetName];
            if ($termSet -ne $null)
            {
              [string]$csvDir = "";
              $csvDir = $outPutDir;
              $outPutFile = $csvDir + "\\" + "$fileName";
              $sw = New-Object System.IO.StreamWriter($outPutFile);
              $sw.writeline('"Term Set Name","Term Set Description","LCID","Available","Term Description","Level 1 Term","Level 2 Term","Level 3 Term","Level 4 Term","Level 5 Term","Level 6 Term","Level 7 Term"');
              [Byte[]] $ampersand = 0xEF,0xBC,0x86;
              #$loop = $termGroup.TermSets.Count;
              #$count = 1;
              if($TermSet.TermsCount -ne 0)
              {
                $topTermOutput = '"' + $TermSet.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' +  $TermSet.Description + '","' + $TermSet.Languages + '","' +  $TermSet.IsAvailableForTagging + '","';
                foreach($childTerm in $TermSet.Terms)
                {
                  if($childTerm.TermsCount -ne 0)
                  {
                    #$topTermOutput = '"' + '","' +  $TermSet.Description + '","' + $TermSet.Languages + '","' +  $TermSet.IsAvailableForTagging + '","';
                    $heritage = $topTermOutput + '","' + $childTerm.Description + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';
                    foreach($secondLevelTerm in $childTerm.Terms)
                    {
                      if($secondLevelTerm.TermsCount -ne 0)
                      {
                        foreach($thirdLevelTerm in $secondLevelTerm.Terms)
                        {
                          if($thirdLevelTerm.TermsCount -ne 0)
                          {
                            foreach($fourthLevelTerm in $thirdLevelTerm.Terms)
                            {
                              if($fourthLevelTerm.TermsCount -ne 0)
                              {
                                foreach($fifthLevelTerm in $fourthLEvelTerm.Terms)
                                {
                                  if($fifthLevelTerm.TermsCount -ne 0)
                                  {
                                    foreach($sixthLevelTerm in $fifthLevelTerm.Terms)
                                    {
                                      if($sixthLevelTerm.TermsCount -ne 0)
                                      {
                                        foreach($seventhLevelTerm in $sixthLevelTerm.Terms)
                                        {
                                          $heritage = $topTermOutput + '","' +                       $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fifthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $sixthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $seventhLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';
                                          $sw.writeline($heritage);
                                        }
                                      }
                                      else
                                      {
                                        $heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fifthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $sixthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';
                                        $sw.writeline($heritage);
                                      }
                                    }
                                  }
                                  else
                                  {
                                    $heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fifthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';
                                    $sw.writeline($heritage);
                                  }
                                }
                              }
                              else
                              {
                                $heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';
                                $sw.writeline($heritage);
                              }
                            }
                          }
                          else
                          {
                            $heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';
                            $sw.writeline($heritage);
                          }
                        }
                      }
                      else
                      {
                        $heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';
                        $sw.writeline($heritage);
                      }
                    }
                  }
                  else
                  {
                    $heritage = $topTermOutput + '","' +        $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                      $sw.writeline($heritage);
                  }
                }
              }
              else
              {
                $heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '",,,,,,,' ;
                $sw.writeline($heritage);
              }
            }
          }
          catch
          {
            return "Problem occurred while creating the export file."
          }
          $sw.close();
          write-host "Your CSV has been created at $outPutFile";
        }
        else
        {
          return "Termset $termSet does not exist in the term store group $term";
        }
      }
      catch [System.Exception]
      {
         write-host($_.Exception)
        "Unable to acquire the termset $termSetName from the term group $grpName"
      }
    }
    else
    {
      return "Term store group $grpName does not exist in the term store $mmsServiceName";
    }
  }
  catch
  {
     "Unable to acquire term store group $grpName from $mmsServiceName"
  }
}
catch
{
  "Unable to acquire session for the site $siteURL";
}
finally
{
  $ErrorActionPreference = "Continue";
}

A: Check if c:\success folder exist.
You can ensure folder with this snippet:
 if ((Test-Path C:\success) -eq $false)
 {
     [IO.Directory]::CreateDirectory("C:\success")
 }

A: This may help:
$outputfile = "test.txt";
$taxonomySite = "http://test.url.com";
$taxonomySession = Get-SPTaxonomySession -site $taxonomySite
$termStore = $taxonomySession.TermStores["Managed Metadata Service"];
function exportTermStore($termStoreGroupName, $termSetName, $termParentName, $termName, $termLabelName) {
    $log = $termStoreGroupName + "," + $termSetName + "," + $termParentName + "," + $termName  + "," + $termLabelName ;
    $log | out-file $outputfile -append;
}
function processTerms($terms,$termStoreGroupName,$termSetName,$termParentName)
{
$terms |% {
    $termName = $_.Name;
    $termLabels = $_.Labels;
    $termLabels |% {
        $termLabelName = $_.Value;

        if ( $termLabelName -eq $termName ) {
            exportTermStore $termStoreGroupName $termSetName $termParentName $termName "";
        }
        else {
            exportTermStore $termStoreGroupName $termSetName $termParentName $termName $termLabelName;
        }

    }
    if ( $_.Terms.Count -ne 0) {
        $termPervName = $termParentName + "," + $termName ;
        write-host $termPervName;
        processTerms $_.Terms $termStoreGroupName $termSetName $termPervName ;
    }
}

}
exportTermStore "Group Name" "TermSet Name" "Parent Term Name" "Term Name" "Label Name";
$termStoreGroup = $termStore.Groups["Test"];
$termStoreGroupName = $termStoreGroup.Name;
$termStoreGroup.TermSets |% {
    $termSetName = $.Name;
    $terms = $.Terms;
    processTerms $terms $termStoreGroupName $termSetName $termSetName;
}


text:
Q: Using multiple AKPlayers for multiple audio files playback I am trying to play 4 mp3 files synchronously using AudioKit's AKPlayer, and it was pretty successful. As a part of my Swift study, though, I wanted to simplify my code using arrays (or something I haven't learned yet) since I feel there's something redundant in my code, simply copying player codes for four times. Below is the code I've written:
    let file1 = try? AKAudioFile(readFileName: "mixing_1_vocal.mp3")
    let file2 = try? AKAudioFile(readFileName: "mixing_2_drums.mp3")
    let file3 = try? AKAudioFile(readFileName: "mixing_3_synth.mp3")
    let file4 = try? AKAudioFile(readFileName: "mixing_4_bass.mp3")

    let player1 = AKPlayer(audioFile: file1!)
    let player2 = AKPlayer(audioFile: file2!)
    let player3 = AKPlayer(audioFile: file3!)
    let player4 = AKPlayer(audioFile: file4!)
    let startTime = AVAudioTime.now() + 0.25

    let mixer = AKMixer()
    player1 >>> mixer
    player2 >>> mixer
    player3 >>> mixer
    player4 >>> mixer

    player1.isLooping = true
    player1.buffering = .always
    player2.isLooping = true
    player2.buffering = .always
    player3.isLooping = true
    player3.buffering = .always
    player4.isLooping = true
    player4.buffering = .always

    AudioKit.output = mixer

    try? AudioKit.start()
    player1.start(at: startTime)
    player2.start(at: startTime)
    player3.start(at: startTime)
    player4.start(at: startTime)

This is it! There are four different tracks (individual instruments), and they are supposed to be played at the same time, looped infinitely. It will be very helpful if anybody could help me improve my code. Are there better ways to perform the same work?

A: This is a pretty open ended question, but here's an example ViewController for iOS.
class ViewController: UIViewController {

    let mixer = AKMixer()
    let players: [AKPlayer] = {
        do {
            let filenames = ["mixing_1_vocal.mp3",
                             "mixing_2_drums.mp3",
                             "mixing_3_synth.mp3",
                             "mixing_4_bass.mp3"]

            return try filenames.map { AKPlayer(audioFile: try AKAudioFile(readFileName: $0)) }
        } catch {
            fatalError()
        }
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        makeConnections()
        startAudioEngine()
        preparePlayers()
        startPlayers()
    }

    func makeConnections() {
        players.forEach { $0 >>> mixer }
        AudioKit.output = mixer
    }

    func startAudioEngine() {
        do {
            try AudioKit.start()
        } catch {
            print(error)
            fatalError()
        }
    }

    func preparePlayers() {
        players.forEach { player in
            player.isLooping = true
            player.buffering = .always
            player.prepare()
        }
    }

    func startPlayers() {
        let startTime = AVAudioTime.now() + 0.25
        players.forEach { $0.start(at: startTime) }
    }

}

Key points:
Use do {try expression} catch { error }, not try? expression.  While convenient to ignore an error, it will quickly bite you down the road.
Map and forEach, map is crucial for working with arrays.  Notice how an array of filenames is transformed into an array of AKPlayers.  Related, shorthand argument names: players.forEach { player in player.play() } is the same as players.forEach { $0.play() }. Also related, map re-throws, so you can try inside of map's closure.
Use closures to encapsulate. The players variable is populated as it's defined using an immediately evaluated closure. The alternative is to have to create this array on init, then later populate it.
Finally, separate logic into functions as much as possible. It makes your code more readable, and easier to maintain.


text:
Q: debo dar clic al elemento // * [@ id = \ "menu-content \"] / a [1] / li / h3 , almacenado en el tercer frame java, no ha sido posible

  <title>NetIQ iManager</title>
  <link rel="icon" type="image/png" sizes="16x16" href="/nps/portal/modules/dev/images/favicon.png">

<frameset rows="88,*,0" framespacing="0" frameborder="0" onload="top.name='eMFrame'" id="iManagerRootFrame">
  <frame src="webacc?taskId=fw.Header&merge=fw.iManagerHeader" id="Branding_ID" name="Branding" title="${requestScope['FrameTitle.HeaderFrame']}" noresize="" scrolling="no" marginheight="0" marginwidth="0">
    <frame src="webacc?taskId=dev.Empty&merge=fw.Body&view=Tasks" name="Mainscreen" title="${requestScope['FrameTitle.Mainscreen']}">
      <frame src="/nps/Empty.html" name="Bitbucket" title="Bitbucket">
</frameset>

<frameset cols="340,*,0">
  <frame name="Nav" title="Trama de navegación" src="webacc?taskId=fw.Nav&merge=fw.Nav&view=Tasks" frameborder="0" scrolling="no">
    <frame name="Content" title="Trama de contenido" src="webacc?NPService=fw.LaunchService&NPAction=CompleteReturn&returnID=fw.HomePage&firstTime=true" marginheight="15" marginwidth="15" frameborder="0">
      <frame name="Empty" src="webacc?taskId=dev.Empty&merge=fw.Empty&firstTime=true" marginheight="0" marginwidth="0" frameborder="0" noresize="">
</frameset>

  <title>Launcher</title>
  <link rel="stylesheet" href="/nps/portal/modules/dev/css/sideNavMenu.css">
  <link rel="stylesheet" href="/nps/portal/modules/dev/css/font-awesome.min.css">
  <link rel="stylesheet" href="/nps/portal/modules/dev/css/bootstrap.min.css">

   CAT

Definir contraseña

Modificar grupo

Estado de Usuario

Verificar Atributos

Verificar perfil

Comprobar estado de contraseña

   INVITADOS - NAC

Ingresar Invitado

Modificar expiracion Invitados


text:
Q: Using concurrent::map() with a list of QModelIndexes I am trying to use concurrent::run() on a list of QModelIndexes.  The function I'm trying to call looks like this:
writeXML(QModelIndex &index)

My map code looks like:
QModelIndexList list;
QFutureWatcher<void> futureWatcher;
futureWatcher.setFuture(QtConcurrent::map(list, list->writeXML() ));

futureWatcher.waitForFinished();

I'm getting a compile error saying "No matching function for call to writeXML().
I have looked at this tutorial which I found useful: http://www.bogotobogo.com/Qt/Qt5_QtConcurrent_QFutureWatcher_QProgressDialog_map.php
But I don't yet understand how the index get passed to the function, in my case writeXML() ?
What do I need to do with my code above to get this at least compiling?

A: QModelIndexList is just a typedef for QList<QModelIndex> and of course QList has no writeXML method, because it is your custom function. You need one container (list) and one function (writeXML), so it should be.
QModelIndexList list;
QFutureWatcher<void> futureWatcher;
futureWatcher.setFuture(QtConcurrent::map(list, writeXML));
//valid only if writeXML is a function, not a class member function!

futureWatcher.waitForFinished();

Another example:
QMutex mutex;
void writeXML(QModelIndex & index)
{
    QMutexLocker lock(&mutex);
    qDebug() << index.data();
}
//...
{
    //somewhere

    //get list of indexes
    QModelIndexList list = ui->tableView->selectionModel()->selectedIndexes();
    QFutureWatcher<void> futureWatcher;
    //apply writeXML to each index
    futureWatcher.setFuture(QtConcurrent::map(list, writeXML));

    futureWatcher.waitForFinished();
}


text:
Q: XPage view control search not working I am new to domino designer and I am required to develop an application with it. I have went through some tutorials and I am stuck at the search function. I have followed guides I found but the search function in view control is not functioning. When I input anything into the search string(even static value), I get a server error 500. The error code is not very useful for solving my problem.(I have the full text index enabled.)
I tried to create my forms and views with the SiteFinderDemo template. I do not get an error but any search string returns 0 results.
I can modify the SiteFinderFinal's codes to work the way I want properly with the demo documents, but the search function else where just cannot work.
I also noticed new documents created with forms or xpages within the SiteFinderDemo instead of the agent do not work with the search function. I assume it has something to do with the full text searching, but I cannot find any information about it. What am I supposed to set up my application so that the search in view control can work without the server error, and what should I do to make new documents work with the search?
Thank you very much and sorry for such a long question.


text:
Q: Can a sum and square sum of a multiset of size n be equal to the square sum and sum of [n] I have a multiset A of $[n]$, $|A| = n$ and $A\not = [n]$ (i.e., A has at least one element repited) whose sum is equal $\frac{n(n+1)}{2}$, i.e.,
$$\sum_{a\in A} a = \frac{n(n+1)}{2}$$
Can it's square sum $\sum_{a\in A}a^2$ be equal to $\frac{n(n+1)(2n+1)}{6}$?

A: Searching for numbers that can be written in many ways as a sum of a certain number of squares produces results quickly. I imagine there are very many qualifying results.
Using the result for $129$ noted in Determining the number of ways a number can be written as sum of three squares,
$$10^2+5^2+2^2=8^2+8^2+1^2=129$$
and noting $10+5+2=8+8+1$, it's easy to see that your property holds for the multiset  $\{1,1,3,4,6,7,8,8,8,9,11\}$ (by substituting $\{1,8,8\}$ for $\{2,5,10\}$ in $[11]$).
I "went to eleven" here just so that $n$ was included in $A$.

A fairly simple program search for numbers that can be represented as a sum of three positive squares multiple ways with common sums finds the smallest solution that has at least one of the solutions being composed of distinct numbers as $62 = 1^2+ 5^2 +6^2 = 2^2 + 3^2 + 7^2$ so the least $n$ is probably $7$.
results to $200$:
sq total 62 sum 12 (1, 5, 6) (2, 3, 7)
sq total 89 sum 15 (2, 6, 7) (3, 4, 8)
sq total 101 sum 15 (1, 6, 8) (2, 4, 9)
sq total 118 sum 16 (1, 6, 9) (3, 3, 10)
sq total 122 sum 18 (3, 7, 8) (4, 5, 9)
sq total 129 sum 17 (1, 8, 8) (2, 5, 10)
sq total 134 sum 18 (2, 7, 9) (3, 5, 10)
sq total 146 sum 18 (1, 8, 9) (3, 4, 11)
sq total 150 sum 18 (1, 7, 10) (2, 5, 11)
sq total 153 sum 19 (2, 7, 10) (4, 4, 11)
sq total 161 sum 21 (4, 8, 9) (5, 6, 10)
sq total 166 sum 20 (2, 9, 9) (3, 6, 11)
sq total 173 sum 21 (3, 8, 10) (4, 6, 11)
sq total 185 sum 21 (2, 9, 10) (4, 5, 12)
sq total 189 sum 21 (2, 8, 11) (3, 6, 12)
sq total 194 sum 20 (1, 7, 12) (3, 4, 13)
sq total 194 sum 22 (3, 8, 11) (5, 5, 12)

OEIS A282241 is (I think) a subset of these values.

This property becomes common for larger numbers; $6515$ of the numbers up to $10000$ can be expressed as a sum of three squares in two or more ways where the square roots also have a common sum.
Python code (improved to get to higher numbers):
lim = int(input('Search limit: '))
rlim = int(lim**0.5)
sqval = {i:i*i for i in range(rlim+1)}

# sieve
allz = []
for a in range(1,rlim+1):
    for b in range(a,rlim+1):
        ab = sqval[a]+sqval[b]
        if ab > lim:
            break
        for c in range(b, rlim+1):
            abc = ab+sqval[c]
            if abc > lim:
                break
            allz.append( (abc, a+b+c, a,b,c) )
# print(len(allz))
allz.sort()
allz.append( (0,0,0,0,0) ) # force action on last totals

pM = 0
pt = 0
mz = []
qct = 0
Mql = 0
for M,t,a,b,c in allz:
    if M != pM or t != pt:
        # report previous block if sutiable
        if len(mz) > 1:
            if any(len(set(mzi))==3 for mzi in mz):
                # report suitable results
                Mql = 1
                print("sq total", pM, "sum", pt, *mz)
        mz = []
        pt = t
        if M != pM:
            qct += Mql
            pM = M
            Mql = 0
    mz.append( (a,b,c) )

print (qct, "numbers in range have a suitable representation")


text:
Q: Will the array datatype in a Rails 4 and Postgres app maintain the order of the items in the array? I am curious about using the datatype :array in a Rails 4 app using a Postgresql database. Will the order that items are added to the array be preserved? My use-case is as follows: I want to allow three people to be added as :collaborators to a Search model. When I return the collaborators of a specific Search, I want to always list the collaborators in the order they joined the search. Is the :array datatype appropriate for this or should I consider using :hstore instead?

A: The array datatype preserves order, while hstore doesn't seem to guarantee it.
But also, maybe think about adding a proper collaborators relationship, if you want to link to another table.


text:
Q: How to detect chrome version in NSIS? My webapp need to depend on chrome browser, so when the app installs, i have to detect the chrome browser version in Nsis script.
I try to use the following script, but it does not work. The $R0 is empty string.
!define CHROME "\Software\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome"
ReadRegStr $R0 HKLM "${CHROME}" "UninstallString"

How to detect chrome version information in NSIS script ?

A: You should look into the current user settings instead of the local machine (or in addition to the local machine if the resulting string is empty):
ReadRegStr $R0 HKCU "${CHROME}" "UninstallString"

Also you should not have a backslash at the beginning of the key path. Did you noticed a warning during the script compilation?
ReadRegStr: registry path name begins with '\', may cause problems


text:
Q: ODE help. $u''(x) +(-2 -x^2 )u = 0 ,\quad 0$u''(x) +(-2 -x^2 )u = 0 ,\quad 0<x<1,\quad u'(0)=u'(1) = 0.$
I'm not sure where to even start. What method?

A: $u\equiv0$ is a solution. Are there any others? The answer is no. To see this, multiply the equation by $u$ and integrate between $0$ and $1$, to get
$$
\int_0^1u''(x)\,u(x)\,dx=\int_0^1(2+x)^2\,(u(x))^2\,dx.
$$
The right hand side is non-negative. Integrating by parts and using the boundary conditions, we see that the left hand side is non-positive. It follows that
$$
\int_0^1(2+x)^2\,(u(x))^2\,dx=0
$$
and $u\equiv0$.
This argument works for any equation $u''(x)=V(x)\,u(x)$ with $V(x)\ge0$ and boundary conditions $u(0)=u(1)=0$, $u(0)=u'(1)=0$, $u'(0)=u(1)=0$, or $u'(0)=u'(1)=0$.


text:
Q: Create a CardDav client to fetch contacts from server in iOS I have read up almost all the questions here on SO regarding carddav and didn't find an answer for my question. Do let me know if this already answered.
I need to create an app which implements a CardDav client to fetch contacts from the server. I am aware of using existing AddressBook framework and make iOS do the heavy lifting. However, our app is more catered to elderly people and business feels not all might be able to navigate into settings and add server information manually. (I am looking into automating this, information from another SO thread).

*

*Is there a SDK available in objective C that I can use to fetch/edit and delete contacts.

*Is there a way to avoid syncing of existing contacts from other sources like iCloud or Gmail to be synced back to our server when default account is switched.

Any pointers or guide to build a native carddav client is deeply appreciated.
Many Thanks


text:
Q: How to get all IDs from Mongo with no record in the past hour Considering the following documents:
[{
    "imei": "352413080100000",
    "datestamp": "2019-03-25T19:17:11.471Z"
}]

How can I get a unique list of all imei where there is no record for the past hour?

A: You can use $group aggregation to find the unique record for the imei field and use moment library to cut of the last hour from the current time.
db.collection.aggregate([
  { "$match": {
    "datestamp": {
      "$lte": moment().subtract(1, 'hours').toDate()
    }
  }},
  { "$group": {
    "_id": '$imei'
  }}
])

Or even you can use distinct query as well
const imeis = await db.collection.distinct('imei', { "datestamp": { "$lte": moment().subtract(1, 'hours').toDate() } })
console.log(imeis)


text:
Q: Applying a background image to listview with textview I'm trying to create a listview with a static background image (i.e. not contained within the individual list cells, but fills the display and does not move when list is scrolled).  I've found a couple references here and am trying to implement, but no joy.  The first is;
Set a background for a listview
In particular, I'm trying this;
    //set background to Drawable
listView.setBackgroundDrawable(myDrawable);

To create the "myDrawable" variable, I'm using a suggestion from;
How can I access an android drawable by a variable
Again, the particular code I'm trying is;
String icon="logo" + cnt;
 int resID = getResources().getIdentifier(icon, "drawable",  getPackageName());
 logo.setImageResource(resID);

Here is the code I created;
ListView lv = getListView();
  lv.setTextFilterEnabled(true);

  String bg="football_turf_subtle";
  int resID = getResources().getIdentifier(bg, "drawable", getPackageName());
  myDrawable.setImageResource(resID);

  lv.setBackgroundDrawable(myDrawable);

The problem I'm running into in my code is "myDrawable cannot be resolved"?  If it's not obvious, I'm new to Android/Java.
Thanks in advance for any help!

A: Just do lv.setBackgroundResource(R.drawable.football_turf_subtle).


text:
Q: Division with two integers returns value with wrong comma I'm experience a strange problem on one of my customers sites:
$val1/$val2 = 0,123

Note the , in 0,123 as comma where it should be a dot ..
Is this a server setting which I don't know?
The $val are definitely integers but just in case -  this doesn't work too:
intval($val1)/intval($val2) = 0,123

PHP version is 5.4.43-1~dotdeb+7.1 on Apache/2.2.22 (Debian)

A: Your locale is clearly set to something in which a decimal is represented by a comma.
To show the current locale:
var_dump(setlocale(LC_ALL, 0));

To show the current numeric formatting info:
var_dump(localeconv());

In order to avoid unintended changes to other localized bits of your code I'd suggest changing only LC_NUMERIC to your desired region. eg:
setlocale(LC_NUMERIC, 'en_US');

Documentation: http://php.net/manual/en/function.setlocale.php


text:
Q: How do you use a string from a list to call a function with the same name, in Python? I wasn't able to find a satisfying answer anywhere so I decided to ask.
Let's say we have a global counter and a global list
counter=0
list=["function1","function2",..."functionN"]

we also we have those functions defined:
def function1():
  pass
def function2():
  pass
.
.
.
def functionN():
  pass

I have an interface with a button, every time I press it, the global counter increments. Depending on the number, I need to call a different function. I can implement this with if and elif but I don't think it's that smart.
Is there a way I can call those functions using the list?
Example
when counter=0=>list[0]=>the string is 'function1'=> call function1()
press button again
counter=1=>list[1]=>the string is 'function2' => call function2()

A: You can call a function by its name like this:
locals()["myfunction"]()
or:
globals()["myfunction"]()
or if its from another module like this:
import foo
getattr(foo, 'myfunction')()

Or if it suits your use case, just use a list of functions instead of a list of strings:
def func1():
    print("1")

def func2():
    print("2")

def func3():
    print("3")

def func4():
    print("4")

some_list=[func1, func2, func3, func4]

# call like this
for f in some_list:
    f()

# or like this
some_list[0]()

A: Similar to what @chepner said, I would approach the problem that way.
Potentially storing the functions in a dictionary and looking up the function based on the counter:
def function():
    print('function 1 called')

def function2():
    print('function 2 called')

counter = 0

functions = {
    1: function,
    2: function2
}

Then:
function_to_call = functions[counter + 1]

and now that when function_to_call() is called it would print function 1 called
This is how I would think about approaching the problem.


text:
Q: Equivalent definition of essential supremum Let $(X,\mathcal{A},\mu)$ be a measure space and let $f\colon X\to [-\infty,+\infty]$ be a measurable function. Denote with $\mathcal{N}_\mu$ the collection of $\mu$-null sets.
On same text the definition of essential supremum is

$$\operatorname{esssup}f:=\inf\left\{\sup_{x\in X\setminus N} f(x)\;\middle|\; N\in\mathcal{N}_\mu \right\}\tag 1$$

In other texts it is:

$$\operatorname{esssup}f:=\inf\left\{a\ge 0\;\middle|\;\mu\left(\{x\in X\;\middle|\; f(x)>a\}\right)=0         \right\}\tag2$$

Question Are $(1)$ and $(2)$ equivalent? Why?

A: I think you need $a\in \mathbb{R}$ and f(x) without the absolute value. Otherwise f konstant -1 is a couterexample. But if you correct this, the two definitions are equivalent:
Let $A:= \{\sup_{x\in X\setminus N}f(x)\mid N\in \mathcal{N}_{\mu}\}$ and $B:= \{a\in \mathbb{R}\mid \mu(\{x\in X\mid f(x)>a\})=0\}$. We show $\inf A=\inf B$:
"$\geq$": For $N\in \mathcal{N}_{\mu}$ we have $\{x\in X \mid f(x)>\sup_{x\in X\setminus N}f(x)\}\subseteq N$, and hence $\mu(\{x\in X \mid f(x)>\sup_{x\in X\setminus N}f(x)\})=0$. Therefore, $A\subseteq B$ and $\inf A\geq \inf B$.
"$\leq $": Let $a$ be given such that $\mu(\{x\in X\mid f(x)>a\})=0$ and define $N:= \{x\in X\mid f(x)>a\}$. Then $N\in \mathcal{N}_\mu$ and for $x\in X\setminus N$ we have $f(x)\leq a$, hence $\sup_{x\in X\setminus N}\leq a$. So for all $x\in B$ there is a $y\in A$ with $y\leq x$. Therefore, $\inf A\leq \inf B$.


text:
Q: How do I call other Google APIs from a Cloud Function? I would like to call other Google APIs from my cloud function, for example, to write a file to Cloud Storage after receiving a message from Pubsub.  How can I do this?

A: You can use the google-cloud client library for Node.js to accomplish this. The same library is also available for Java, Python and Ruby.
For example in Node JS, you'll want to edit your package.json file accordingly:
{
  "dependencies": {
    "google-cloud": "*"
  },
  ...
}

Then, in your code, you can simply invoke the relevant library.  The following example just lists the buckets in the project:

var gcloud = require('google-cloud');

exports.helloworld = function(context, data) {
  var gcs = gcloud.storage({projectId: '<PROJECT>'});
  gcs.getBuckets(function(err, buckets) {
    if (!err) {
      buckets.forEach(function(bucket) {
        console.log(bucket.name);
      });
    } else {
      console.log('error: ' + err);
    }
  });

  context.success();
}

You also shouldn't include the entire google-cloud npm module, but instead specify a specific sub-module, e.g. require('@google-cloud/storage') in the above example.


text:
Q: wrapper div doesn't completely sorruound it's chields Here i have a form .It has a couple of label and input elements.I have a wrapper div which is supposed to wrap it's child elements completely( in my case label and input element ).But it only wraps the label element.I need it to cover the input element too.How it can be solved?

<form action='<?php echo $_SERVER['PHP_SELF']; ?>' id='mydiv' method='post' enctype='multipart/form-data'>

            username

             <input type='text' class='field' name='username' value='' autocomplete='off'>

            password

            <input type='password' class='field' name='password' value='' autocomplete='off'>

            password_again

            <input type='password' class='field' name='password_again' value='' autocomplete='off'>

            Full Name

            <input type='text' class='field' name='name' value='' autocomplete='off'>

       <input type='submit' value='register' >

   <input type='hidden' name='token' value="<?php echo Token::generate(); ?>">

</form>

A: It doesn't wrap the input field because you set the height of the div (class='whole') to 50px. You can remove the height property or set it to auto.


text:
Q: Two scripts refuse to run together I've encountered a strange issue while trying to run scripts within my .cshtml file. I am trying to run a script that sets an icon depending on how the user clicks on it, and other which uses the Leaflet Javascript library to display a map.
My issue is that only the last script to be listed in the section works (aka if I put star.js after mapdisplay.js, star.js would work and mapdisplay.js would not, and vice-versa).
I am running this on .NET 5.0
Index.cshtml - @section scripts
@section scripts {
    <script type="text/javascript" src="~/scripts/star.js"></script>

    <script>
        var lat = '@Model.Latitude';
        var long = '@Model.Longitude';
    </script>

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
            integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
            crossorigin="">
    </script>
    <script type="text/javascript" src="~/scripts/mapdisplay.js"></script>
}

And just in case, here's both scripts.
star.js
window.onload = function () {
    //Adds click event handler to make an AJAX request to star when the star is clicked
    $(".clickable").click(function () {
        let star = $(this);

        //Might be undefined if user deletes the attribute
        if (star.attr("reportId") != undefined) {
            let id = parseInt(star.attr("reportId"));

            //NaN might happen if user changes reportId attribute to something which isn't a number
            if (!isNaN(id)) {
                let dataToSend = {
                    reportId: id
                }

                //Sends ajax request
                $.ajax({
                    type: 'POST',
                    url: '/Home/Star',
                    data: dataToSend,
                    dataType: "json",
                    success: function (response) {
                        if (response) {
                            //If StarReport finished successfully, update the UI
                            if (star.hasClass("starred")) {
                                star.removeClass("starred").addClass("unstarred");
                            } else {
                                star.removeClass("unstarred").addClass("starred");
                            }
                        }
                    }
                });
            } else {
                alert("Don't mess with the code!");
            }
        } else {
            alert("Don't mess with the code!");
        }
    });
}

mapdisplay.js
window.onload = function () {
    //Creates map bounds
    let topLeftCorner = L.latLng(35.11111111115, 14.111111111);
    let bottomRightCorner = L.latLng(35.1123231312, 14.67243783646247);
    let bounds = L.latLngBounds(topLeftCorner, bottomRightCorner);

    let map = L.map("map", {
        center: L.latLng(lat, long),
        zoom: 14,
        zoomControl: false,
        dragging: false,
        keyboard: false,
        maxBoundsViscosity: 1.0
    });

    map.setMinZoom(18);

    L.tileLayer(
        'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
    ).addTo(map);

    marker = L.marker([lat, long], { draggable: false }).addTo(map);
}

Any help would be appreciated, as this is driving me nuts.

A: For closure's sake I'll respond to my own question. As user:charlietfl pointed out in comments, window.onload can only be assigned to one function.
I personally simply solved this by using window.addEventListener('load', function () { in the .js files instead of window.onload, which works in my context.


text:
Q: Lumia imaging sdk 3 blur effect issue (The component cannot be found. (Exception from HRESULT: 0x88982F50)) I need to render an xaml element and apply a blur effect using LumiaImageSDK 3
            var bitmapRended = new RenderTargetBitmap();
            await bitmapRended.RenderAsync(LayoutRoot);

            IBuffer buffer = await bitmapRended.GetPixelsAsync();

            var target = new WriteableBitmap(bitmapRended.PixelWidth, bitmapRended.PixelHeight);
            var source = new BufferImageSource(buffer);
            var blur = new BlurEffect(source, 128);

            var renderer = new WriteableBitmapRenderer(blur, target);

            var result = await renderer.RenderAsync();

            var imgBrush = new ImageBrush();
            imgBrush.ImageSource = result;

            Menu.Background = imgBrush;

but when i run the code i get this error:
The component cannot be found. (Exception from HRESULT: 0x88982F50)

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

i think is something related to the way i convert the  RenderTargetBitmap to an IRandomAccessStream.
the exception is raised from this line of code : var result = await renderer.RenderAsync();
it seams that the problem is a deadlock but i'm not able to find a solution
edit: code updated

A: I got the same issue when using Lumia Imaging SDK. I am still checking the issue. However, to blur a image, using Win2D is a alternative choice.
Your code above shows how to render a XAML UIElement as s stream or sth. Then you can blur it by using Win2D library. I have post simply talking about how to do the blur stuff.
Hope it helps.

A: Since you have a IBuffer with the result (IBuffer buffer) then skip all the buffer manipulation and just create a BufferImageSource.
var target = new WriteableBitmap(bitmapRender.PixelWidth, bitmapRender.PixelHeight);
using (var source = new BufferImageSource(buffer))
using (var blur = new BlurEffect(source , 128))
using (var renderer = new WriteableBitmapRenderer(blur, target))
{
    var result = await renderer.RenderAsync();
}

That said I can't see an obvious problem with the code you wrote. I will have to look into it, but until then, have you made sure the stream is at the beginning? That is a common error with streams.


text:
Q: AnyLogic Car library: Is there a way of checking if a route exists for a given destination? I am using AnyLogic car library and have multiple roads and parking lots. However, not every parking slip is accessible from every road. I want to detect this beforehand if the car won't be able to make it to the destination and send them to somewhere else.
Currently when the car enters the carMoveTo37 block, it throws an error if there is no way of reaching the destination.

Is there any way of checking this before entering the carMoveTo block?

A: Yes, you can simply use the bottom out-port as per the help:

So simply reroute those cars via that port or do something else with them :)


text:
Q: Is Mac OS X a UNIX-based OS? Is OS X Mountain Lion a pure UNIX-based OS?
Some tutorials say that it is a Unix-like OS, but after version 10.5, all Mac operating systems are based on pure UNIX.
Is this true?

A: There's a lot of discussion on this topic, but as far as Apple's concerned, yes it's UNIX:

Open source UNIX foundation

*

*POSIX-compliant, Open Brand UNIX 03 Registered Product

*Open source kernel based on FreeBSD and Mach 3.0

*64-bit OS using LP64 data model

*Support for multiple CPU and GPU cores via Grand Central Dispatch and OpenCL

*Hand-tuned, standards-compliant scalar and vector math libraries

  Standards-based networking

*

*Complete IP-based architecture supporting IPv4, IPv6, and L2TP/IPSec VPN

*Rich zero-configuration discovery and naming via Bonjour and Dynamic DNS

*Interoperable file serving via NFS, AFP, SMB/CIFS, and FTP

*Powerful Apache web services

*Open Directory services built on LDAP and Kerberos for single sign-on

  Comprehensive UNIX user environment

*

*Standards-based graphics built on PDF (Quartz), OpenGL, and H.264 (QuickTime)

*Full-screen terminal with xterm-256color support

*Familiar UNIX/Linux utilities (such as emacs, vim, and bash)

*Free Xcode developer tools based on Clang/LLVM

A: The UNIX trademark is owned by The Open Group, which basically uses it as a certification mark for SUS-compliance. OS X has been registered as a UNIX 03-compliant product since 10.5, so it qualifies as UNIX (not just UNX or Unix-like) in that sense. Most GNU/Linux distributions are not registered as SUS-compliant, so they should be called something like UNIX-like or UNX in that sense, even though neither of those terms is used by The Open Group.
OS X could also be considered to be genetic Unix in the sense that Darwin was based on FreeBSD (or it has used FreeBSD as a reference platform), and BSDs are usually considered to be genetic Unix, since the original BSD was based on AT&T code. Both GNU and Linux were rewritten from scratch though, so GNU/Linux platforms are not generally considered to be genetic Unix.
In a functional or spiritual sense, OS X is maybe less Unix (whatever that means) than platforms that are merely "Unix-like" in the first or second senses, but OS X could still considered to "be Unix" in all three senses.


text:
Q: Pointer to a subarray of TypedArray Imagine we have
var a = new Float64Array([1, 2, 3]),
    b = new Float64Array([4, 5]);

var c = new Float64Array(a.length + b.length);

Now I want to combine a and b into c. I have written a C++ BLAS binding to copy data between two double/single precision arrays. Thing is, this binding has no offset attribute:
void cblas_dcopy(int n, const double *x, const int inc_x, const double *y, const int inc_y);

Can I get a subarray pointing to an offset of c's memory space? The following is called in JavaScript:
// copy first to result, works
cblas_dcopy(3, a, 1, c, 1);

// does not work because slice() returns a copy
cblas_dcopy(2, b, 1, c.slice(a.length), 1);

// now how would I copy to c at offset b.length?

A: You can actually do this easily without a C++ binding:
var a = new Float64Array([1, 2, 3]);
var b = new Float64Array([4, 5]);
var c = new Float64Array(a.length + b.length);
c.set(a, 0);
c.set(b, a.length);

To get the subarray as you asked, try using typedarray.subarray([begin[, end]]).


text:
Q: ObservableCollection<> CollectionChanged Not Firing I have a datagrid in a WPF app that is bound to an ObservableCollection like so
<DataGrid ItemsSource="{Binding Spring.SpringData, Mode=OneWay}" />

My data displays fine, and I can edit the data in my grid, but it does not fire the PublishSpringChange event when I manually edit the data in the grid. The underlying data changes, but the event does not fire, what am I missing?
With a model of Spring that has the following
public class Spring : INotifyPropertyChanged
{

    private ObservableCollection<SpringData> _SpringData;

    public ObservableCollection<SpringData> SpringData
    {
        get { return _SpringData; }
    }

     public Spring()
    {
        ....

        _SpringData = new ObservableCollection<SpringData>();
        SpringData.CollectionChanged += PublishSpringChange;

       ...
    }
    private void PublishSpringChange(object sender, NotifyCollectionChangedEventArgs e)
    {
        // Code that does not run!
    }
}

with a SpringData class of
public class SpringData: BindableBase
{
    private double _force;
    private double _displacement;

    public SpringData(double displacement, double force)
    {
        Displacement = displacement;
        Force = force;
    }

    public double Displacement
    {
        get { return _displacement; }
        set { SetProperty(ref _displacement, value); }
    }

    public double Force
    {
        get { return _force; }
        set { SetProperty(ref _force, value); }
    }
}

A: INotifyCollectionChanged only fires when you actually modify the collection. This is when you Add, Remove, Move, Replace or Reset items in the collection. It will not fire when one of the properties in a SpringData object is changed.
In order to listen to changes for a SpringData object, assuming it implements INotifyPropertyChanged, you will need to hook up listeners to the PropertyChanged event of each of the items.

A: Its quite useful to have a single handler for all properties changing sometimes.  Here's how you can do it.
Handle CollectionChanged as you are above:
_SpringData = new ObservableCollection<SpringData>();
SpringData.CollectionChanged += PublishSpringChange;

Now for all added and removed objects to the collection add a handler to PropertyChanged:
private void PublishSpringChange(object sender, NotifyCollectionChangedEventArgs e)
{
    foreach (INotifyPropertyChanged added in e.NewItems)
    {
        added.PropertyChanged += SpringDataOnPropertyChanged;
    }

    foreach (INotifyPropertyChanged removed in e.OldItems)
    {
        removed.PropertyChanged -= SpringDataOnPropertyChanged;
    }
}

private SpringDataOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
    //your code here
}


text:
Q: How to put screenshots in one pdf file? I have a setup where I run the test, and the screenshot is captured. If I run 100s of tests, I get 100s of png files in the screenshot folder. Is this possible to save all screenshots in one file as a pdf, rather than individual file.
Thanks!


text:
Q: Moving items in a listbox in c# I am adding file names from a directory in a list box which I am able to add successfully.I then should be able to arrange the files in the list box  by selecting a particular item & then moving it up or down.
The below function is an attempt to move the file up. I am trying to copy entire listbox items to an object and selected listbox
items to a different object.
Then if button is pressed the selected item should be swapped with the item above to it in the list.
I intend to change the new list and copy the items back to the original listbox.But I am unaware how to copy items from object back to the listbox
The below code does not work
private void plus_Click(object sender, EventArgs e)
    {

        object[] items = new object[listBox1.Items.Count];

        listBox1.Items.CopyTo(items, 0);

        object[] selecteditems = new object[listBox1.SelectedItems.Count];

        listBox1.SelectedItems.CopyTo(selecteditems, 0);

        object[] selectedindices = new object[listBox1.SelectedItems.Count];

        listBox1.SelectedIndices.CopyTo(selectedindices, 0);

       // listBox1.Items.CopyTo(items, 0);

        int upper_index = listBox1.Items.Count - 1;

        for (int i = 0; i < listBox1.Items.Count;i++ )
        {
           if ((i == (int)selectedindices[i])&&(i!=0))
            {
                    object temp = items[i];
                    items[i] = items[i - 1];
                    items[i - 1] = temp;
           }
        }

    }

A: At first sight it should not work because you're creating a new a list and not changing the actual DataSource for the ListBox. You need to move the items inside the DataSource itself, or you need to perform all that actions on a separate list and at the end, set the DataSource again.


text:
Q: PayPal Sandbox 'DoDirectPayment' Error Code 10501 When I attempt to DoDirectPayment I receive the error code saying I have an Invalid Configuration. Although there is a PayPal employee responding to all of the posts online that someone brings up this issue I can not find an actual fix.
Is there a way to add PayPal Payments Pro from a sandbox account?

A: Typically when you create a pre configured Website Payments Pro account, this should get enabled by default.  However from time to time, there are some issues that cause this not to get enabled.  A couple of options for getting this enabled is either trying to manually toggle it on, or trying to create a new pre configured account and see if it gets enabled on the new one.  If you can provide me the email address for your test sandbox seller account, I can try to toggle it manually on my side for you.


text:
Q: How to make sure there are no duplicates in an array? I've been trying to make my c++ program check for duplicates in an array, as I need this for a program I am writing. But, it doesn't work, and I think I know how what the issue is but I have no idea how to fix it.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>

using namespace std;

int asknum(int ask);
int check(int checking);

bool error = false;

int test [10] = {};

int i = 0;

int gen = 0;

int main() {
    //int gen = 0;

    for (i=0; i<10; i++) {
        gen = asknum(gen);
    }
    for (int b=0; b<10; b++) {
        cout << test [b] << endl;
    }

    return 0;
}

int asknum(int ask) {
    ask = 0;
    gen = 0;
    int nouse;
    cout << "Please enter a value: ";
    cin >> ask;
    error = 0;
    nouse = check(ask);
}

int check(int checking) {
    int n = 0;
    for (n=0; n<10; n++) {
        int temp = test [n];
        if (temp == checking) {
            cout << "Value is the same. Enter another value.\n";
            error = 1;
            gen = asknum(gen);
        }

    }

    if (n == 10) {

        if (error == 0) {
            gen = 0;
            test [i] = checking;
        }
    }
}

What's wrong with my code? The first time I wrote the code it worked perfectly. But when I noticed a flaw, which was that if you constantly entered a present number, it would stop asking for a new number, I decided to move the code into functions, but now it doesn't work properly! Here is the output:
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 3
That number already is used. Please type in another value.
Please enter a number: 4
Please enter a number: 5
Please enter a number: 6
Please enter a number: 7
Please enter a number: 8
Please enter a number: 9
Please enter a number: 10
1
2
3
3
5
6
7
8
9
10

I think there's something wrong with the communication. Please help!
Thanks!

A: After adding the duplicate 3 the program continues from the gen = asknum(gen); with error being assigned equal to 0 in function asknum(int ask). That is why it passes the if condition to assign ith element in the array. Remove error=0 from asknum(int ask) and put it after if condition in check:
EDIT :
checked it above solution was still giving same output however error value was same due to calling of asknum within asknum. to make it work change for loop for cin in main to:
for (i=0; i<10; i++) {

    gen = asknum(gen);
      if(error==1)
      {
          i--;
          error=0;
      }
    }

And check to:
int check(int checking) {
    int n = 0;
    for (n=0; n<10; n++) {
        int temp = test [n];
        if (temp == checking) {
            cout << "Value is the same. Enter another value.\n";
            error = 1;
            //fflush(stdout);
            //cin.clear();
            //gen = asknum(gen);
        }

    }
    //cout<<error<<"\n";

        if (error == 0) {
            gen = 0;
            test [i] = checking;
            cout<<checking<<" "<<i<<"\n";
        }
    //error=0;
}

Please check if this helps.

A: Okey, so what you want to do is ask the user for an integer and if that integer does not exist in your container you want to add it to the container.
In c++ I would suggest avoiding c-style arrays and instead look to use one of the c++ containers instead, for example std::set.
So what does the reference pages tell us about std::set?

Sets are containers that store unique elements following a specific order.

Sounds just like what we want!
The big advantage is that std::set has built in functionality to for example, find an existing element based on the value of the element.
An example of how this could look:
void getNumberFromUser(set<int>& numbers);

int main()
{
    set<int> numbers;

    for (int i = 0; i < 10; ++i) {
        getNumberFromUser(numbers);
    }

    for (auto& value : numbers) {
        cout << value << endl;
    }

    return 0;
}

void getNumberFromUser(set<int>& numbers)
{
    int value;

    cout << "Please enter a value: ";
    cin >> value;

    auto result = numbers.insert(value);

    while (!result.second()) {
        cout << "That number is already used. Please type in another value.\n";
        cout << "Please enter a value: ";
        cin >> value;

        result = numbers.insert(value);
    }
}

Since set::insert

return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

all we have to do is check if the second value of the returned pair is true or false to know if the value was already in use or not.
I hope this helped a bit and don't be afraid to look at the c++ reference pages, they are not as scary as you might think!


text:
Q: A sum of sum involving binomial coefficent.(my conjecture) While using MATLAB I found out that
$\displaystyle\sum_{k=0}^{n}\frac{(\sum_{r=\max (0,k+m-n)}^{\min (k,m)}(-1)^{r}\binom{n-m}{k-r}\binom{m}{r})^{2}}{\binom{n}{k}}=\frac{2^{n}}{\binom{n}{m}}
$
hold for all $m\leq n\leq 100\
$ and I proved that the equality hold for all $m=0,1,n-1,n\
$ but I couldn't prove it in general (or disprove).
 Any help is appreciated! Thanks in advance.

A: The credit for this proof goes to Dan Carmon.
Let $V$ be the space of homogeneous polynomial of degree $n$ in 2 variable $x$ and $y$ and let $T$ be the linear map defined as: $T(p)(x,y)=p(x+y,x-y)$.
Now note that: $T^{2}(p)(x,y)=T(p)(x+y,x-y)=p((x+y)+(x-y)),(x+y)-(x-y))=p(2x,2y)=2^{n}p(x,y)$
Let $A$ be the matrix representation of the linear transformation $T$ with the base $\left \{ x^{n},x^{n-1}y,...,xy^{n-1},y^{n} \right.\left. \right \}$
$\sum_{k=0}^{n}a_{m,k}x^{n-k}y^{k}=T(x^{n-m}y^{m})=(x-y)^{m}(x+y)^{n-m}\\=\sum_{k=0}^{n}\sum_{r=max(0,k+m-n)}^{min(m,k)}(-1)^{r}\binom{m}{r}\binom{n-m}{k-r}x^{n-k}y^{k}$
We are getting closer to end because now we know that $a_{m,k}=\sum_{r=max(0,k+m-n)}^{min(m,k)}(-1)^{r}\binom{m}{r}\binom{n-m}{k-r}$
and with sum (some) manipulation $\binom{m}{r}\binom{n-m}{k-r}\binom{n}{m}=\frac{m!(n-m)!n!}{r!(m-r)!(k-r)!(n-m-k+r)!(m-n)!m!}\\=\frac{n!}{r!(m-r)!(k-r)!(n-m-k+r)!}=\frac{n!(n-k)!k!}{r!(m-r)!(k-r)!(n-m-k+r)!k!(n-k)!}=\binom{k}{r}\binom{n-k}{m-r}\binom{n}{k}$
So $\binom{n}{m}a_{m,k}=\binom{n}{k}a_{k,m}$
The identity we seek to prove is equivalent to $\sum_{k=0}^{n}\frac{\binom{n}{m}a_{m,k}^{2}}{\binom{n}{k}}=2^{n}$
but the last identity yield:
$\sum_{k=0}^{n}\frac{\binom{n}{m}a_{m,k}^{2}}{\binom{n}{k}}=\sum_{k=0}^{n}a_{m,k}a_{k,m}=\left [ A^{2} \right ]_{m,m}=\left [ 2^{n} I\right ] _{m,m}=2^{n}
$
$\blacksquare$


text:
Q: Apex: Copy all populated values from one SObject record to another I like the way JavaScript lets you easily overlay two objects, retaining the properties of both:
let obj1 = {name: 'Foo', quantity: 3};
let obj2 = {name: 'Bar', description: 'A very nice bar'};
// Merge the objects. Where these object share properties, obj2 will "win"
let newObj = {...obj1, ...obj2};
console.log(JSON.stringify(newObj));
// Console output:
// {'name': 'Bar', 'quantity': 3, 'description': 'A very nice bar'};

I often find myself needing to do something similar in Apex when dealing with SObject records of the same type.  For example, when dealing with duplicates, or when working with dummy SObject records from test utilities.
I have a method for this, but it feels pretty heavy for what ought to be a simple task, relying (as it does) on a getDescribe() call:
// Push all populated, updateable field values from one SObject to another
// SObject of the same type
public static SObject transferSObjectFieldValues(
    SObject targetObject,
    SObject sourceObject,
    Boolean writeBlank
) {
    Map<String, Schema.SObjectField> fieldMap = targetObject.getsObjectType()
        .getDescribe().fields.getMap();
    Map<String, Object> sourceFields = sourceObject.getPopulatedFieldsAsMap();
    for (String fieldName : sourceFields.keySet()) {
        Object value = sourceFields.get(fieldName);
        if (fieldMap.containsKey(fieldName)
            && fieldMap.get(fieldName).getDescribe().isUpdateable()
            && (writeBlank ||
                (value != null &&
                    !(value instanceof String &&
                        String.isBlank((String)value))))) {
            targetObject.put(fieldName, sourceFields.get(fieldName));
        }
    }
    return targetObject;
}

Is there something more lightweight and straightforward I could be doing?


text:
Q: Does function inlining use more RAM or ROM? and what is effect on micro-controller's RAM? When I write an inline function in my code (a bare-metal code for stm32), I know that every time we call this inline function it is replaced with its definition this saves the overhead of a function calling i.e. save stack.
Now I am confused, between RAM and ROM usage of the inline function.
Can anyone please join memory usage of an inline function with RAM and ROM usage, especially in the context of a bare-metal code.

A: Your linker will be able to generate a link map with a summary of ROM and RAM usage - you can build with and without inlining and see the result for yourself.
Inlining causes copies of the code to replace calls to a single copy of code, so by definition the code space (ROM in your case) is increased. It has little effect on RAM, although reduce stack usage by a small amount because no return address is required.  That is a run-time reduction and will not show in the link map.
It will only make a difference if your compiler chooses to apply the inline request. GCC for example will not do so at the -O0 (default) optimisation level, and even then may not do so in all circumstances, and may even in-line code that is not explicitly marked for inlining.
Your compiler may have a means to force inlining, but the inline keyword is not it - for example in GCC you would use the __attribute__((always_inline)) function attribute.  However second guessing the compiler when it comes to what should and should not be inlined is generally a bad idea with a modern optimising compiler.  It will generally make better more holistic decisions on a code base of any significant size with no developer effort.

A: If you run your code from the FLASH memory, the length of the code does not affect your RAM usage. The code will be longer of course if the function is inlined more than once (but it is not guaranteed by the 'inline' keyword).
Another question is the usage of the SRAM memory for the local variables storage. Usually it will be lower as inlining allows more aggressive optimizations (inline functions can be used only if the optimizations are on - otherwise they will not be inlined).
'inline' keyword is only a suggestion for the compiler, if you want to force the inlining you need to use the apripriate attribute or pragma - for gcc __attribute__((always_inline))


text:
Q: How to come up with a flat count output in DocumentDB I am trying to come up with a simple, flat output for document counts in DocumentDB.  For example if I have the following three documents:
    {
      "id": "1",
      "statusId": "new",
    }
    {
      "id": "2",
      "statusId": "new",
    }
    {
      "id": "3",
      "statusId": "complete",
    }

and if I run this in the Azure Query Explorer:
    select Value Count(1) from c
    where c.statusId = "new"

I get this:
[
  2
]

What I am trying to figure out how to do is produce a result that looks something like this:
{
    "new": 2,
    "complete" : 1
}

Even if that's not possible it would be okay to just run multiple selects in the same window at once. However when I try that I get syntax errors in the Query Explorer, i.e.
select Value Count(1) from c
where c.statusId = "new"

select Value Count(1) from c
where c.statusId = "complete"

produces
Syntax error, incorrect syntax near 'select'.

A: According to your description, you want to implement function like SELECT COUNT(*) FROM XXX GROUP BY XXX in azure cosmosdb queries.
Per my experience, azure cosmosdb aggregation capability in SQL limited to COUNT, SUM, MIN, MAX, AVG functions. GROUP BY or other aggregation functionality are not be supported in azure cosmosdb now.
However, stored procedures or UDF can be used to implement your aggregation requirement.
You could refer to a great package documentdb-lumenize based on DocumentDb stored procedure.
Hope it helps you.

A: I am afraid, I don't have an easy answer for you. You can construct the desired JSON after getting the result back.
and second, today you can not execute two select statement in query window.


text:
Q: Adding coupon discounted price to woo-commerce product page Hello I am looking to show a coupon discounted price on a woo-commerce product pages. I found code that is written for woo-commerce 3.x but that is pretty outdated and we are running the latest release 6.9.1. The code for 3.x is below. Any help would be fantastic.
with this code it returns this error
syntax error, unexpected '}', expecting end of file
if ( WC()->cart->has_discount() ) {
        $values = array (
            'data'      => $product,
            'quantity'  => 1
        );
        $coupons = WC()->cart->get_coupons();
        $_price = $product->get_price();
        $undiscounted_price = $_price;
        if ( ! empty( $coupons ) ) {
            foreach ( $coupons as $code => $coupon ) {
                if ( $coupon->is_valid() && ( $coupon->is_valid_for_product( $product, $values ) || $coupon->is_valid_for_cart() ) ) {
                    $discount_amount = $coupon->get_discount_amount( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ? $_price : $undiscounted_price, $values, true );
                    $discount_amount = min( $_price, $discount_amount );
                    $_price          = max( $_price - $discount_amount, 0 );
                }
                if ( 0 >= $_price ) {
                    break;
                }
            }
            if ( ( $product->get_price() > 0 ) && ( $undiscounted_price !== $_price ) )
                $price = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $undiscounted_price ) ), $_price ) . $product->get_price_suffix();
        }
    }
    return $price;
}


text:
Q: How do I describe the two types of adjectives, terminologically? In adjectives there are two main groups:
First Group: adjectives that their 3 grades (base, comparative and superlative) are changed whether regularly (nice > nicer > nicest) or irregularly (good > better > best).
Second group:  adjectives that their 3 grades, are changed by adding "more" or "most" (e.g. "more expensive" or "most expensive" rather than expensivier or expensiviest)
Then my question is, how are these two groups distinguished terminologically?

A: I think the OP is asking how to classify the different types of adjectives. Apologies if I have misunderstood.
Basically, adjectives can be classified by the number of syllables. The rules governing disyllabic adjectives are a bit complicated to go into any great detail but see this question and the answers posted on EL&U if you are curious.
Adjectives consisting of one syllable are monosyllabic
They can also be called one syllable adjectives.
Adjectives with two syllables are bisyllabic  or
disyllabic
Or they can simply be called two syllable adjectives
Adjectives with three syllables are  trisyllabic or three syllable adjectives

*

*In English, the comparative can be formed either synthetically (prouder) or analytically (more proud). Quirk et al. (1985: 461) identify word length as the major factor in the distribution, suggesting that the synthetic comparative is formed by monosyllabic adjectives, while trisyllabic or longer adjectives form the analytic comparative.

*Disyllabic adjectives are said to exhibit variation. While word length does seem to have a strong effect, exceptions such as more apt or
  trustworthier indicate that more factors have to be considered.
The English comparative - Phonology and Usage


text:
Q: Is android application able to retrieve location info from connected WiFi hotspot AP? Wanted to know how Lat/Long info will be retrieved for specific location where my mobile device is connected to one of the public WiFi hotspot AP. So, my program gets the data and pass on to find location info to originate E911 calls or sending location info for any calls made?
 if this possible, let us know how this can be done? are there any specific Android APIs to do so? Please provide the details if possible.

A: You can't get location direction from WiFi hotspot (actually WiFi spot itself doesn't know where it's located).
However, there are databases which contains mapping between WiFi hotspot MAC address and locations. So, your application should get info about WiFi hotspot and after go to one of this databases.
As example, check this out:
http://en.wikipedia.org/wiki/Skyhook_Wireless

A: Location can be retrieved using various ways in android from GPS or from your internet access ( whether its wifi or 3G) the great thing is that in android the last location that was retrieved from any application on the device will be saved and you can actually compare your currently retrieved location with the previous to see if its better or more accurate.
Here is a link that can let you understand better how location works with android.


text:
Q: Run WinCE application I am working on VC++ for WinCE application development. I want to know that, once, I have compiled the project, how to see the output of it on PC ? Can I run the application without the hardware (The development board on which WinCE is loaded) on the computer or I must need the hardware device for it ?

A: Your binary will be compiled for a different OS (Windows CE) and potentially a different processor.  That means that your desktop OS will have no ability to execute the application.
There are some emulators that ship with the development tools (Windows Mobile, Pocket PC, etc) and there's even a standalone emulator and Emulator BSP for creating your own; you can run one of them on your desktop machine and then have that emulator run your code.  That might work, depending on your target CPU (Microsoft's DeviceEmulator emulates ARM, so you must compile for ARM).
So the short answer is no, you can't run it on your desktop directly, but if you use an emulator, you might be able to use the app (depending on if it uses non-emulated hardware or not).


text:
Q: Removing consecutive duplicate symbols from a vector I have a vector which is full of + symbols separating valid characters. I need to remove replicate, consecutive + symbols, but retain non-consecutive + symbols which are used as separators.
Below is an example dataset:
df <- data.frame(name = c(A="a+++a+b+c++++d+d+d"))

                name
  a+++a+b+c++++d+d+d

Below is the desired output:
           name
  a+a+b+c+d+d+d

Below is the code I tried to use to substitute the repeated ++ symbols with +.
sub("++", "+", df$name)

When I try this I get the error below:
Error in sub("++", "+", df$name) :
  invalid regular expression '++', reason 'Invalid use of repetition operators'
In addition: Warning message:
In sub("++", "+", df$name) :
  TRE pattern compilation error 'Invalid use of repetition operators'

A: You can try below:
df <- df %>% mutate(name=gsub("\\++","\\+",name))

output:
           name
A a+a+b+c+d+d+d

A: sapply should work
df$name <- sapply(df,  function(x) { gsub("\\++", "\\+", x) })


text:
Q: c# Serial-port: Receiving some echo I have made a tiny program, witch can send and receive over a serial port.
My problem is that when I send commands ex: "netcfg" I get this echo:

At the spaces it displays the UTF8-code 08. If you convert to java script it displays: \b
But the output just have to be: netcfg, not: n ne net netc netcf netcfg
so the output i want loks like this:
"sds://>netcfg" and then newline.
I can see that the device understands my command, but this doesn't look nice, so please help me.
My code is messy right now but here it is anyway:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private string _TerminalString;

        public Form1()
        {
            InitializeComponent();
            if (!mySerialPort.IsOpen)
            {
                mySerialPort.Open();
                txtTerminal.Text = "The port is now open";
            }
            else
            {
                txtTerminal.Text = "The port is in use";
            }
        }

        private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            _TerminalString = mySerialPort.ReadExisting();

            Invoke(new EventHandler(displayText));
        }

        private void displayText(object o, EventArgs e)
        {
            byte[] str2 = Encoding.ASCII.GetBytes(txtSend.Text);
            var testList = new List<byte>(str2);
            testList.Add(0x0D);
            byte[] str3 = testList.ToArray();
            mySerialPort.Write(str3, 0, str3.Length);
            txtTerminal.AppendText(_TerminalString);
        }

        private void bSend_Click(object sender, EventArgs e)
        {
            byte[] str2 = Encoding.ASCII.GetBytes(txtSend.Text);
            var testList = new List<byte>(str2);
            testList.Add(0x0D);
            byte[] str3 = testList.ToArray();
            mySerialPort.Write(str3, 0, str3.Length);
        }

        private void bClear_Click(object sender, EventArgs e)
        {
            txtTerminal.Clear();
            txtSend.Clear();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            mySerialPort.Close();
        }

        private void btnSearchForComPorts_Click(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                cbmComPorts.Items.Add(port);
            }
        }

        private void btnSelectComPort_Click(object sender, EventArgs e)
        {
            if (mySerialPort.IsOpen)
            {
                mySerialPort.Close();
            }

            mySerialPort.PortName = cbmComPorts.Text;
            txtTerminal.AppendText(cbmComPorts.Text);
            mySerialPort.Open();
        }

        private void btnNetcfg_Click(object sender, EventArgs e)
        {
            // netcfg + enter
            byte[] str = {0x6E, 0x65, 0x74, 0x63, 0x66, 0x67, 0x0D, 0x0A};

            mySerialPort.Write(str, 0, str.Length);
        }
    }
}

A: The ASCII character 8 is a backspace character. It appears that the program on the other end of your serial cable is trying to erase characters entered at its prompt before reprinting the came thing, with your new character added to the end.
Change your program to detect when ASCII 8 is received, and then delete the last character and move the cursor position back one. Might be tricky if you backspace through a new-line... I would ignore it if you're already at the left edge.
You might see other things too. There is a BEL character (7?) that should cause the terminal to beep. There are other characters for other things...
It's possible too, if you start seeing other weird things, that this device expects the user (you) to handle VT100 or ANSI terminal commands. You'll probably see things like ^[12n if that's the case (replace the ^[ with a little square with a lot of fonts in Windows. It's the escape character.
Ah, the good ol' days of BBSes.