text:
Q: On the first column. I have codes like 2abc and 22abc ı want 2's to become 02abc I have a column of barcodes. Like 2abc, 3sdh, 23dgs, 41eds extc. I will match these to a list by using VLOOKUP with first two numbers of the barcodes. But first ı need to make 2abc to 02abc, 3dsh to 03 sdh extc.
I need to put infront of the number if it is just one digit number.
I have figured ı can use VLOOKUP after ı have first two characters as numbers.

A: Try this:
=IF(ISERR(INT(LEFT(A1,2))),TEXT(LEFT(A1,1),"0#")&MID(A1,2,LEN(A1)), A1)


text:
Q: When does copy(foo) call foo.copy? I'm designing a base class, and I want it to define a base behaviour for copy.copy.
This behaviour consists in printing a warning in the console, and then copying the instance as if it had no __copy__ attribute.
When one defines a blank Foo class and copies an instance of it, the copy function returns a new instance of that class, as shown by the following session:
>>> class Foo: pass
...
>>> foo = Foo()
>>> foo2 = copy(foo)
>>> foo is foo2
False

Now if the Foo class defines a __copy__ instance method, the latter will be called when trying to pass an instance to copy:
>>> class Foo:
...     def __copy__(self):
...         print("Copying")
...
>>> foo = Foo()
>>> copy(foo)
Copying

So as I understand it, the flow of execution of the copy function would be:

*

*Try to access the object's __copy__ attribute

*If present, call it

*If absent, perform a generic copy

But now, I want to capture the copy function's accessing the __copy__ attribute, through defining a __getattr__ method, and then simulate the absence of this attribute, by raising an AttributeError:
>>> class Foo:
...     def __getattr__(self, attr):
...         if attr == '__copy__':
...             print("Accessing '__copy__'")
...             raise AttributeError
...

Then the __copy__ attribute does not seem to be accessed anymore:
>>> foo = Foo()

# Actual behaviour of copy(foo)
>>> copy(foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Miniconda3\lib\copy.py", line 96, in copy
    rv = reductor(4)
TypeError: 'NoneType' object is not callable

# Expected behaviour of copy(foo)
>>> foo.__copy__()
Accessing '__copy__'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __getattr__
AttributeError

What am I missing in the execution flow of the copy function, with regards to the __copy__ attribute?
As far as I understand, given a foo object with no attribute bar, it should behave exactly the same, whether it has a __getattr__ method that fails on bar, or it doesn't define anything.
Is this statement exact?

A: Short answer seems to be "no".
Within the copy.copy method we find this (summarized)
cls = type(x)

...

copier = getattr(cls, "__copy__", None)

We see that the function uses getattr on the class, not the instance.
And there's no way to have __getattr__ called when getattr is called on the class (just because it's an instance method)
Demo (sorry, I would have prefered a working demo)
class Foo:
    def __getattr__(self,attr):
             if attr == '__copy__':
                     return "WORKED"

foo = Foo()
print(getattr(foo, "__copy__",None))
print(getattr(Foo, "__copy__",None))

this returns:
WORKED
None

So it's not possible to fool the original copy.copy module into believing there's a __copy__ attribute without creating a __copy__ method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell scripting: switching contexts between hybrid Exchange on-prem and online Environment is hybrid Exchange with AD sync and ADFS/SSO.
I have a new user onboarding script that I'm writing that needs to perform commands against our on-prem server to create AD account and enable remote mailbox. It triggers an ADsync, waits 5 minutes, then connects to MSOLservice to provision a licence.
The next step is to set shared mailbox permissions, but when I run get-mailbox it's pulling on-prem mailboxes instead of remote ones.
I've tried unloading the EMS snap-in and AD module, and closing my sessions. As soon as I load get-mailbox it creates a session back to on prem.
Can't pipe get-remotemailbox into get-mailboxpermissions.
Can't use invoke-command to run get-mailbox |get-mailboxpermission | where-object {$_.user -eq "user@domain.com"} (See no-language error here for why)

A: the solution is to use prefixes:
http://www.stevieg.org/2010/11/managing-office-365-on-premises-exchange-2010-powershell-session/
Import-PSSession $o365Session -prefix cloud
get-cloudmailbox |get-cloudmailboxpermission ...


text:
Q: recursive calling to print list of numbers I'm trying to sort an array and print the output recursively until the array is = [0,0,0,0,0] but it only prints [3,2,1,0,0] ,,,,, this is what i wrote can you help to fix this isuee ,, still learning
the answer should be
[4 3 2 1 0 0]
[3 2 1 0 0 0]
[2 1 0 0 0 0]
[1 0 0 0 0 0]
[0 0 0 0 0 0]

numbers=[5,4,3,2,1,1]
numbers.sort()

numbers.sort(reverse=True)

print('List sorted: ', numbers)

def list_arrays(numb):
level=numbers[0]
if len(numbers)-1 < level:
    return 0

else:
        numbers.pop(0);
        print(numbers)
        for i in range(len(numbers)):
            numbers[i] -= 1

        print(numbers)
        #list_arrays(numbers)

if __name__=='__main__':
    list_arrays(numbers)

A: You have a number of problems here.  First, you defined a function, but you never called the function.  That's why nothing printed.
Second, you don't need "sort" immediately followed by "sort(reverse)".
Third, I don't know what you were attempting by checking the level.  That doesn't seem to be related to your problem.
Fourth, you're subtracting 1 from every number, but you should only be subtracting 1 if the number is greater than 0.
Finally, you're only subtracting once.  You need to repeat it until all the numbers are zero.
numbers=[5,4,3,2,1,1]
numbers.sort(reverse=True)

print('List sorted: ', numbers)

def list_arrays(numb):
    while any(numb):
        for i in range(len(numb)):
            if numb[i]:
                numb[i] -= 1
        print(numb)

list_arrays(numbers)

In most cases, rather than modify the list in place, I would suggest creating a new list during each loop, but for this simple assignment, this will work.
To remove the zeros, you really do want to create a new list, not modify in place.
numbers=[5,4,3,2,1,1]
numbers.sort(reverse=True)

print('List sorted: ', numbers)

def list_arrays(numb):
    while numb:
        new = []
        for v in numb:
            if v > 1:
                new.append(v-1)
        numb = new
        print(numb)

list_arrays(numbers)

Or even:
numbers=[5,4,3,2,1,1]
numbers.sort(reverse=True)

print('List sorted: ', numbers)

def list_arrays(numb):
    while numb:
        numb = [v-1 for v in numb if v>1]
        print(numb)

list_arrays(numbers)

A: Maybe this is what you want?
def make_all_zero_and_print(numbers):
    while numbers[0] > 0:
        print(numbers)
        for i in range(len(numbers)):
            if numbers[i] > 0:
                numbers[i] -= 1
    print(numbers)

make_all_zero_and_print([5, 4, 3, 2, 1, 1])

Output:
[5, 4, 3, 2, 1, 1]
[4, 3, 2, 1, 0, 0]
[3, 2, 1, 0, 0, 0]
[2, 1, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]

A: In another comment you asked to remove all zeroes. Perhaps this is the solution you are looking for -
def run(t):
  while(t):
    yield t
    t = [x - 1 for x in t if x > 1]

mylist = [5,4,3,2,1,1]
for t in run(mylist):
  print(t)

[5, 4, 3, 2, 1, 1]
[4, 3, 2, 1]
[3, 2, 1]
[2, 1]
[1]

Or gather all lines in a single array using list -
mylist = [5,4,3,2,1,1]
print(list(run(mylist)))

[
  [5, 4, 3, 2, 1, 1],
  [4, 3, 2, 1],
  [3, 2, 1],
  [2, 1],
  [1]
]


text:
Q: How to display dataset in R without having NA? I am trying to have a quick overview of the dataset variables using this command in R:
str(df, vec.len=1, max.level=1)

But I am getting NA at first:
$ Life.expectancy.at.birth..male..years.  : num  NA NA ...
$ Methane.emissions..kt.of.CO2.equivalent.  : int  NA NA ...
$ Population..total: num  NA NA ...


text:
Q: Creating an initializer list in C How do you create an initializer list in C?  Do you have to use a struct or union?
Because currently I have written code that apparently has a problem with how many initialized variables I have.
Compiling error:
Number of initializers cannot be greater than the number

A: struct S
{
    int a, d, p;
};

#define S_INITIALIZER { 12, 10, 77 }

struct S s = S_INITIALIZER;

You (typically) provide a value for each member. If you provide less, the remaining members are zero-initialized (C99, 6.7.8.21). If you provide more, you will get a compiler warning and the additional initializer values are discarded.
Edit: As Olaf pointed out (thanks!), it is better to use designated initializers:
#define S_INITIALIZER { .a = 12, .d = 10, .p = 77 }

This way, the initializer is robust against changes of the struct associated with:
struct S
{
    int d, a, o, p;
    //        ^ new value; a and d inverted!
};

is still initialized as before, o is initialized to 0 (C99 6.7.8.19). And if you now drop p, you get a compile error – at least with gcc.
Actually, the standard states:

If a designator has the form
     . identifier
  then the current object (defined below) shall have structure or union type and the
  identifier shall be the name of a member of that type.

(C99 6.7.8.7). However, did not find what happens if not doing so.
Similarly:

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

(C99 6.7.8.2), again no word if doing otherwise (providing more elements). Discarding additional elements seems to be legal, not compiling does not seem to be illegal either...


text:
Q: How to run a MySQL query through Node Js Module File I am trying to make a separate file consisting of some functions which will return the result of my MySQL queries.
Here is what I have done so far, I have a file called
db_connection.js
var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "mypassword",
  database: "dbname"
});

con.connect(function(err) {
  if (err) console.log("Couldn't connect to the Database");
  console.log("Connected to the database");
});

exports.result = (myQuery) => {
  con.query(myQuery, function (err, res) {
    if(err) throw err;
    return res;
  })
}

My file from where I am calling contains the following:
const db = require('../db_connection');

console.log(db.result("SELECT * FROM products"));

I can see in the console that the connection is established but instead of returning the array of products it returns undefined


text:
Q: Hadoop and map-reduce on multicore machines I have read a lot about Hadoop and Map-Reduce running on clusters of machines. Does some one know if the Apache distribution can be run on an SMP with several cores. In particular, can multiple Map-Reduce processes be run on the same machine. The scheduler will take care of spreading them across multiple cores. Thanks. - KG

A: Yes. You have multiple map and reduce slots in each machine which are determined by the RAM and CPU (each JVM instance needs 1GB by default so a 8GB machine with 16 cores should still have 7 task slots)
from hadoop wiki

Use the configuration knob: mapred.tasktracker.map.tasks.maximum and
  mapred.tasktracker.reduce.tasks.maximum to control the number of
  maps/reduces spawned simultaneously on a TaskTracker. By default, it
  is set to 2, hence one sees a maximum of 2 maps and 2 reduces at a
  given instance on a TaskTracker.
You can set those on a per-tasktracker basis to accurately reflect
  your hardware (i.e. set those to higher nos. on a beefier tasktracker
  etc.).

A: You can use those lightweight MapReduce frameworks for multicore computers.
For example
LeoTask: A lightweight, productive, and reliable mapreduce framework for multicore computers
https://github.com/mleoking/LeoTask

A: For Apache Hadoop 2.7.3, my experience has been that enabling YARN will also enable multi-core support. Here is a simple guide for enabling YARN on a single node:
https://hadoop.apache.org/docs/r2.7.3/hadoop-project-dist/hadoop-common/SingleCluster.html#YARN_on_a_Single_Node
The default configuration seems to work pretty well. If you want to tune your core usage, then perhaps look into setting 'yarn.scheduler.minimum-allocation-vcores' and 'yarn.scheduler.maximum-allocation-vcores' within yarn-site.xml (https://hadoop.apache.org/docs/r2.7.1/hadoop-yarn/hadoop-yarn-common/yarn-default.xml)
Also, see here for instructions on how to configure a simple Hadoop sandbox with multicore support: https://bitbucket.org/aperezrathke/hadoop-aee


text:
Q: kubernetes cluster fails to start with minikube I was trying out Kubernetes using minikube in a VM host using KVM as VM Driver.But it looks like I cannot use KVM on a vm host as virtualization will not be enabled on a VM host.
 $ egrep -c '(vmx|svm)' /proc/cpuinfo
 0

minikube start is failing with the below error
$ minikube start --vm-driver=kvm
Starting local Kubernetes v1.8.0 cluster...
Starting VM...
Downloading Minikube ISO
140.01 MB / 140.01 MB [============================================]
100.00% 0s
E1108 02:38:25.792900   17062 start.go:150] Error starting host: Error  creating host: Error creating machine: Error in driver during machine creation: virError(Code=8, Domain=44, Message='invalid argument: could not find capabilities for domaintype=kvm ').

Any suggestions how to proceed on a VM host

A: My advice would be to use --vm-driver=none. This will install all minikube binaries in host machine. While not all features are available, it should be enough for doing some testing.

A: Links that would help
Minikube install in Ubuntu vm_VT-X/AMD-v enabling to VM inside another VM
https://github.com/kubernetes/minikube#quickstart

A: See info about enabling nested virtualization: https://fedoraproject.org/wiki/How_to_enable_nested_virtualization_in_KVM

A: open another terminal and check that swap is disabled swapoff -a then it will succeed


text:
Q: How to show/hide DIV on selection of drop down menu I have selection in dropdown menu of 4 items .
I want hide all the DIV initially , unless any option is selected.
And on selection any of the above option I want to display only that DIV.

A: Try using:

$(document).ready(function() {
$(".drop-down-menu").toggle();
    $(".drop-down-menu-button").click(function() {
        $(".drop-down-menu").toggle();
        $(".hide").toggle();
    });
    });

<button class="drop-down-menu-button">Hide The Text And Toggle The Menu</button>

Item 1

Item 2

Item 3

Item 4

Hide Me By Clicking the button


text:
Q: moving a map of unique_ptr into a const map of unique_ptr I understand that the following example works:
#include <memory>
#include <map>

using namespace std;

map<int, unique_ptr<int> > mapCreator () {
  map<int, unique_ptr<int> > smallMap;
  for (int i = 0; i < 10; i++) {
    unique_ptr<int> ptr(new int(10));
    smallMap.insert(make_pair(
      i,
      std::move(ptr)
    ));
  }
  return smallMap;
};

class mapContainer {
 public:
  mapContainer(map<int, unique_ptr<int> > smallMap) {
    std::move(smallMap.begin(), smallMap.end(), std::inserter(smallMap_, smallMap_.begin()));
  }
 private:
  map<int, unique_ptr<int> > smallMap_;
};

int main() {
  mapContainer container(mapCreator());
}

however, what do I do if I want to force smallMap_ to be
const map<int, unique_ptr<int> > smallMap_;

Please help, I have tried all the move combinations I know of.

A: Just do
class mapContainer
{
public:
    mapContainer(map<int, unique_ptr<int> > smallMap) :
        smallMap_(std::move(smallMap))
    {
    }
 private:
    const map<int, unique_ptr<int> > smallMap_;
};

Live example


text:
Q: How to split and set data to listview in android? I have a string in android.
str = |test1:23|st1:4|st2:3|st3:5|test2:25|st1:5|st2:6|st3:7|test3:26|st1:5|st2:2|st3:8|test4:28|st1:8|st2:3|st3:2|test5:29|st1:1|st2:2|st3:2|......

I need to split that string and set each data to listview in android.

I mean for each listitem I should keep the data as

test1:23
st1:4
st2:3
st3:5
---------------------
test2:25
st1:5
st2:6
st3:7
----------------------

Now I will split the string with | symbol using:
 String splitstring = str.split("\\|");

Now splitstring[0] contains test1:23, splitstring[1] contains sty:4. But I need to set first 4 to 1st listitem,the next four to next listitem and so on.
Please suggest me how can achieve that task? Thanks in advance.

A: How about:
    String str = "test1:23|st1:4|st2:3|st3:5|test2:25|st1:5|st2:6|st3:7|test3:26|st1:5|st2:2|st3:8|test4:28|st1:8|st2:3|st3:2|test5:29|st1:1|st2:2|st3:2";
    String[] splitted = str.split("\\|");
    List<String> fourItems = new ArrayList<String>();
    int listItemPosition = 0;
    for (String s : splitted) {
        fourItems.add(s);
        if (fourItems.size()==4) {
            processItems(fourItems, listItemPosition++);
            fourItems.clear();
        }
    }

    private void processItems(List<String> fourItems, int position) {
        // do whatever you want to do with your four strings like
        // assigning it to your list item at position
    }

Of course this is wthout any error handling and the like


text:
Q: Problems with route calculate I use routing v8 api. I create route calculations for:
    avoid[features]=dirtRoad
    transportMode=truck
    vehicle[grossWeight]=39999

I want that car to go by route no 1 near too Fagaras city in Romania.  As I know this is a good route for that kind of car. but your system
leads through routes 104A and 104C.
Additionally, even if I add one or more via with latLng from route no 1, according to v8 response truck should turn back and go again go by routes 104A and 104B.
Could you explain to me, why is that? Why does this route part is seems to be banned by v8?
I added some screenschots with this part of route:

A: Noone answer? I think it's really strange behavior.


text:
Q: how to style fist child in React Native I need to apply marginLeft:4 to all elements except firs one for styles.option , how can i get to style only the first child  in React Native? Is it possible not installing any new packages to the project?
 return (
        <View style={style}>
            <View style={styles.container}>
                {options.map((option) => (
                    <Option
                        checked={option.value === value}
                        key={option.value}
                        label={option.label}
                    />
                ))}
            </View>
        </View>
    );
}

function Option(){
  return (
        <Pressable
            style={[styles.option, checked && styles.checked]}
        >
            <Text>
                {label}
            </Text>
        </Pressable>
    );
}

const styles = StyleSheet.create({
    container: {
        padding: 4,
    },
    option: {
        marginLeft: 4,  //Need to apply this style to all elements except firs one
    },
    "option:first-child": {
        marginLeft: 0, //This does not work
    },

A: Hey here is how you can do it, check answer
 return (
            <View style={style}>
                <View style={styles.container}>
                    {options.map((option,index) => (
                        <Option
                            index={index} // pass index like this
                            checked={option.value === value}
                            key={option.value}
                            label={option.label}
                        />
                    ))}
                </View>
            </View>
        );
    }

    function Option(props={}){
    const {index = 0} = props;
      return (
            <Pressable
                style={[styles.option, checked && styles.checked, {

marginLeft:index ===0? 0: 4 // here is how you do it
}]}
            >
                <Text>
                    {label}
                </Text>
            </Pressable>
        );
    }

    const styles = StyleSheet.create({
        container: {
            padding: 4,
            flexDirection: "row",
            backgroundColor: "gray",
        },
        option: {
            backgroundColor: "red",
            **marginLeft: 4,**  //Need to apply this style to all elements except firs one
            justifyContent: "center",
            alignItems: "center",
        },
        "option:first-child": {
            **marginLeft: 0,** //This does not work
        },


text:
Q: CSS Paged Media: Cannot achieve desired breaking behaviour (break-after, break-before doing nothing) Here's the layout of the relative part of my document:

Header 2

Header 3

Header 4

Header 4

Header 3

Header 4

Header 3

Header 4

Which looks like:

And as for where I'd like page-breaks to be able to happen:

*

*You cannot break between an h2 and the first .subsection;

*You cannot break between an h4 and its .body-text;

*You can break between a .body-text and the h4 following it;

*You can break within a .body-text if it gets too long;

*You can break between a .subsection and another .subsection

Here's what I've tried so far:
/* Borders to show where I do and do not want breaks in the following screenshot */
h2 {
  break-before: auto;   /* ✅ */
  break-after: avoid;   /* ❌ */
  border-top: 1px solid forestgreen !important;
  border-bottom: 1px solid red !important;
}

.subsection:first-of-type {
  break-before: avoid;  /* ❌ */
  break-after: auto;    /* ✅ */
  border-top: 1px solid red !important;
  border-bottom: 1px solid forestgreen !important;
}

h4 {
  break-before: auto;  /* ✅ */
  break-after: avoid;  /* ❌ */
  border-top: 1px solid forestgreen !important;
  border-bottom: 1px solid red !important;
}

.subsection:first-of-type h4 {
  break-before: avoid;  /* ❌ */
  border-top: 1px solid red !important;
}

.body-text {
  break-before: avoid;  /* ❌ */
  break-after: auto;    /* ✅ */
  border-top: 1px solid red !important;
  border-bottom: 1px solid forestgreen !important;
}

This seems to be fairly synonomous with what I've outlined above. However, I see
the following once I go to print:

You can see that, even though I've been explicit with break-*: auto;, there is
still a break between the Course Content Creator h4 and its following
.body-text. What is stopping it from breaking at the green line immediately
preceeding it (after the Web Application Development line)? Surely these two
boxes should be glued together.
The only thing that seems to actually do… anything is using
break-inside: avoid; on the sections:
section {
  break-inside: avoid;
  background-color: rgba(255, 0, 0, 0.25);
}
/* ↓ CSS from above... ↓ */

Clearly, this is not the correct way to go about things, since I very much do
not want to avoid breaks inside of sections. It's just that this is the only
thing that seem to affect how the document is actually printed.

I'm doing this in Chrome, version 83.0.4103.106. Firefox 77.0.1 performs the
same way.
If it makes a difference, The .subsections are actually Vue components, which
are slotted into each section's component. I don't see how this would be the
problem, though, since I've double-checked with Chrome DevTools that even
through all the CSS scoping that happens, every CSS property is applied to the
correct element. In any case, the source code for this project is fully visible
here: github.com/matthew-e-brown/resume.

A: break-inside: avoid on a section does not imply a section can never have a page-break. It implies that it should be avoided if possible.
It also looks like you do want to allow pagebreaks inside the .subsection divs, opposed to inside the section. page-break: avoid on the .subsections is what caused them to go to the next page when they don't fit.
/*prevent page breaking inside section, when a section doesn't fit it will display on the next page */
section {
  break-inside: avoid;
}
/*try not to break between h2 and section*/
h2 + .subsection {
  break-before: avoid;
}

How to think about page-breaks
I think it may be useful to describe how I think about the main page break options. It may help your understanding.
page-break: inside: glues together all the content inside this element. It will try to act as a single block.
break-before: avoid: glues the element before it to the current element so they try to act as a single block.
break-after: avoid: glues the element after it to the current element so they try to act as a single block.

A: After giving up for just about two years and only just now deciding to look into this again, I've found my answer. The problem comes from the fact that my document uses CSS Grid to lay content out side-by-side. As per this answer, the W3 specification for this sort of behaviour is still in the candidate stage.
So, it looks like I was just a little bit ahead of the curve. At the very least, there doesn't seem to be anything wrong with the CSS code itself


text:
Q: Which is faster: to run the same sql query twice or run only once and store the result in arrays? Suppose I have a SQL query that gives me some complex data, and in order to display it properly in HTML, I came up with a method where I run the same (or similar) query twice.
To avoid running the same query twice, I can create a table in memory (max a few hundred lines), using array of arrays or anything like that.
My question is: does Postgresql has some sort of cache for the last operation, where it could be more advantageous to run the exact same query twice, instead of creating an array of arrays?

A: Storing the result in RAM will almost undoubtedly be faster, but will use more RAM. It's a tradeoff.  Even if Postgre does have some last query cache, you will still need to move data over the network in order to access it, which will still be slower than simply going to RAM to get the data.

A: If you are wondering whether postgresql has an equivalent of mysql query cache, the short answer is no. The long answer is that it's available through various means such as pgpool.
However it should be noted that if sufficient memory has been allocated to postgresql it will cache indexes and data in memory and the second time you execute a query it will be much faster than the first time even though the resultset is not being cached by default.
Even if you are saving the resultset in memory it might not be more efficient than fetching it from the database it's hard to say without bench marking.
If you know for a fact that your query is slow and it cannot be optimized with better indexes, and you want to use the result in different http requests, you ought to invest in a caching mechanism like redis or memcached. You will see a big performance boost.


text:
Q: AngularJs envia un OPTIONS por cada petición al backend Estoy haciendo una aplicación web para la tesis usando AngularJs v1.7.2 y Spring Boot y estoy teniendo problemas con los servicios web. Al hacer un llamado POST me hace dos peticiones una por OPTIONS y otra por POST, el problema es que me crea doble en mi base de datos ya que se hacen 2 peticiones idénticas. Ya revisé en mi frontend y no estoy llamando doble. También he probado un par de cosas en el frontend y en el backend y no ha funcionado. La seguridad del backend es con Srping Security que filtra cada petición para comprobar el token de autenticación y luego le pasa la petición a los RestControllers.

//FRONTEND

//contante
app.constant('$backendConection', {
    server_ip: '192.168.1.101',
    port: '8080'
});

//config
//Para poder enviar el token en el header
    jwtOptionsProvider.config({
        tokenGetter: function () {
            return localStorage.getItem('jwt');
        },
        whiteListedDomains: [$backendConection.server_ip]//el dominio que esta esperando al token

    });
    $httpProvider.interceptors.push('jwtInterceptor');

//factory
  function save(data) {
        return $http({
            url: 'http://' + $backendConection.server_ip + ':' + $backendConection.port + '/news',
            method: 'POST',
            data: data,
            skipAuthorization: false //para enviar el token de autenticación
        });
    }

//En el controller

$scope.newss = {};
$scope.newss.title = 'mi titulo';
$scope.newss.text = 'mi texto';
$listNewsService.save($scope.newss).then(function (response) {
  var toast = $mdToast.simple().content('La noticia ha sido creada').position('bottom right');
  $mdToast.show(toast);
   $mdDialog.hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>

//Backend
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthEntryPoint unauthorizedHandler;

    @Bean
    public JwtAuthTokenFilter authenticationJwtTokenFilter() {
        return new JwtAuthTokenFilter();
    }

    //1 Cuanda arranca
    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
     logger.info("configure-> authenticationManagerBuilder finished");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //2 Cuando arranca
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().
                authorizeRequests()
                .antMatchers(HttpMethod.GET,
                        "/",
                       "/*.html",
                        "/favicon.ico",
                        "/assets/**",
                        "/components/**",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js").permitAll()
                .antMatchers("/auth/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

//Controller
@PreAuthorize("hasRole('ADMIN')")
@PostMapping(value = "/news", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity save(@RequestBody News news) {
    if (this.newsService.save(news))
        return new ResponseEntity(HttpStatus.OK);
    else
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
}


text:
Q: Exception creating type for an adapter in a Sharepoint website? I have a website in Sharepoint 2007. I use control adapters, specifically an adapter for the menu and the login control. These two adapters resides in a signed assembly that it is deployed to the bin folder of the website.
The browser
<browser refID="Default">
        <controlAdapters>
            <adapter controlType="System.Web.UI.WebControls.Menu"
             adapterType="NameofEnterprise.SecondName.Adapters.MenuAdapter" />
            <adapter controlType="System.Web.UI.WebControls.Login"
         adapterType="NameofEnterprise.SecondName.Adapters.LoginAdapter" />
        </controlAdapters>
    </browser>

From time to time I get the following exception, just from time to time, let's say once or twice a day:
Unable to create type 'NameofEnterprise.SecondName.Adapters.MenuAdapter'.

Things to take in mind: this happens in the machine I develop, I don't know if there are temporary files that can get the framework crazy. Second, I don't know if the framework perhaps is looking for the class of the Adapter in another assembly, as I have some assemblies that have the same namespaces as this one, that is to say: NameofEnterprise.SecondName.BusinessLayer,NameofEnterprise.SecondName.DataLayer....
Plz could you tell me what can be the problem? Can I be more specific to tell the framework the name of the assembly (in the browser you only write the name of the class and namespace)?
SOLUTION
Finally i have used the 2 advices you have given me. I think that with the first thing is enough, that is to say:
<system.web>
    <compilation>
      <assemblies>
        <add assembly="*<Your assembly name here>*"/>
    </assemblies>
    </compilation>
</system.web>

But i have included two the assembly and public token in the browser:
<browser refID="Default">
    <controlAdapters>
            <adapter controlType="System.Web.UI.WebControls.Menu"
             adapterType="NameofEnterprise.SecondName.Adapters.MenuAdapter", YourAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=YourPublicKeyToken"/>
    </controlAdapters>

A: You should modify your web.config, adding your assembly to the list of assemblies:
<system.web>
    <compilation>
      <assemblies>
        <add assembly="*<Your assembly name here>*"/>
    </assemblies>
    </compilation>
</system.web>

Add the assembly that contains your controls, and the error should disappear.  For future reference, Temp internet files has almost nothing to do with Asp.net errors.  Though you can clear them if it makes you feel better.

A: It's also useful to use the full qualified name when you add the reference to your assembly:
<browser refID="Default">
    <controlAdapters>
            <adapter controlType="System.Web.UI.WebControls.Menu"
             adapterType="NameofEnterprise.SecondName.Adapters.MenuAdapter", YourAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=YourPublicKeyToken"/>
    </controlAdapters>


text:
Q: How to use awk or sed to combine match content from two files I have two file, file1 and file2
I need to search file2 with each line of file1, and put them together in another form once match
my progress:
awk 'FNR==NR{ids[$0]=$0;next}{for(id in ids){if($0 ~ "\\y"id"\\y"){print "- name:"id; print "  version: " ; print}}}' file1 file2

file1:
attr-2.4.48
bzip2-1.0.8
curl-7.71.1
dnsmasq-2.86
dropbear-2022.82
elfutils-0.179
ethtool-5.4

file2:
  url: https://sourceforge.net/projects/lzmautils/files/xz-5.2.5.tar.gz/download
  url: http://download.savannah.nongnu.org/releases/attr/attr-2.4.48.tar.gz
  url: https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz
  url: https://curl.se/download/curl-7.71.1.tar.bz2
  url: https://sourceware.org/elfutils/ftp/0.179/elfutils-0.179.tar.bz2
  url: https://git.kernel.org/pub/scm/network/ethtool/ethtool.git/snapshot/ethtool-5.4.tar.gz

output
- name: attr
  version: 2.4.48
  url: http://download.savannah.nongnu.org/releases/attr/attr-2.4.48.tar.gz
- name: bzip2
  version: 1.0.8
  url: https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz
- name: curl
  version: 7.71.1
  url: https://curl.se/download/curl-7.71.1.tar.bz2
- name: dnsmasq
  version: 2.86
  url:
- name: dropbear
  version: 2022.82
  url:
- name: elfutils
  version: 0.179
  url: https://sourceware.org/elfutils/ftp/0.179/elfutils-0.179.tar.bz2
- name: ethtool
  version: 5.4
  url: https://git.kernel.org/pub/scm/network/ethtool/ethtool.git/snapshot/ethtool-5.4.tar.gz

A: This awk should work for you with 2 different field separators for 2 input files:
awk '
FNR == NR {
   u = $0
   sub(/(\.[a-z][[:alnum:]]*)+(\/[^\/]+)?$/, "")
   a[$NF] = u
   next
}
{
   print "- name:", $1
   print "  version:", $2
   print "  " ($0 in a ? a[$0] : "url:")
}' FS='/' file2 FS='-' file1

Output:
- name: attr
  version: 2.4.48
  url: http://download.savannah.nongnu.org/releases/attr/attr-2.4.48.tar.gz
- name: bzip2
  version: 1.0.8
  url: https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz
- name: curl
  version: 7.71.1
  url: https://curl.se/download/curl-7.71.1.tar.bz2
- name: dnsmasq
  version: 2.86
  url:
- name: dropbear
  version: 2022.82
  url:
- name: elfutils
  version: 0.179
  url: https://sourceware.org/elfutils/ftp/0.179/elfutils-0.179.tar.bz2
- name: ethtool
  version: 5.4
  url: https://git.kernel.org/pub/scm/network/ethtool/ethtool.git/snapshot/ethtool-5.4.tar.gz

A: What you want can be done naturally in a small shell script using cut and grep.
We can use sed instead of the cut and grep combo and get a shell script like this:
cat "file1" | while read prginfo
do
    name="${prginfo%%-*}"
    version="${prginfo##*-}"
    url="$(sed -n "/${prginfo}/ {s/url: //;p}" file2)"
    printf -- "- name: %s\n  version: %s\n  url: %s\n" "$name" "$version" "$url"
done

We loop over the lines of file1 (due to the cat, | and while read).
The name and version parts are parsed from the lines of file1 via shell parameter expansion .
The url is parsed via sed:

*

*-n is used to suppress output from unmatched lines

*/${prginfo}/ is used to match the line and apply the further sed sommands inside the braches:

*

*s/url: //;p} replaces the "url: " and prints the modified line

*we could replace this line with url=$(grep "$prginfo" "$2" | cut -d\  -f2)
This is a bit shorter than first reading and storing the file2. But it might take much longer if those files are large.

A: With your shown samples only, in GNU awk please try following awk code; written and tested in GNU awk should work in any version of it.
awk '
FNR==NR{
  arr1[$1]=$2
  next
}
{
  for(i in arr1){
    if(index($0,i)){
      arr2[i]
      print "- name: " i ORS "  version: " arr1[i] ORS  $0
      break;
    }
  }
}
END{
  for(i in arr1){
    if(!(i in arr2)){
      print "- name: " i ORS "  version: " arr1[i] ORS "  url:"
    }
  }
}
' FS="-" file1 file2

A: sed 'h;s/-/\n  version: /;s/^/- name: /p;g;s/-.*//;s/^/grep /;s/$/ file2/e' file1 | sed 's/^$/  url:/'

*

*use sed to h hold the original fine from file1

*s/-/\n  version: /;s/^/- name:/p print version/name

*g get the original line again

*s/^/grep /;s/$/ file2/e used s///e to create a grep command and execute it

*| sed 's/^$/  url:/' clean up empty lines

Basically looping over the lines of file1 with sed, calling grep with s///e.


text:
Q: Stringgrid with buttons 1st Question:
How do you call the part in stringgrid that is not visible? You need to scroll to see it.
For example:
There are 20 rows in a stringgrid but you can see only 10 at a time. You need to scroll to see other 10. How are the "hidden" ones called?
2nd Question:
I know this is probably not the right way to do it so some pointers would be appreciated.
I have a string grid with 1 fixed row. I add ColorButtons at runtime. So I populate 1 column with buttons.
I use this buttons to "insert/delete" rows. As long as all of the grid is in the "visible" part this works well.
Problem occcurs when I "insert" new rows and move the buttons to the "hidden" part. The last button is then drawn to Cell[0,0]. Other buttons in the "hidden" part are drawn correctly. Any idea why this happens? Should I find a way to manage this problem in the OnDraw method or is there a better (correct) way to do this?
Code:
procedure Tform1.addButton(Grid : TStringGrid; ACol : Integer; ARow : Integer);
var
  bt : TColorButton;
  Rect : TRect;
  index : Integer;
begin
    Rect := Grid.CellRect(ACol,ARow);
    bt := TColorButton.Create(Grid);
    bt.Parent := Grid;
    bt.BackColor := clCream;
    bt.Font.Size := 14;
    bt.Width := 50;
    bt.Top := Rect.Top;
    bt.Left := Rect.Left;
    bt.Caption := '+';
    bt.Name := 'bt'+IntToStr(ARow);
    index := Grid.ComponentCount-1;
    bt :=(Grid.Components[index] as TColorButton);
    Grid.Objects[ACol,ARow] := Grid.Components[index];
    bt.OnMouseUp := Grid.OnMouseUp;
    bt.OnMouseMove := Grid.OnMouseMove;
    bt.Visible := true;
end;

procedure MoveRowPlus(Grid : TStringGrid; Arow : Integer; stRow : Integer);
var
  r, index : Integer;
  bt : TColorButton;
  Rect : TRect;
begin
  Grid.RowCount := Grid.RowCount+stRow;

  for r := Grid.RowCount - 1 downto ARow+stRow do
    begin
      Grid.Rows[r] := Grid.Rows[r-StRow];
    end;

  index := Grid.ComponentCount-1;
  for r := Grid.RowCount - 1 downto ARow+stRow do
    begin
      bt :=(Grid.Components[index] as TColorButton);
      Rect := Grid.CellRect(10,r);
      bt.Top := Rect.Top;
      bt.Left := Rect.Left;
      Grid.Objects[10,r] := Grid.Components[index];
      dec(index);
    end;
      for r := ARow to (ARow +stRow-1) do
        begin
          Grid.Rows[r].Clear;
        end;
end;

procedure MoveRowMinus(Grid : TStringGrid; Arow : Integer; stRow : Integer);
var
  r, index : Integer;
  bt : TColorButton;
  Rect : TRect;
begin

  for r := ARow to Grid.RowCount-stRow-1 do
    begin
      Grid.Rows[r] := Grid.Rows[r+StRow];
    end;

  index := ARow-1;
  for r := ARow to Grid.RowCount-stRow-1 do
    begin
      Rect := Grid.CellRect(10,r);
      bt :=(Grid.Components[index] as TColorButton);
      bt.Top := Rect.Top;
      bt.Left := Rect.Left;
      Grid.Objects[10,r] := Grid.Components[index];
      bt.Visible := true;
      inc(index);
    end;

  for r := Grid.RowCount-stRow to Grid.RowCount-1 do
    begin
      Grid.Rows[r].Clear;
    end;
  Grid.RowCount := Grid.RowCount-stRow;
end;

A: *

*For the visible part there exist the VisibleRowCount and VisibleColCount properties. The TGridAxisDrawInfo record type names the visible part Boundary and all parts together Extent (or vice versa, I never remember). So there is no specific by the VCL declared name for the unvisible part of a string grid. It just is the unvisible part.

*I think you are making a logical error: the buttons are not moved when you scroll the grid. Though it may seem like they move, that is just the result of moving the device context contents due to an internal call to ScrollWindow. The scroll bars in the string grid component are custom added, and do not work like those of e.g. a TScrollBox.
To always show all buttons on the locations where they really are, repaint the string grid in the OnTopLeftChanged event:
procedure TForm1.StringGrid1TopLeftChanged(Sender: TObject);
begin
  StringGrid1.Repaint;
end;

When the row heights of all rows and the height of string grid never change, then it is sufficient to create all buttons only once, and let them stay where they are. This means that every button no longer is "attached" to a row, and storing them in the Objects property has no significance any more. When a button is pressed, simply calculate the intended row index from the position of the button in combination with the TopRow property of the string grid which specifies the index of the first visible scrollable row in the grid.
If the grid can resize, e.g. by anchors, then update the button count in the parent's OnResize event. And if the row count of the string grid may become less then the maximum visible row count, then also update the (visible) button count.
If you want more of an answer, then please update your question and explain how the MoveRowPlus and the MoveRowMinus routines are called due to interaction with the grid and or buttons, because now I do not fully understand what it is that you want.
And about CellRect giving the wrong coordinates: that is because CellRect only works on full (or partial) visible cells. To quote the documentation:

If the indicated cell is not visible, CellRect returns an empty rectangle.

Addition due to OP's comments
I think the following code does what you want. The original row index of every button is stored in the Tag property.
unit Unit1;

interface

uses
  Windows, Classes, Controls, Forms, StdCtrls, Grids;

type
  TForm1 = class(TForm)
    Grid: TStringGrid;
    procedure GridTopLeftChanged(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    FPrevTopRow: Integer;
    procedure CreateGridButtons(ACol: Integer);
    procedure GridButtonClick(Sender: TObject);
    procedure RearrangeGridButtons;
    function GetInsertRowCount(ARow: Integer): Integer;
    function GridButtonToRow(AButton: TButton): Integer;
    procedure MoveGridButtons(ButtonIndex, ARowCount: Integer);
  end;

implementation

{$R *.dfm}

type
  TStringGridAccess = class(TStringGrid);

procedure TForm1.FormCreate(Sender: TObject);
begin
  FPrevTopRow := Grid.TopRow;
  CreateGridButtons(2);
end;

procedure TForm1.CreateGridButtons(ACol: Integer);
var
  R: TRect;
  I: Integer;
  Button: TButton;
begin
  R := Grid.CellRect(ACol, Grid.FixedRows);
  Inc(R.Right, Grid.GridLineWidth);
  Inc(R.Bottom, Grid.GridLineWidth);
  for I := Grid.FixedRows to Grid.RowCount - 1 do
  begin
    Button := TButton.Create(Grid);
    Button.BoundsRect := R;
    Button.Caption := '+';
    Button.Tag := I;
    Button.ControlStyle := [csClickEvents];
    Button.OnClick := GridButtonClick;
    Button.Parent := Grid;
    Grid.Objects[0, I] := Button;
    OffsetRect(R, 0, Grid.DefaultRowHeight + Grid.GridLineWidth);
  end;
end;

procedure TForm1.GridButtonClick(Sender: TObject);
var
  Button: TButton absolute Sender;
  N: Integer;
  I: Integer;
begin
  N := GetInsertRowCount(Button.Tag);
  if Button.Caption = '+' then
  begin
    Button.Caption := '-';
    Grid.RowCount := Grid.RowCount + N;
    for I := 1 to N do
      TStringGridAccess(Grid).MoveRow(Grid.RowCount - 1,
        GridButtonToRow(Button) + 1);
    MoveGridButtons(Button.Tag, N);
  end
  else
  begin
    Button.Caption := '+';
    for I := 1 to N do
      TStringGridAccess(Grid).MoveRow(GridButtonToRow(Button) + 1,
        Grid.RowCount - 1);
    Grid.RowCount := Grid.RowCount - N;
    MoveGridButtons(Button.Tag, -N);
  end;
end;

procedure TForm1.GridTopLeftChanged(Sender: TObject);
begin
  RearrangeGridButtons;
  FPrevTopRow := Grid.TopRow;
end;

procedure TForm1.RearrangeGridButtons;
var
  I: Integer;
  Shift: Integer;
begin
  Shift := (Grid.TopRow - FPrevTopRow) *
    (Grid.DefaultRowHeight + Grid.GridLineWidth);
  for I := 0 to Grid.ControlCount - 1 do
  begin
    Grid.Controls[I].Top := Grid.Controls[I].Top - Shift;
    Grid.Controls[I].Visible := Grid.Controls[I].Top > 0;
  end;
end;

function TForm1.GetInsertRowCount(ARow: Integer): Integer;
begin
  //This function should return the number of rows which is to be inserted
  //below ARow. Note that ARow refers to the original row index, that is:
  //without account for already inserted rows. For now, assume three rows:
  Result := 3;
end;

function TForm1.GridButtonToRow(AButton: TButton): Integer;
begin
  for Result := 0 to Grid.RowCount - 1 do
    if Grid.Objects[0, Result] = AButton then
      Exit;
  Result := -1;
end;

procedure TForm1.MoveGridButtons(ButtonIndex, ARowCount: Integer);
var
  I: Integer;
begin
  for I := 0 to Grid.ControlCount - 1 do
    if Grid.Controls[I].Tag > ButtonIndex then
      Grid.Controls[I].Top := Grid.Controls[I].Top +
        ARowCount * (Grid.DefaultRowHeight + Grid.GridLineWidth);
end;

end.

But may I say that this is also possible without the use of button controls: I suggest drawing fake button controls in the string grid's OnDrawCell event.


text:
Q: How to combine 2 SELECT statements with different returning data-types in 1 query? I have tried using UNION ALL query, but it needs the same returning data-type. In the example below name is TEXT while debits is json it leads to an error with UNION ALL-
So how do I return the combined result of name and debits in one query ?
'''
    (SELECT
    name
    FROM
    mytable
    WHERE grade= % s)
    UNION
    ALL
    (SELECT
    debits
    FROM
    mytable
    WHERE balancesheet= % s)
    ;
    '''

psycopg2.errors.DatatypeMismatch: UNION types text and json cannot be matched .

A: Like you stated correctly, and the error msg instructs: you need compatible types. One way to solve it: convert text to json with to_json():
SELECT to_json(name) AS name_and_debit
FROM   mytable
WHERE  grade = %s

UNION ALL
SELECT debits
FROM   mytable
WHERE  balancesheet = %s
;

Or json to text with a plain cast: debits::text. See:

*

*Postgres data type cast


text:
Q: Filebeat : data path already locked by another beat. Please make sure that multiple beats are not sharing the same data path Looking at the logs in one of the filebeat pods i can see this:
2021-01-04T10:10:52.754Z        DEBUG   [add_cloud_metadata]    add_cloud_metadata/providers.go:129     add_cloud_metadata: fetchMetadata ran for 2.351101ms
2021-01-04T10:10:52.754Z        INFO    [add_cloud_metadata]    add_cloud_metadata/add_cloud_metadata.go:93     add_cloud_metadata: hosting provider type detected as openstack, metadata={"ava
ilability_zone":"us-east-1c","instance":{"id":"i-08f536567bd9945df","name":"ip-10-101-2-178.ec2.internal"},"machine":{"type":"m5.2xlarge"},"provider":"openstack"}
2021-01-04T10:10:52.755Z        DEBUG   [processors]    processors/processor.go:120     Generated new processors: add_cloud_metadata={"availability_zone":"us-east-1c","instance":{"id":"i-08f5
36567bd9945df","name":"ip-10-101-2-178.ec2.internal"},"machine":{"type":"m5.2xlarge"},"provider":"openstack"}, add_docker_metadata=[match_fields=[] match_pids=[process.pid, process.ppid]]
2021-01-04T10:10:52.755Z        INFO    instance/beat.go:392    filebeat stopped.
2021-01-04T10:10:52.755Z        ERROR   instance/beat.go:956    Exiting: data path already locked by another beat. Please make sure that multiple beats are not sharing the same data path (pat
h.data).
Exiting: data path already locked by another beat. Please make sure that multiple beats are not sharing the same data path (path.data).

as you can see the filebeat stopped with an error :
data path already locked by another beat. Please make sure that multiple beats are not sharing the same data path (path.data).

After searching the problem in github/forum i found this :
https://discuss.elastic.co/t/data-path-already-locked-by-another-beat/219852/4
Which looks like my problem,
Im using the default filebeat-kubernetes.yaml , and there is no information in ELK / Filebeats docs on how to add unique paths in the filebeat-kubernetes.yaml
where do i add them and how do i make them unique?
Thanks

A: I had the same problem. It means that your data path (/var/lib/filebeats) are locked by another filebeat instance. So execute sudo systemctl stop filebeat (in my case) to ensure that you don't have running filebeat
and then run filebeat with sudo filebeat -e which prints logs in console
I also tried link, that you shared, but it didn't help me. Here another solutions, may be it would help you: https://discuss.elastic.co/t/data-path-already-locked-by-another-beat/219852/2

A: In addition to @Anton's answer, In one of the scenarios, I had a lock file in the data path. This could be  /var/lib/filebeat/filebeat.lock depending on the configuration. Delete the file and run sudo filebeat -e

A: If you want to run Elastic stack as a service, the solution is just to restart all of the stack in this order:

*

*Elasticsearch

*Kibana

*Logstash

*Filebeat(s)

which is already suggested in this link.


text:
Q: jquery ajax wont return text and or fire alert on error
Possible Duplicate:
Jquery: Return the value of a ajax call to caller function?

In the code below ,
I'm trying to put my ajax call in a function that needs it but makeIt() wont  return "usa from the ajax call ? Or am I going about this all wrong?
var makeIt = function () {
    var getStuff = function () {
        return $.ajax({
          type: "POST",
          url: "my.php",
          data: {
            id: "2"
          },
          success: function (data) {
            data
          }, // data will return string "usa"
          error: function () {
            alert("error");
          }
        });
      };
    return getStuff();
  };
var result = makeIt() //result should = "usa"

A: Just writing data in the success function doesn't achieve anything.
  success: function (data) {
    data
  }

It needs to be something like
  success: function (data) {
     doSomethingWith(data);
  }

A: You're doing it wrong. $.ajax call is anychronous, there is no way for makeIt to return a value obtained by $.ajax call, you can do this instead:
var makeIt = function (callback) {
    $.ajax({
        type: "POST",
        url: "my.php",
        data: { id: "2" },
        success: callback,
        error: function () { alert("error"); }
    });
};

makeIt(function (result) {
    //result should = "usa"
});

That way, you'll have a nice wrapper around $.ajax call, with all the parameters and error handling provided.

A: Define "result var" as global var.
Then add extra function to your project.
var result;

var makeIt = function () {

    var getStuff = function () {

       return $.ajax({
            type: "POST",
            url: "my.php",
            data: { id: "2" },
            success: function (data) { fnResult(data) },
            error: function () { alert("error"); }
        });

    };

function fnResult(data){result = data};


text:
Q: optimize output value using a class and public member Suppose you have a function, and you call it a lot of times, every time the function return a big object. I've optimized the problem using a functor that return void, and store the returning value in a public member:
#include <vector>
const int N = 100;

std::vector<double> fun(const std::vector<double> & v, const int n)
{
    std::vector<double> output = v;
    output[n] *= output[n];
    return output;
}

class F
{
public:
    F() : output(N) {};
    std::vector<double> output;
    void operator()(const std::vector<double> & v, const int n)
 {
     output = v;
     output[n] *= n;
  }
};

int main()
{
    std::vector<double> start(N,10.);
    std::vector<double> end(N);
    double a;

    // first solution
    for (unsigned long int i = 0; i != 10000000; ++i)
      a = fun(start, 2)[3];

    // second solution
    F f;
    for (unsigned long int i = 0; i != 10000000; ++i)
    {
     f(start, 2);
     a = f.output[3];
 }
}

Yes, I can use inline or optimize in an other way this problem, but here I want to stress on this problem: with the functor I declare and construct the output variable output only one time, using the function I do that every time it is called. The second solution is two time faster than the first with g++ -O1 or g++ -O2. What do you think about it, is it an ugly optimization?
Edit:
to clarify my aim. I have to evaluate the function >10M times, but I need the output only few random times. It's important that the input is not changed, in fact I declared it as a const reference. In this example the input is always the same, but in real world the input change and it is function of the previous output of the function.

A: More common scenario is to create object with reserved large enough size outside the function and pass large object to the function by pointer or by reference. You could reuse this object on several calls to your function. Thus you could reduce continual memory allocation.

A: In both cases you are allocating new vector many many times.
What you should do is to pass both input and output objects to your class/function:
void fun(const std::vector<double> & in, const int n, std::vector<double> & out)
{
    out[n] *= in[n];
}

this way you separate your logic from the algorithm. You'll have to create a new std::vector once and pass it to the function as many time as you want. Notice that there's unnecessary no copy/allocation made.
p.s. it's been awhile since I did c++. It may not compile right away.

A: It's not an ugly optimization.  It's actually a fairly decent one.
I would, however, hide output and make an operator[] member to access its members.  Why?  Because you just might be able to perform a lazy evaluation optimization by moving all the math to that function, thus only doing that math when the client requests that value.  Until the user asks for it, why do it if you don't need to?
Edit:
Just checked the standard.  Behavior of the assignment operator is based on insert().  Notes for that function state that an allocation occurs if new size exceeds current capacity.  Of course this does not seem to explicitly disallow an implementation from reallocating even if otherwise...I'm pretty sure you'll find none that do and I'm sure the standard says something about it somewhere else.  Thus you've improved speed by removing allocation calls.
You should still hide the internal vector.  You'll have more chance to change implementation if you use encapsulation.  You could also return a reference (maybe const) to the vector from the function and retain the original syntax.

A: I played with this a bit, and came up with the code below.  I keep thinking there's a better way to do this, but it's escaping me for now.
The key differences:

*

*I'm allergic to public member variables, so I made output private, and put getters around it.

*Having the operator return void isn't necessary for the optimization, so I have it return the value as a const reference so we can preserve return value semantics.

*I took a stab at generalizing the approach into a templated base class, so you can then define derived classes for a particular return type, and not re-define the plumbing.  This assumes the object you want to create takes a one-arg constructor, and the function you want to call takes in one additional argument.  I think you'd have to define other templates if this varies.

Enjoy...
#include <vector>

template<typename T, typename ConstructArg, typename FuncArg>
class ReturnT
{
    public:
        ReturnT(ConstructArg arg): output(arg){}
        virtual ~ReturnT() {}
        const T& operator()(const T& in, FuncArg arg)
        {
            output = in;
            this->doOp(arg);
            return this->getOutput();
        }
        const T& getOutput() const {return output;}
    protected:
        T& getOutput() {return output;}
    private:
        virtual void doOp(FuncArg arg) = 0;

        T output;
};

class F : public ReturnT<std::vector<double>, std::size_t, const int>
{
    public:
        F(std::size_t size) : ReturnT<std::vector<double>, std::size_t, const int>(size) {}
    private:
        virtual void doOp(const int n)
        {
            this->getOutput()[n] *= n;
        }
};

int main()
{
    const int N = 100;
    std::vector<double> start(N,10.);
    double a;

    // second solution
    F f(N);
    for (unsigned long int i = 0; i != 10000000; ++i)
    {
        a = f(start, 2)[3];
    }
}

A: It seems quite strange(I mean the need for optimization at all) - I think that a decent compiler should perform return value optimization in such cases. Maybe all you need is to enable it.


text:
Q: Orbits of Special Linear Group acting on $\mathbb{C}^n$ Letting $SL_n(\mathbb{C})$ act on $\mathbb{C}^n$, what orbits do you get?
Answer: Clearly $A0 = 0$ for all $A \in SL_n(\mathbb{C})$. Also as $A$ is invertible, $A0 = 0 \iff v = 0$, so $0$ forms a singleton orbit.
Now given any two vectors $ v \neq w \in \mathbb{C}^n$, there is a matrix  $A \in SL_n(\mathbb{C})$ such that $Av = w$, so the orbits are $0$ and $\mathbb{C}^n \setminus 0$.
Is this last assertion about there existing an A true, and if so, why (using elementary group theory)

A: Let $v=v_1$ be any nonzero vector in $\mathbb{C}^n \setminus \{0\}$. Complete it to a basis $v_1, v_2, \dots, v_n$ of $\mathbb{C}^n$ and let $A$ be the matrix whose columns are the $v_i$. Then $A$ is invertible and satisfies $Ae_1 = v$. Assuming $n \geq 2$, change the matrix $A$ by replacing any of the $v_i$ with $i \geq 2$ by $((\det{A})^{-1})v_i$. Call the resulting matrix $A'$. Then $A'$ is in $\text{SL}_n{\mathbb{C}}$ and satisfies $A'e_1 = v$. This shows that the induced action of $\text{SL}_n(\mathbb{C})$ on $\mathbb{C}^n \setminus \{0\}$ is transitive (since we have shown that the orbit of $e_1$ is $\mathbb{C}^n \setminus \{0\}$).

A: Note that the assertion is not quite true for $n=1$.
For $n > 1$, though, it is a matter of showing that if you fix the first column of a matrix $A$ to be an arbitrary non-zero vector, then you can complete $A$ to an element of the special linear group. Without lack of generality, suppose the first column is
$$
\begin{bmatrix}
a_{1}\\a_{2}\\ \vdots \\a_{n}
\end{bmatrix},
$$
with $a_{1} \ne 0$. Then take
$$
A =
\begin{bmatrix}
a_{1} & 0 & 0 & \dots & 0\\
a_{2} & a_{1}^{-1} & 0 & \dots & 0\\
a_{3} & 0 & 1& \dots & 0\\
&&& \ddots \\a_{n} & 0 & 0 & \dots & 1\\
\end{bmatrix}
$$


text:
Q: Selenium Java + TestNG integration with TFS I have my selenium code in Java with TestNg framework (used Eclipse as code editor), but now I need to integrate it in TFS. I am very new to TFS but I have seen many ppl told it is possible so if somebody can help me with exact steps from starting it would be really helpful. If some hidden tips and tricks also , any body can suggest for smooth integration please do so. Thanks in advance for your time!!

A: The first thing is setting up your environment, both local and build server. You'd better to make they are some as each other, which could significantly reduce build issue/error.
For your local develop environment, please use Visual Studio Team Explorer Everywhere for Eclipse (VSTS and TFS) which is a plug-in for Eclipse that enables you to work with Team Foundation Server (TFS) and Visual Studio Team Services (VSTS) using both Team Foundation Version Control (TFVC) and Git version control systems.
Since you are new to TFS, suggest you first go through the build and deploy pipeline of JAVA projects with TFS. -- Working with Visual Studio Team Services (VSTS) and Java
About Selenium and test, please take a look at below tutorials:

*

*Testing Java applications with VSTS

*Selenium Java Integration with Team Foundation Server

*Get started with Selenium testing in a CD pipeline


text:
Q: Can you have 2 different islands on the same Switch? In AC: New Horizons, does it work like old animal crossings where there's only one town per system or, since there's the profiles option on the switch, its one town per profile?
Asking because my SO will receive another switch by mail in a week, and she is starting on our old switch... but when Ill start myself on that old switch will I be stuck in her town?

A: You are limited to one island per console. So unless you completely delete everything and start over from the very beginning, you will be playing on the island she created.

A: From what has been said from Nintendo, it's one town per system.
However, each profile can have a different house in the same town.
That allows you and your friends to do local multiplayer.

A: There is the additional problem of "Island Representative" . Whomever logs on first and creates the island is permanently the main character or "Island Rep" and the only character that can move plot along/buy major upgrades, invite new NPC villagers, etc. If that person stops putting time in (on your console), you have to play as them when something important needs to happen.
Alternatively, you can erase HerIsland and start fresh before y'all progress too far. Allow her to play a 2ndary character on your new island while waiting for her console to arrive. FYI, the town folk will mention/gossip about the character a lot make it someone you want to hear about forever/play yourself. Down the line, a 2nd character will give you more storage as you upgrade the 2ndary tent into a house with lots of storage... But while waiting, she should focus on mining resources, including Nook miles to take to her permanent island when her new console arrives.
Another option: If you keep playing HerIsland and do the Nuke after the new Switch arrives, then you can ferry over pocket full, by pocket full of bells, flowers, fruit, saved (unlearned) DIY cards, etc to start her out, and then ferry half of them back to yourself after you nuke and restart. You can move up this timeline if you involve a 3rd party, namely a trustworthy ACNH friend willing to hold all your stuff for a few hours/a day (I hope there aren't many full grown flowers/trees) during the nuke and restart process.
I have never done this. I'd guess DIYs likely get lost permanently. I don't know if things like Nook Miles get nuked too. ...The internet says: Oooh. Yes 100% of the data is erased when rebooting including all characters created (and their data). Total clean slate, like you just bought AcNh. Cash out those NookMiles into NM tickets and export them to another island before you erase the game's data.


text:
Q: Installing xcode in VirtualBox on windows 8 Does anyone know how to get xcode on a windows 8 laptop. I have tried virtualbox and installed mavericks and works fine but for some reason xcode keeps failing to download. I tried upgrading to 10.9.4 as well and it still didn't work

A: Using Virtual Machine, firstly download in your real computer Xcode file and then use this link: http://techsultan.com/share-folder-mac-os-x-windows-7-vmware/
Share your file to access by your Virtual Machine and then install itself.


text:
Q: How do you take a random stringed word and turn each letter into a variable I want to take a random word which is a string and turn that string into a list of variables with each letter being a variable. Then multiply each variable together to get a value. For example
a, b, c, d = 2, 3, 5, 7
word = "bad"
wrd = list(word)

wrd would give me wrd = ('b' , 'a' , 'd')
but what i want is  wrd = (b,a,d) = (3,2,7) so that i can do something along the lines of
value = wrd[0]*wrd[1]*wrd[2]

I also need value = 42 to still be related to "bad"
Thanks

A: Don't generate variable names; use a dictionary instead:
values = {'a': 2, 'b': 3, 'c': 5, 'd': 7}

value = 1
for char in word:
    value *= values[char]

It is much simpler to look up a key in a dictionary than it is to dynamically look up names in your local or global namespace.
Demo:
>>> values = {'a': 2, 'b': 3, 'c': 5, 'd': 7}
>>> word = 'bad'
>>> value = 1
>>> for char in word:
...     value *= values[char]
...
>>> value
42

You can generate an inverse mapping from primes back to letters too:
inverse = {prime: char for char, prime in values.items()}

so that if you calculate the prime factors of the value you can at least reconstruct the characters used for a given value (but not the order).


text:
Q: Server side paging in SQL Server I am a little confused about how SQL server achieves less reads and performance improvements using common table expressions and ROW_NUMBER. Why doesn't the table actualized in the expression have to perform all the reads which a normal query would have to perform to allow the query to order using ROW_NUMBER?

A: The CTE is not (necessarily) "actualized". It's not that it will inevitably copy all rows elsewhere and will perform other operations over the copy (though it may behave so it the optimizer decides it's better).
If we take this simple query:
SELECT  *
FROM    (
        SELECT  *,
                ROW_NUMBER() OVER (ORDER BY id) rn
        FROM    mytable
        ) q
WHERE   rn BETWEEN 101 AND 110

and look at its plan we'll see something like this:
  |--Filter(WHERE:([Expr1003]>=(101) AND [Expr1003]<=(110)))
       |--Top(TOP EXPRESSION:(CASE WHEN (110) IS NULL OR (110)<(0) THEN (0) ELSE (110) END))
            |--Sequence Project(DEFINE:([Expr1003]=row_number))
                 |--Segment
                      |--Clustered Index Scan(OBJECT:([ee].[dbo].[mytable].[PK__mytable__3213E83F29C2D227]), ORDERED FORWARD)

Here, the records are scanned (in id order as the table is clustered on id), assigned the ROW_NUMBER (this is what Sequence Project does) and passed on to TOP which just halts execution when a certain threshold is reached (110 records in our case).
Those 110 records are passed to Filter which only passes the records with rn greater than 100.
The query itself only scans 110 records:
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 1 ms.

(строк обработано: 10)
Table 'mytable'. Scan count 1, logical reads 3, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

in 3 pages.
Now let's see the unpaginated query:
SELECT  *
FROM    mytable
ORDER BY
        id

This one is pretty simple: read everything from the table and spit it out.
  |--Clustered Index Scan(OBJECT:([ee].[dbo].[mytable].[PK__mytable__3213E83F29C2D227]), ORDERED FORWARD)

However, looking easily does not mean done easily. The table is quite large and we need to do many a read to return all records:
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 0 ms.

(строк обработано: 1310720)
Table 'mytable'. Scan count 1, logical reads 2765, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 266 ms,  elapsed time = 11690 ms.

So, in a nutshell, the pagination query just knows when to stop.


text:
Q: jQuery each() results to array to php to database Basically what I am doing is making a sort of invitation system, the user clicks on users and they go into a list,  that all works, I can get the ids of them using each() but I need to pass it through jQuery Ajax to php to send it to the database for notifications. This is basically what I have:
$(".group-video-create").click(function(){
    var url = $(".group-input-url").val();
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var checked_url = url.match(exp,"$1");
    if(checked_url)
    {
        $("#group-input-names li").each(function(){ // This is the relevant code
        var user_id = $(this).attr("id");           // Here too
        });                                         // & here

        if(user_id)
        {

            $.ajax({
                type: "POST",
                //url: "",
                //data: "", //this would be an array of all of the ids, (could be 1, could be 100).
                cache: false,
                success: function(html){
                    ///Once all invitations have been sent to the database it would then load a new div and hide the previous one.
                    }
            });
        }
    }
});

if you want to see what I'm trying to accomplish just go here:
http://www.kithell.com/#/video
usr: PhpFreak@yahoo.com
pass: phpfreaklogin
It's under Group Video. (You should be automatically directed there once logged in)

A: You might be able to use jQuery.serialize to bundle up all of your form data.  Also, jQuery.post is a nice shortcut for doing a POST request with jQuery.ajax.
A rough example might look this:
$.post( '/my-ajax-service.php',
        $('#MyForm').serialize(),
        function(data, txtStatus, jqXHR) {
            //Do stuff
});

A: Here is one possibility
http://jsfiddle.net/nickywaites/9GZ2e/
$(function() {

//I would use jQuery Map to build Array
//http://api.jquery.com/map/
var ids = $("#group-input-names li").map(function() {
    return $(this).attr("id");
}).get(); //Get Required to convert to regular javascript array

console.log(ids);

var invites = {}
invites.users = ids;

//Then use JSON.stringify() to pass array to server
//https://github.com/douglascrockford/JSON-js
if (ids.length > 0) {
    $.ajax({
        type: "POST",
        //url: "",
        data: JSON.stringify(invites),
        cache: false,
        success: function(html) {}
    });
}

});


text:
Q: Exit infinite while loop (python) when user enters "exit", but if users enters a number compare it to 50 i need help with this problem. ask user to enter a number inside an infinite while loop, compare this number to let say 50 (less, greater or equal). but in order to exit this while loop user must enter "exit". i have the following code that is working according to requirement but i want 'exit' (if) statement to be written at the end. doing so definitely causes an error. please feel free for alternative ways.
while True:
x = input('please enter a number to compare or enter "exit" to exit the loop \n')
if x == "exit":
    exit()
elif int(x) > 50:
    print(x, 'is greater than 50')
elif int(x) < 50:
    print(x, 'is less than 50')
else:
    print('the number you entered is 50')

A: Well, what happens if the user types fkljhae? A ValueError is raised. And... hang on! This is raised for any non-int input - "exit" satisfies this criterion.
from sys import exit

while True:
    x = input('please enter a number to compare or enter "exit" to exit the loop \n')
    try:
        if int(x) > 50:
            print(x, 'is greater than 50')
        elif int(x) < 50:
            print(x, 'is less than 50')
        else:
            print('the number you entered is 50')
    except ValueError:
        if x == "exit":
            exit()

This isn't particularly good, though; what if print raises a ValueError? Let's refactor it so that only int(x) is in the try: except: block:
from sys import exit

while True:
    text = input('please enter a number to compare or enter "exit" to exit the loop \n')
    try:
        x = int(text)
    except ValueError:
        if text == "exit":
            exit()
    else:
        if x > 50:
            print(x, 'is greater than 50')
        elif x < 50:
            print(x, 'is less than 50')
        else:
            print('the number you entered is 50')

This is better, though "exit" isn't at the bottom any more.

A: It is because you are trying to parse "exit" which is string to int
You can use try and except.


text:
Q: Sci-fi/time traveller cartoon where a time traveler on a training mission saves a girl from being killed which makes Earth disappear Sci-fi/time traveller cartoon from the early to mid 2000's.
The plot goes like this:
A time traveler was in some sort of training mission. Whilst he was on this mission he witnesses this girl that was going to get killed (I think this was taking part during the French Revolution). He saves the girl but it somehow causes the Earth to just disappear as if it had never existed. After this they go on an journey to find out what happened.
I remember seeing it when I was growing up in Portugal and I think it either aired on Panda or Panda Big.

A: Elements of this sound like plot points from various Valérian comics, and apparently there was a 2007 animated series, Time Jam: Valerian & Laureline, that moved various of the elements around so sounds like a match. From Wikipedia:

The TV series differs from the original comics in that in the TV series Valerian comes from the year 2417 instead of 2720, and meets Laureline in the year 912 instead of 1000. Whereas in the comics Valerian takes Laureline back to his own time without any trouble, in the animated series this results in Earth disappearing from the solar system. The couple settle in the galactic capital Central Point and realize they are possibly the only humans left. They begin a new life as space mercenaries and adventurers, exploring the new space-time continuum while at the same time attempting to rediscover the Earth.


text:
Q: wxPython - Align buttons in an expanding sizer I'm trying to make a dialog that looks similar to the wx.MessageDialog. There's a section at the bottom that coloured different but in my code, the buttons will not cooperate.
The buttons should be aligned right, and the bottom section should expand to colour it grey. There's probably a simple solution, anyone able to see my error?
This is with the sizer set to expand:

This is with the sizer set not to expand:

Here's a working simplified version of the code which demonstrates the issue. The troublesome code is at the bottom, surrounded with "===":
import wx

class TestDialog(wx.Dialog):
    def __init__(self, parent, msg, title):
        wx.Dialog.__init__(self, parent, id=-1, title=title)
        # outer sizer, this is to allow a spot at the bottom for the buttons
        outerSizer = wx.BoxSizer(wx.VERTICAL)

        # Main sizer for the message dialog
        mainSizer = wx.BoxSizer(wx.HORIZONTAL)

        staticIcon = wx.StaticBitmap(self, bitmap=wx.ArtProvider.GetBitmap(wx.ART_INFORMATION), size=(32,32))
        mainSizer.Add(staticIcon, flag=wx.ALL, border=10)

        # Sizer to hold the message and buttons
        controlsSizer = wx.BoxSizer(wx.VERTICAL)

        # Static text field to show the (error/warning) message on the message dialog
        errorText = wx.StaticText(self, -1, msg, wx.DefaultPosition, wx.DefaultSize, 0)
        errorText.Wrap(600)

        # This is a sizer so we can nest it inside the controls sizer. This allows us to use multiple border flags
        errorTextSizer = wx.BoxSizer(wx.HORIZONTAL)
        errorTextSizer.Add(errorText, flag=wx.TOP, border=15)

        # Add the error text to the controls sizer
        controlsSizer.Add(errorTextSizer, flag=wx.RIGHT, border=10)

        # Outer button panel, to get that slighty greyed look
        outerButtonPanel = wx.Panel(self)
        outerButtonPanelSizer = wx.BoxSizer(wx.HORIZONTAL)
        outerButtonPanel.SetSizer(outerButtonPanelSizer)

        # Button for the "yes" option
        btnYes = wx.Button(outerButtonPanel, label='Yes')
        btnYes.Bind(wx.EVT_BUTTON, self.__yes)
        outerButtonPanelSizer.Add(btnYes, flag=wx.ALIGN_RIGHT | wx.ALL, border=15)

        # Button for the "no" option
        btnNo = wx.Button(outerButtonPanel, label='No')
        btnNo.Bind(wx.EVT_BUTTON, self.__no)
        outerButtonPanelSizer.Add(btnNo, flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP | wx.BOTTOM, border=15)

        outerButtonPanel.SetBackgroundColour(wx.Colour(100, 100, 100)) # find decent colour

        # Add all the sizers to each other, finish up
        mainSizer.Add(controlsSizer)
        outerSizer.Add(mainSizer)

        # ====================================================================
        outerSizer.Add(outerButtonPanel, flag=wx.ALIGN_RIGHT | wx.EXPAND)
        # ====================================================================
        #outerSizer.Add(outerButtonPanel, flag=wx.ALIGN_RIGHT)
        # ====================================================================

        # Done layout
        self.SetSizerAndFit(outerSizer)
        self.CenterOnScreen()

    def __yes(self, evt):
        self.EndModal(wx.ID_YES)

    def __no(self, evt):
        self.EndModal(wx.ID_NO)

if __name__ == '__main__':
    app = wx.App()
    dlg = TestDialog(None, "test test test test test test test test test test test test test test test test", "Test Title")
    val = dlg.ShowModal()
    print "Dialog result: " + str(val == wx.ID_YES)
    app.Exit()

A: At last, the solution. wx apparently doesn't approve of multiple horizontal box sizers nested together with a panel at the core. More specifically, it doesn't like it when you attempt to align something as well as set it to expand. From what I can tell, you have to nest multiple panels and vertical box sizers (with a horizontal box sizer for the buttons).
Here's the example above, but working properly. Literally, change
outerButtonPanelSizer = wx.BoxSizer(wx.VERTICAL)

to
outerButtonPanelSizer = wx.BoxSizer(wx.HORIZONTAL)

and the whole thing breaks.
import wx

class TestDialog(wx.Dialog):
    def __init__(self, parent, msg, title):
        wx.Dialog.__init__(self, parent, id=-1, title=title)
        # outer sizer, this is to allow a spot at the bottom for the buttons
        outerSizer = wx.BoxSizer(wx.VERTICAL)

        # Main sizer for the message dialog
        mainSizer = wx.BoxSizer(wx.HORIZONTAL)

        staticIcon = wx.StaticBitmap(self, bitmap=wx.ArtProvider.GetBitmap(wx.ART_INFORMATION), size=(32,32))
        mainSizer.Add(staticIcon, flag=wx.ALL, border=10)

        # Sizer to hold the message and buttons
        controlsSizer = wx.BoxSizer(wx.VERTICAL)

        # Static text field to show the (error/warning) message on the message dialog
        errorText = wx.StaticText(self, -1, msg, wx.DefaultPosition, wx.DefaultSize, 0)
        errorText.Wrap(600)

        # This is a sizer so we can nest it inside the controls sizer. This allows us to use multiple border flags
        errorTextSizer = wx.BoxSizer(wx.HORIZONTAL)
        errorTextSizer.Add(errorText, flag=wx.TOP, border=15)

        # Add the error text to the controls sizer
        controlsSizer.Add(errorTextSizer, flag=wx.RIGHT, border=10)

        # Outer button panel, to get that slighty greyed look
        outerButtonPanel = wx.Panel(self)
        outerButtonPanelSizer = wx.BoxSizer(wx.VERTICAL)
        outerButtonPanel.SetSizer(outerButtonPanelSizer)

        # inner panel for the buttons (this allows us to right align the buttons
        innerButtonPanel = wx.Panel(outerButtonPanel)
        innerButtonPanelSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Button for the "yes" option
        btnYes = wx.Button(innerButtonPanel, label='Yes')
        btnYes.Bind(wx.EVT_BUTTON, self.__yes)
        innerButtonPanelSizer.Add(btnYes, flag=wx.ALL, border=15)

        # Button for the "no" option
        btnNo = wx.Button(innerButtonPanel, label='No')
        btnNo.Bind(wx.EVT_BUTTON, self.__no)
        innerButtonPanelSizer.Add(btnNo, flag=wx.RIGHT | wx.TOP | wx.BOTTOM, border=15)

        # Add the inner button panel to the outer button panel and align it right
        innerButtonPanel.SetSizer(innerButtonPanelSizer)
        outerButtonPanelSizer.Add(innerButtonPanel, flag=wx.ALIGN_RIGHT)

        outerButtonPanel.SetBackgroundColour(wx.Colour(100, 100, 100)) # find decent colour

        # Add all the sizers to each other, finish up
        mainSizer.Add(controlsSizer)
        outerSizer.Add(mainSizer)

        # ====================================================================
        outerSizer.Add(outerButtonPanel, flag=wx.EXPAND)

        # Done layout
        self.SetSizerAndFit(outerSizer)
        self.CenterOnScreen()

    def __yes(self, evt):
        self.EndModal(wx.ID_YES)

    def __no(self, evt):
        self.EndModal(wx.ID_NO)

if __name__ == '__main__':
    app = wx.App()
    dlg = TestDialog(None, "test test test test test test test test test test test test test test test test", "Test Title")
    val = dlg.ShowModal()
    print "Dialog result: " + str(val == wx.ID_YES)
    app.Exit()

A: Could you try putting a spacer to the left of the buttons.
        outerButtonPanelSizer.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )


text:
Q: Convert the string of numbers into comma separated values I want the string of numbers into comma separated values.
I have tried this:
$str = 12345;
$newStr = "'" . str_replace("",",", $str) . "'";
print_r($newStr);

expected output:- 1,2,3,4,5

A: Try this
$str = 12345;
$arr= str_split($str); //will output in array
echo implode(',',$arr); //convert array to string with delimiter


text:
Q: Failed to add reference to 'Microsoft.DiaSymReader.Native.amd64' I have created a nuget package and published to Azure. When I add the package to another project it fails with the following error:

I followed the same process for every other nuget package without issues. Any tips?


text:
Q: How can I write Unit Tests for classes that run until Keyboard Interrupt and don't return anything? I am working on a Python service that monitors a directory in the filesystem. When it sees that a file has been created or moved there, it sends the path of the file into a Kafka queue. I have the service working exactly like I need it to, but my problem is that I am supposed to have at least 90% coverage with unit tests. I am relatively new to Python, and I haven't ever used unit testing in any language before, so I feel really out of my depth. I just can't wrap my head around how I would go about testing these classes.
This is the class that monitors the file system, I'm using the watchdog library.
I added the handler=FileHandler parameter to init because I figured I could use that to pass the class a fake handler I could use for the tests, but that feels like it's unnecessarily complicated.
class FileSystemMonitor:

    def __init__(self, target_path, kafka_queue, handler=FileHandler):
        self.path = target_path
        self.queue = kafka_queue
        self.handler = handler(self.queue)

    def start(self):
        observer = Observer()
        observer.schedule(self.handler, self.path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

def parse_args():
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    queue = sys.argv[2] if len(sys.argv) > 2 else 'default'
    return path, queue

if __name__ == "__main__":
    path, queue = parse_args()
    monitor = FileSystemMonitor(path, queue)
    monitor.start()

This is the class I made which handles the events thrown by the monitor, and passes the path to the Kafka Queue.
class FileHandler(PatternMatchingEventHandler):

    def __init__(self, queue):
        super(FileHandler, self).__init__(ignore_patterns=["*/.DS_Store"], ignore_directories=True)
        self.queue = queue

    def on_any_event(self, event):
        super(FileHandler, self).on_any_event(event)
        #print(event, self.queue)
        result = kafkaProducer.send_msg(self.queue, event.src_path, event.event_type)
        print("Handler:", result)
        return result

I've written some tests for the kafkaProducer class, and I didn't have a very hard time with that, because it actually returns a value that I could test.
FileSystemMonitor runs infinitely and just waits for a keyboard interrupt, and when it does end, it doesn't return anything, so how do I write the unit tests for it?
As for the FileHandler class it depends on events being triggered by the monitor class, so how would I isolate the Handler class to test it?

A: FileSystemMonitor.start is very hard to test since it blocks until an external event happens but the test can't easily make the event happen because of the block. I guess you could do some trick with multithreading or multiprocessing or maybe just a timer, but this would add some indeterminism to your test which I don't like.
A more explicit approach is allow the caller to specify what happens inside the while loop so that an exception can be raised in the test while time.sleep will be called in the production code.
class FileSystemMonitor:
    def __init__(self, target_path, kafka_queue, handler=FileHandler):
        self.path = target_path
        self.queue = kafka_queue
        self.handler = handler(self.queue)

    def start(self, loop_action):
        observer = Observer()
        observer.schedule(self.handler, self.path, recursive=True)
        observer.start()
        try:
            while True:
                loop_action()
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

This is what your test would look like:
def fake_loop_action():
    raise KeyboardInterrupt

def test_FileSystemMonitor():
    # Initialize target_path, kafka_queue and handler here.
    # You might want to use test doubles.
    monitor = FileSystemMonitor(target_path, kafka_queue, handler)
    monitor.start(loop_action=fake_loop_action)

And in the production code you would use time.sleep instead. You can even specify the delay in the call now.
monitor.start(loop_action=lambda: time.sleep(1))


text:
Q: Make FFmpeg output a similar video quality I'm using FFmpeg in my program to cut a video. This is the command my program executed:
ffmpeg -i in.avi -ss 00:00:00.000 -to 00:04:35.000 out.avi

Quality and size of out.avi are MUCH lower than in.avi. How can I tell FFmpeg to keep the quality of the input file? I don't want to use -c copy because then the video will start with black frames.
Here is the output without -c copy (command above) http://pastebin.com/JYYRsFsQ
Here is the output of the command with -c copy ffmpeg -i in.avi -ss 00:00:05.000 -c copy -to 00:04:35.000 out.avi
output with -c copy: http://pastebin.com/wXPhBSYj

A: I use ffmpeg -i inFile -c:v libx264 -preset veryfast -c:a copy -ss starttime -to endtime outFile now. It seems to encode the video in good quality and reasonable size (exactly what you'd expect from libx264).


text:
Q: firebase messaging onCreate not called I'm facing an issue with FirebaseMessaging class.
public class FirebaseService extends FirebaseMessagingService {

    private static final String TAG = FirebaseService.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        GlobalApp.logDebug(TAG, "Firebase Service started");
    }
}

The onCreate is not called.
I don't receive any notifications
I'm using implementation 'com.google.firebase:firebase-messaging:20.2.0'
The google documentation is not clear when that service starts.
This is my manifest :
<service
            android:name=".common.google.FirebaseService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"
            android:directBootAware="true">
            <intent-filter android:priority="-500">
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

Any idea ?
Thanks

A: Thanks to @azizbekian
<service
            android:name=".common.google.FirebaseService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"
            android:directBootAware="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

I just had to remove the android:priority="-500"...
Facepalm..


text:
Q: Retrieve value from img tag I want to get the favoriteid value.

This is what I tried but got back undefined.
console.log(this.childNodes[0]['favoriteid'])

The console.log(this) outputs:

A: Something like this?
See docs!

const img = document.querySelector("img[favoriteid]");
console.log( img.getAttribute("favoriteid") )

or
document.querySelector(".favoriteRow img").getAttribute("favoriteid")

console.log(document.querySelector(".favoriteRow img").getAttribute("favoriteid"));


text:
Q: How do I tell what all packages are in a given repository? A friend came to me with an Ubuntu question I didn't have a quick one-off answer for, so I present it to SF: How can I list all the packages available from a given apt repository? Example, all the packages in the Canonical partners repo.

A: download the Packages file(s) and pipe it/them through something like:

bzcat Packages.bz2 | egrep '^($|Package:|Version:)'

or, if a simple grep isn't good enough, use grep-dctrl to extract the info you need from the downloaded Packages files.

A: Here's an ugly solution, but its advantage is that it allows you to browse the repository using your favorite tools (aptitude, Synaptic, etc):

*

*Make a backup copy of /etc/apt/sources.list;

*Edit the original sources.list and comment out all the repositories except the one you want to browse;

*Run your tool's update function and browse away;

*When done, copy your sources.list.backup over the modified original, and re-run your tool's update function.


text:
Q: Is there a way to macro unit test in kdb+? I have seen a few different unit testing approaches online using qunit and k4unit but I can only get them testing on single functions. I was hoping that I could run a unit test that check the daily checks I execute each day such as, "has the nightjobs ran correctly?", "are the dashboards on the WebUI up?", "did the deploy script run with no errors?". Is there built in kdb+ functionality for these kind of tests or a clean way to adapt the qunit or k4unit unit tests? Or will it require a script written from scratch?
Thanks

A: I don't think a unit test is what you're looking for here. Some kind of reporting mechanism for jobs would be more appropriate. Within your existing jobs you could generate some kind of alert to indicate the job's success/failure. This qmail library may be useful for that.
I'm not sure what kind of system you're using, but AquaQ Analytics' TorQ system has a reporter process which can (amongst other things) email alerts for specific processes.
(Disclaimer: I'm an employee of AquaQ Analytics)


text:
Q: How do we ask about two couples? Let's assume we have two men and two women. They seem like couples.
Can I ask this question?
Are you guys couples? (Are you four couples?)
Or is it grammatically incorrect? And I can only say:
Are you guys a couple?

A: "Are you guys' couples" works. It implies that there are two couples no matter who is with whom.

A: "Are you guys a couple" ( When addressing only two people)
"Are you guys couples"  (when asking more than two people)
I wouldn't go ahead with this, as it may confuse people. How would they know that you're asking them all?
Seems syntactically invalid and abnormal.


text:
Q: Free to wrong pool 2608aa8 not 6d3fe8 at test.pl Following is my code:
sub test_ms {

    my $coderef1 = shift;
    my $coderef2 = shift;

    if (fork() == 0) {
        &$coderef1;
        exit;
    }
    &$coderef2;
}

When I am running this, I am getting the error as

Free to wrong pool 2608aa8 not 6d3fe8 at test.pl

Why am I getting this error?

A: perlfork says

On Windows fork() system call is not available

That's why it's not working as expected for you. Try using Win32::Process::Create.
See:

*

*What is the difference between Windows fork and Unix fork?

*A Great little summary of issues with fork on Windows

*Mr. Peabody Explains fork()

A: That message means a scalar (or array or ...) allocated by one thread (or interpreter?) was freed by another. fork creates threads, not processes on Windows. It's probably because the object in $Excel is not safe to pass between threads. Create $Excel in the thread in which you are going to use it.


text:
Q: Integral $\int (\cot^{2}x+\cot^{4}x)\mathrm{d}x$ I am having difficulties with integrating this function:
$$\int (\cot^{2}x+\cot^{4}x)\mathrm{d}x$$
I separated the function in two and calculated $\int \cot^2x\mathrm{d}x$:
$$\int \cot^2x\mathrm{d}x=\int (-1+1+\cot^2x)\mathrm{d}x=-\int \mathrm{d}x+\int (1+\cot^2x)\mathrm{d}x=-x-\cot x+c$$
But I don't know how to deal with $\int \cot^4x\mathrm{d}x$. I assume that there is a shorter solution somewhere but I'm not sure. In addition, this is a high school level question, I'm only familiar with primitives of simple functions, integration by parts and trigonometric replacement.
Any help would be appreciated, thanks in advance.

Solution
$$\int (\cot^{2}x+\cot^{4}x)\mathrm{d}x=\int \cot^{2}x\cdot(\cot^{2}x+1)\mathrm{d}x=\int (\cot^{2}x\cdot\csc^{2}x)\mathrm{d}x$$
Let's assume $u:=\cot x$
Then $\mathrm{d}u=-\csc^2x\mathrm{d}x$. So we have:
$$\int (\cot^{2}x\cdot\csc^{2}x)\mathrm{d}x=-\int u^2\mathrm{d}u=-\frac{u^3}{3}+c=-\frac{\cot^2x}{3}+c$$
N. S. and MyGlasses, thank you for your help.

A: $$\int (\cot^{2}x+\cot^{4}x)\mathrm{d}x= \int\cot^{2}x\left(1+\cot^{2}x \right)\mathrm{d}x= \int\cot^{2}x\csc^{2}x \mathrm{d}x$$
and use the fact that $(\cot(x))'=-\csc^2(x)$.


text:
Q: Powershell Script To Reindex WSUS DB and email results Hi I am trying to write a PowerShell script that reindexs the WSUS Database and I am stuck.  So far I have a separate config file that holds the email details of the server, and I think I have got the WSUS reindex working.  However I'm stuck getting the data from the sql query. I have used a TechNet article as a starting point.
The code I have so far is:
$configKey = @{}
Get-Content server.ini | ForEach-Object {
$keys = $_ -split "="
$configKey += @{$keys[0]=$keys[1]}
}

cd "c:\Program Files\Microsoft SQL Server\100\Tools\Binn\"
"Invoke-sqlcmd -I -i"c:\scripts\WSUSDBMaintenance.sql" -S "np:\\.\pipe\MSSQL$MICROSOFT##SSEE\sql\query"

#file backup

$body += '<font size="5"  face="Calibri"Windows Server Reindex Report:
'
$body += $Result + "
"
"
 Invoke-Sqlcmd -Query "PRINT 'Number of indexes to rebuild: ' + cast(@@ROWCOUNT as nvarchar(20)';" -Verbose

 $body += "
"

 $subject += $configKey.company
#Send Email
Send-MailMessage -From $configKey.from -To $configKey.to -Subject $subject -Body $Body -BodyAsHtml -Smtpserver $configKey.server

A: a few things jump out at me.

*

*"Invoke-sqlcmd -I -i"c:\scripts\WSUSDBMaintenance.sql" -S "np:\.\pipe\MSSQL$MICROSOFT##SSEE\sql\query"

should probably be
Invoke-sqlcmd -I -i "c:\scripts\WSUSDBMaintenance.sql" -S "np:\.\pipe\MSSQL$MICROSOFT##SSEE\sql\query"

*

*And you have an extraneous double quote here:
$body += $Result + "
"
"<<<<<<<<<<<<<<<<<<<<<<<<<

*Also, are the tools really in a directory called Binn rather than Bin?