text:
Q: crop image directly from byte array I have a byte array, which contains an image... i'd like to save it cropped.
My working method was:
get the byte[]
convert it into a bitmap with BitmapFactory.decodebytearray
make another bitmap from it with createbitmap(sourceBitmap, x1, y1, whileX, whileY)
recycle the first (uncropped one)
save out the second, then recycle that too
the problem is that for a while it exists 2 bitmap, the original and the cropped one, and thats why i cant use this method with larger images (over 3MP)
is there a way to crop image directly from the byte array? I saw that there is a decodeByteArray(dataArray, offset, length, options), but i couldn't make an image from it (the remaining data was not an image)... could someone help maybe?

A: The method decodeByteArray(dataArray, offset, length, options) is not intended to crop an image but to parse an image from a byte buffer that contains more data than the image itself. The typical use of this is to extract images from complex binary data structures that include images among other things.
To my knowledge there is no way to crop an image without creating a new one. To me the best you can do is what you are currently doing.

A: For JPEG (the ubiquitous picture format on mobile devices), it is possible to decode only some specific rectangle. This requires some discipline in writing C code on top of generic software decoder, especially if you want to do it as fast as possible, and waste not extra RAM.
Support in libjpeg-turbo was been added five years after this question had been asked.


text:
Q: Jerky scrolling when adding/removing views to ScrollView's child I hope someone can give an idea on how to improve the performance of the scrolling on my app.
Basically I have tiles/images being generated in a secondary thread, and once they are ready I add them to a RelativeLayout on a specific position with LayoutParams. For now I'm setting the size of this RelativeLayout as fixed to avoid complexities. This RelativeLayout is the one I add to the ScrollView.
I also listen for the scroll change event of the ScrollView, so I am able to request new tiles when I scroll to a new position. When this happens, new tiles are generated on the secondary thread, and at the same time I get the information to remove old tiles that are not necessary anymore (this helps to keep the quantity of tiles to not blow out memory).
But, the main problem here is WHILE scrolling AND adding/removing tiles (using addview() and removeView()) the scrolling is jerky. I have the same app in iOS, using the same approach and the scrolling is perfect.
Here's basically what I have:
// Main activity
RelativeLayout tileCanvas = new RelativeLayout(this);
tileCanvas.setLayoutParams(new LayoutParams(800, 10000));
ScrollView scroll = new ScrollView(this).
scroll.addView(tileCanvas);
setContentView(scroll);

...

private void addTile(TileInfo tileInfo) {
    ImageView image = new ImageView(this.getContext());
    image.setImageBitmap(tileInfo.mBitmap);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(tileInfo.mWidth, tileInfo.mHeight);
    params.leftMargin = tileInfo.mLeft;
    params.topMargin = tileInfo.mTop;
    tileCanvas.addView(image, params);

}

I checked that if I stop calling addTile() after sometime, the scroll works perfectly with the tiles that are currently added in the tileCanvas.

A: I faced the same issues in my project. Why are you using your own filing mechanism with GestureDetector?
ScrollView already handles all of that. Solution i found,
1.Try to reduce the if() conditions and unwanted nesting if() condition in your code.
2.Please write the optimistic code structure is the only way increase the scrollview speed without jerk. But you hesitate the above step,Scrollview are affected.
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parquet Output From Kafka Connect to S3 I see Kafka Connect can write to S3 in Avro or JSON formats. But there is no Parquet support. How hard would this be to add?

A: Starting with Confluent 5.4.0, there is official support for Parquet output to S3.

A: The Qubole connector supports writing out parquet - https://github.com/qubole/streamx

A: Try secor:
https://github.com/pinterest/secor
Can work with AWS S3, google cloud, Azure's blob storage etc.
Note that the solution you choose must have key features like:
Guarantee writing each message exactly once, load distribution, fault tolerance, monitoring, partitioning data etc.
Secor has it all and as stated above, can easily work with other "s3" style services..


text:
Q: Could not extract .bin file I can not extract .bin file on Ubuntu 16.04 LTS.
Error message:
root@ilgar-Ubuntu:~# '/home/ilgar/jre-6u21-linux-i586.bin'
Unpacking...
Checksumming...
Extracting...
/home/ilgar/jre-6u21-linux-i586.bin: 86: /home/ilgar/jre-6u21-linux-i586.bin: ./install.sfx.10336: not found
Failed to extract the files.  Please refer to the Troubleshooting section of
the Installation Instructions on the download page for more information.

Open JDK is installed:
openjdk version "1.8.0_91"

A: This may be because you are using an x64 system. If you are, install the 32 bit libs with:
sudo apt-get install lib32z1

Then try to run the self extraction file again.
Hope that helps.


text:
Q: how to remove spaces, brackets and " from nsarray I have an array where i am trying to remove the access spaces, brackets and " from the nsarray in order to use componentsSeparatedByString:@";"
NSArray *paths = [dic valueForKey:@"PATH"];

    for(NSString *s in paths)
    {
        NSLog(@"String: %@", s);
    }

String: (
"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043"
)

this is the output give as show there are spaces, brackets and " how could i remove them
?
As this line is juz a string inside that array "29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043" this line is a string inside the path array and i try using componentsSeparatedByString:@";" it could not be spilt all there are spaces brackets and " inside.

A: Try stringByTrimmingCharactersInSet:
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@"()  \n\""];
s = [s stringByTrimmingCharactersInSet:charsToTrim];

A: try to use:
s = [s stringByReplacingOccurrencesOfString:@";"
                                     withString:@""];

A: it separates the numbers for you and you can work with them as i.e. NSInteger values.
NSString *_inputString = @"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043";
NSString *_setCommonSeparator = [_inputString stringByReplacingOccurrencesOfString:@";" withString:@","];
NSArray *_separetedNumbers = [_setCommonSeparator componentsSeparatedByString:@","];

for (NSString *_currentNumber in _separetedNumbers) {
    NSInteger _integer = [_currentNumber integerValue];
    NSLog(@"number : %d", _integer);
}


text:
Q: Open Dialogbox with Jquery I am trying to open up a website(Google DialogFlow Chat BOT) in my website using JQuery load function.
My Code is as shown below.
ChatBOT

    $("#configs").ready( function() {
                    $( "div#configs-dialog" ).dialog({
                        autoOpen: false,
                        height: 400,
                        width: 600,
                        modal: true,
                        buttons: {
                            Close: function() {
                                $( this ).dialog( "close" );
                            }
                        }
                    });

                    $('#configs').click(function(){ $('div#configs-dialog').dialog('open'); });

                } );

                $(function(){
                    $("#configs-dialog").load("https://console.dialogflow.com/api-client/demo/embedded/bbdd7d51-741c-4308-82c0-fc70073b057e");
                });

I am not able to load the website into the dialog window.
It opens up a blank dialog box when I click on the link.
Can any one please help me with this?

A: With this sort of element, you cannot use .load() as it will only load the elements and not the JavaScript that is needed.

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

Consider using an iFrame instead.

$(function() {
  $("#configs-dialog").dialog({
    autoOpen: false,
    height: 400,
    width: 600,
    modal: true,
    buttons: [{
      text: "Close",
      class: "ui-state-primary",
      click: function(e) {
        var results = confirm("Are you sure you want to close the ChatBOT?");
        if (results) {
          $(this).dialog("close");
        }
        return false;
      }
    }]
  });

  $('#configs').click(function() {
    $('#configs-dialog').dialog('open');
    $("#configs-dialog")
      .html("")
      .append($("", {
          class: "configs-dialog-frame",
          src: "https://console.dialogflow.com/api-client/demo/embedded/bbdd7d51-741c-4308-82c0-fc70073b057e"
        })
        .css("height", $("#configs-dialog").height() - 5));
  });
});
.ui-dialog .ui-dialog-titlebar {
  display: none;
}

.ui-dialog #configs-dialog.ui-dialog-content {
  padding: 0;
}

.configs-dialog-frame {
  border: 0;
  width: 100%;
  margin: 0;
  padding: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

ChatBOT


text:
Q: Specialize static constexpr data member I have a class to describe some traits of a type.
template<typename T>
struct my_traits
{
    static constexpr int some_trait = 0;

    static constexpr T min() { return std::numeric_limtis<T>::min(); }
    static constexpr T max() { return std::numeric_limits<T>::max(); }
};

I want to specialize my_traits::some_trait but when I try:
template<> constexpr int my_traits<int>::some_trait = 1;

The compiler complains that my_traits::some_trait already has an initializer. Of course I can specialize it by doing:
template<>
struct my_traits<int>
{
    static constexpr int some_trait = 1;

    // min and max
};

but then I have to redefine all the other functions, even though they will be exactly the same.
So how can I specialize my_traits<int>::some_trait without having to repeat min and max?

A: There are several ways to do it. @Piotr Skotnicki and @Niall mentioned initializing through some helper that can be specialized. In general, just restructure your code so that you can specialize some classes or functions, and then use (by composition or inheritance) the specializing parts by parts which you don't need to specialize.
As an example of an alternative to the comments, here is a specializing base:
#include <iostream>
#include <limits>

template<typename T>
struct my_specializing_traits
{
    static constexpr int some_trait = 0;
};

template<>
struct my_specializing_traits<int>
{
    static constexpr int some_trait = 1;
};

Now you can just subclass it into a common part:
template<typename T>
struct my_traits :
    public my_specializing_traits<T>
{
    static constexpr T min() { return std::numeric_limits<T>::min(); }
    static constexpr T max() { return std::numeric_limits<T>::max(); }
};

The following shows it used (it outputs 0 and 1)
int main()
{
    std::cout << my_traits<char>().some_trait << std::endl;
    std::cout << my_traits<int>().some_trait << std::endl;
}


text:
Q: Как вернуть класс ребенка У меня есть общий класс
public class ClassParent {
  public static ClassParent get() {
    return new ClassParent();
  }
}

И есть дочерние классы, к примеру:
public class ClassChild : ClassParent {
  ... code
}

Как сделать так, что бы при вызове:
ClassChild.get();

Возвращался обьект типа ClassChild, а не ClassParent?

A: Нашел самое оптимальное решение моей задачи, если кому то понадобиться то вот пример:
public class ClassParent<T> where T : new() {
    static public T Get() {
        return new T();
    }
}

public class ClassChild : ClassParent<ClassChild> {
  ... Some code
}


text:
Q: How to find points along arc if given initial point, ending point, random point + precision? the precision is the number of points I want for my vector, from 0, the initial point of my arc, to the precision I want minus 1.
Code example in c++:
int precision = 20;
double pointInit[3] = {2,5,2};
double pointRandom[3] = {3,7,1};
double pointInit[3] = {0,-3,1};

std::vector<std::array<double,3>> pointArc;
std::array<double, 3> currentPoint;

// Fill the pointArc vector, from 0 (initial point) to precision -1 (ending point)
for (int i = 0 ; i < precision; i++)
{
    // Find the value of the current point
    // currentPoint[0] = ????;
    // currentPoint[1] = ????;
    // currentPoint[2] = ????;
    pointArc.push_back(currentPoint);
}

EDIT : The arc I'm looking for is a circular arc

A: Use atan2() to find the angles of the endpoints with respect to the center, subtend the angle between them precision - 1 times, and convert the polar coordinates (use one of the endpoints to get the distance from the center) to rectangular form.

A: 1) translate the three points so that P0 comes to the origin
2) consider the vectors P0P1 and P0P2 and form an orthonormal basis by the Gram-Schmidt process (this is easy)
3) in this new basis, the coordinates of the three points are (0, 0, 0), (X1, 0, 0), (X2, Y2, 0), and you have turned the 3D problem to 2D. (Actually X1=d(P0,P1) and X2, Y2 are obtained from the dot and cross products of P0P2 with P0P1 / X1)
The equation of a 2D circle through the origin is
x² + y² = 2Xc.x + 2Yc.y

Plugging the above coordinates, you easily solve the 2x2 system for Xc and Yc.
X1² = 2Xc.X1
X2² + Y2² = 2Xc.X2 + 2Yc.Y2

4) The parametric equation of the circle is
x = Xc + R cos(t)
y = Yc + R sin(t)

where R²=Xc²+Yc².
You can find the angles t0 and t2 corresponding to the endpoints with tan(t) = (y - Yc) / (x - Xc).
5) interpolate on the angle t0.(1-i/n) + t2.i/n, compute the reduced coordinates x, y from the parametric equation and apply the inverse transforms of 2) and 1).


text:
Q: Displaying Flex Object References I have a bit of a memory leak issue in my Flex application, and the short version of my question is: is there any way (in AcitonScript 3) to find all live references to a given object?
What I have is a number of views with presentation models behind each of them (using Swiz). The views of interest are children of a TabNavigator, so when I close the tab, the view is removed from the stage. When the view is removed from the stage, Swiz sets the model reference in the view to null, as it should. I also removeAllChildren() from the view.
However when profiling the application, when I do this and run a GC, neither the view nor the presentation model are freed (though both set their references to each other to null). One model object used by the view (not a presenter, though) IS freed, so it's not completely broken.
I've only just started profiling today (firmly believing in not optimising too early), so I imagine there's some kind of reference floating around somewhere, but I can't see where, and what would be super helpful would be the ability to debug and see a list of objects that reference the target object. Is this at all possible, and if not natively, is there some light-weight way to code this into future apps for debugging purposes?
Cheers.

A: Flash GC uses a mix of ref counting and mark and sweep, so it does detect circular references. It seems rather you're having another reference in you object graph. The most common reason is, that the objects you want disposed still are having event handlers registered on objects that are not disposed. You could try to ensure that handlers are always registered with weak reference. You could also override addEventListener and removeEventListener in all (base) classes, if possible, to look which listeners are registered and whether there are chances for some not to be removed.
Also, you can write destructors for your objects, that for ui components clear graphics and remove all children, and for all objects, removes references to all properties. That way, only your object is kept in RAM, which shouldn't require much memory (a small footprint of 20 B or so, plus 4 B per variable (8 for a Number)).
greetz
back2dos

A: Assuming you are using Flex Builder, you could try the Profiler. In my experience, it's not so good for profiling performance, but it's been of great help for finding memory leaks.
It's not the most intuitive tool and it takes a while to get used to it (I mean, to the point where it actually becomes helpful). But, in my opinion, investing some time to at least learn the basics pays off. There's an enormous difference between just seeing how much memory the player is using globally (what System.totalMemory gives you, a very rough, imprecise and often misleading indicator) and actually track how many instances of each object have been created, how many are still alive and where were they allocated (so you can find the potential leak in the code and actually fix it instead of relying in black magic).
I don't know of any good tutorials for the FB profiler, but maybe this'll help to get you started.
First, launch the profiler. Uncheck performance profiling and check everything else (Enable memory profiling, watch live memory data and generate object allocation stack traces).
When the profiler starts, you'll see stats about the app objects, grouped by class. At this point, you might want to tweak  filters. You'll see a lot of data and it's very easy to be overwhelmed. For now, ignore everything native to flash and flex stuff, if possible, and concentrate on some object that you think it should be collected.
The most important figures are "cumulative instances" and "instances". The first is the total number of instances created so far; the second, the number of said instances that are still alive. So, a good starting point is get your app to the state where the view you suspect that leaks gets created. You should see 1 for "cumulative instances" and "instances".
Now, do whatever you need to do to get to the point where this view should be cleaned up (navigate to other part of the app, etc) and run a GC (there's a button for that in the profiler UI). A crucial point is that you will be checking the app behaviour against your expectations -if that makes sense-. Finding leaks automatically in a garbarge collected environment is close to impossible by definition; otherwise, there would be no leaks. So, keep that in mind: you test against your expectations; you are the one who knows the life cycle of your objects and can say, "at this point this object should have been collected; if it's not, there's something wrong".
Now, if the "instances" count for you view goes down to 0, there's no leak there. If you think the app leaks, try to find other objects that might not have been disposed properly. If the count remains at 1, it means your view is leaked. Now, you'll have to find why and where.
At this point, you should take a "memory snapshot" (the button next to the Force GC button). Open the snapshot, find the object in the grid and double click on it. This will give you a list of all the objects that have a reference to this object. It's actually a tree, and probably each item will contain in turn a number of backreferences and so on. These are the objects that are preventing your view from being collected. In the right panel, also, you will an allocation trace. This will show how the selected object was created (pretty much like a stack trace).
You'll probably see a hugh number of objects there. But your best bet is to concentrate in those that have a longer life cycle than the object you're examining (your view). What I mean is, look for stage, a parent view, etc; objects on which your view depends on rather than objets that depend on your view, if that makes sense. If your view has a button and you added a listener to it, your button will have a ref to your view. In most cases, this is not a problem, since the button depends on the view and once the view is collect, so is the button. So, the idea is that since there are a lot of objects, you should try to stay focused or you will get nowhere. This method is rather heuristic, but in my experience, it works.
Once you find the source of a leak, go back to the source, change the code accordingly (maybe this requires not just changing code but refactoring a bit). Then repeat the process and check whether your change has caused the desired effect. It might take a while, depending on how big or complex is your app and how much you know about it. But if you go step by step, finding and fixing one problem at the time, you'll eventually get rid of the leaks. Or at least the worst and more evident ones. So, while a bit tedious, it pays off (and as a nice aside, you'll eventually understand what a waste of time is in most cases to use weak refs for every single event handler on the face of this earth, nulling out every single variable, etc, etc; it's an enlightening experience ;).
Hope this helps.

A: also a useful heuristics for finding memory leaks: http://www.tikalk.com/flex/solving-memory-leaks-using-flash-builder-4-profiler


text:
Q: Who's the actress in this sci-fi comedy film/TV series (Name of film/TV series unknown) What's the name of the actress in this clip:

Once I know the name of the actress I can look her up on IMDB and work out what the film or TV series is called

A: This is Beth Behrs as 'Aliengirl'. The clip is from the comedy film Route 30, too


text:
Q: Yet another combinations with conditions question I want to efficiently generate pairs of elements from two lists equal to their Cartesian product with some elements omitted. The elements in each list are unique.
The code below does exactly what's needed but I'm looking to optimize it perhaps by replacing the loop.
See the comments in the code for details.
Any advice would be appreciated.
from itertools import product
from pprint import pprint as pp

def pairs(list1, list2):
    """ Return all combinations (x,y) from list1 and list2 except:
          1. Omit combinations (x,y) where x==y """
    tuples = filter(lambda t: t[0] != t[1], product(list1,list2))

    """   2. Include only one of the combinations (x,y) and (y,x) """
    result = []
    for t in tuples:
        if not (t[1], t[0]) in result:
            result.append(t)
    return result

list1 = ['A', 'B', 'C']
list2 = ['A', 'D', 'E']
pp(pairs(list1, list1))  #  Test a list with itself
pp(pairs(list1, list2))  #  Test two lists with some common elements

Output
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[('A', 'D'),
 ('A', 'E'),
 ('B', 'A'),
 ('B', 'D'),
 ('B', 'E'),
 ('C', 'A'),
 ('C', 'D'),
 ('C', 'E')]

A: UPDATE:
There are now four answers including my own answer, pairs3.
The following script checks and benchmarks the solutions.
import timeit
import gc
from itertools import product, combinations, chain
from pprint import pprint as pp

""" This script checks and benchmarks the solutions. """

#  Solution offered by @saquintes
def pairs1(list1, list2):
    return list(set((tuple(sorted(t)) for t in product(list1, list2)
        if t[0] != t[1])))

#  Solution offered by @constantstranger
def pairs2(list1, list2):
    cache = set()
    return [(cache.add((x,y)), (x,y))[-1] for x in list1 for y in list2
            if not (x==y or (y,x) in cache)]

#  My solution
def pairs3(list1, list2):
    res = dict()
    for x,y in product(list1,list2):
        if not (x == y or res.get((y,x))):
            res[(x,y)] = 1
    return list(res.keys())

#  This is the very clever and exceedingly fast
#  solution offered by @Kelly Bundy.
#  (See @Kelly Bundy's post for a version that returns an iterator!)
def pairs4(list1, list2):
    a = {*list1}
    b = {*list2}
    ab = a & b
    return [
        *product(a, b-a),
        *product(a-b, ab),
        *combinations(ab, 2)
    ]

def check(fn, list1, list2):
    """ Prints the output of function fn """
    print('\nFunction', fn.__name__, 'output:')
    res = fn(list1, list2)
    pp(res)

def run_checks(functions):
    """ Passes lists to each function in functions and prints the results """
    for fn in functions:
        print('\n------------------------------------------------\n')
        print('Function:', fn.__name__, '\n')
        print('Combinations of a list with itself:')
        list1 = ['A', 'B', 'C']
        list2 = ['A', 'B', 'C']
        print('list1:', list1)
        print('list2:', list2)
        check(fn, list1, list1)

        print('\nCombinations of Two lists with a common element:')
        list1 = ['A', 'B', 'C']
        list2 = ['A', 'D', 'E']
        print('list1:', list1)
        print('list2:', list2)
        check(fn, list1, list2)

def benchmark(fn, list1, list2, iterations):
    def callit():
        fn(list1, list2)
    gc.collect()
    t = timeit.timeit(callit, number=iterations)
    print('Function', fn.__name__, 'time:', f'{t:.2f} secs')

def run_benchmarks(functions, list1, list2, iterations):
    print('\nRunning', f'{iterations}', 'iterations per run repeated 3 times\n')
    for fn in functions:
        benchmark(fn, list1, list2, iterations)
        benchmark(fn, list1, list2, iterations)
        benchmark(fn, list1, list2, iterations)
        print()

print('\n-------------- Check performance --------------\n')
list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
list2 = [0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
print('list1:', list1)
print('list2:', list2)
run_benchmarks([pairs1, pairs2, pairs3, pairs4], list1, list2, 100000)

print('--------------  Check correctness --------------\n')
run_checks([pairs1, pairs2, pairs3, pairs4])

Output:
-------------- Check performance --------------

list1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
list2: [0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

Running 100000 iterations per run repeated 3 times

Function pairs1 time: 20.61 secs
Function pairs1 time: 20.53 secs
Function pairs1 time: 20.54 secs

Function pairs2 time: 10.69 secs
Function pairs2 time: 10.69 secs
Function pairs2 time: 10.68 secs

Function pairs3 time: 9.87 secs
Function pairs3 time: 9.87 secs
Function pairs3 time: 9.89 secs

Function pairs4 time: 1.44 secs
Function pairs4 time: 1.44 secs
Function pairs4 time: 1.44 secs

--------------  Check correctness --------------

------------------------------------------------

Function: pairs1

Combinations of a list with itself:
list1: ['A', 'B', 'C']
list2: ['A', 'B', 'C']

Function pairs1 output:
[('B', 'C'), ('A', 'C'), ('A', 'B')]

Combinations of Two lists with a common element:
list1: ['A', 'B', 'C']
list2: ['A', 'D', 'E']

Function pairs1 output:
[('C', 'E'),
 ('B', 'D'),
 ('A', 'B'),
 ('A', 'E'),
 ('B', 'E'),
 ('C', 'D'),
 ('A', 'C'),
 ('A', 'D')]

------------------------------------------------

Function: pairs2

Combinations of a list with itself:
list1: ['A', 'B', 'C']
list2: ['A', 'B', 'C']

Function pairs2 output:
[('A', 'B'), ('A', 'C'), ('B', 'C')]

Combinations of Two lists with a common element:
list1: ['A', 'B', 'C']
list2: ['A', 'D', 'E']

Function pairs2 output:
[('A', 'D'),
 ('A', 'E'),
 ('B', 'A'),
 ('B', 'D'),
 ('B', 'E'),
 ('C', 'A'),
 ('C', 'D'),
 ('C', 'E')]

------------------------------------------------

Function: pairs3

Combinations of a list with itself:
list1: ['A', 'B', 'C']
list2: ['A', 'B', 'C']

Function pairs3 output:
[('A', 'B'), ('A', 'C'), ('B', 'C')]

Combinations of Two lists with a common element:
list1: ['A', 'B', 'C']
list2: ['A', 'D', 'E']

Function pairs3 output:
[('A', 'D'),
 ('A', 'E'),
 ('B', 'A'),
 ('B', 'D'),
 ('B', 'E'),
 ('C', 'A'),
 ('C', 'D'),
 ('C', 'E')]

------------------------------------------------

Function: pairs4

Combinations of a list with itself:
list1: ['A', 'B', 'C']
list2: ['A', 'B', 'C']

Function pairs4 output:
[('A', 'C'), ('A', 'B'), ('C', 'B')]

Combinations of Two lists with a common element:
list1: ['A', 'B', 'C']
list2: ['A', 'D', 'E']

Function pairs4 output:
[('A', 'E'),
 ('A', 'D'),
 ('C', 'E'),
 ('C', 'D'),
 ('B', 'E'),
 ('B', 'D'),
 ('C', 'A'),
 ('B', 'A')]

A: About 5-6 times faster than the fastest in your answer's benchmark. I build sets of values that appear in both lists or just one, and combine them appropriately without further filtering.
from itertools import product, combinations

def pairs(list1, list2):
    a = {*list1}
    b = {*list2}
    ab = a & b
    return [
        *product(a, b-a),
        *product(a-b, ab),
        *combinations(ab, 2)
    ]

You could also make it an iterator (because unlike previous solutions, I don't need to store the already produced pairs to filter further ones):
from itertools import product, combinations, chain

def pairs(list1, list2):
    a = {*list1}
    b = {*list2}
    ab = a & b
    return chain(
        product(a, b-a),
        product(a-b, ab),
        combinations(ab, 2)
    )

A: UPDATE:
My original answer (see below) omitted duplicate pairs when there are duplicate values within one or both of the input lists, which is outside the scope of OP's input constraints ("elements in each list are unique").
However, just to address a slightly broader question than OP's, here's an alternative to OP's code that should give equivalent results even if list elements were not unique and still seems to be somewhat faster:
def pairs2(list1, list2):
    res = []
    cache = set()
    for x in list1:
        for y in list2:
            if not (x==y or (y,x) in cache):
                cache.add((x,y))
                res += [(x,y)]
    return res

... or, if you prefer condensed code:
def pairs2(list1, list2):
    cache = set()
    return [(cache.add((x,y)), (x,y))[-1] for x in list1 for y in list2 if not (x==y or (y,x) in cache)]

Benchmarking:
10x performance improvement for input lists of length 20 with 4 duplicates:
list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

list2
[0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

Timeit results:
foo_1 (OP) ran in 0.0013974264999851585 seconds using 1000 iterations
foo_2 (list/set/comprehension) ran in 0.00011681730000418612 seconds using 1000 iterations

44x faster for input lists of length 40 with 8 duplicates:
list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]

list2
[0, 1, 2, 3, 4, 5, 6, 7, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71]

Timeit results:
foo_1 (OP) ran in 0.025825615999929143 seconds using 100 iterations
foo_2 (list/set/comprehension) ran in 0.0005934359997627326 seconds using 100 iterations

Original answer:
Here is alternative code:
def pairs2(list1, list2):
    return list(set((x,y) if x < y else (y,x) for x in list1 for y in list2 if x != y))

NOTE: @Kelly Bundy pointed out in a comment that a set comprehension such as the following is slightly faster than the code above:
def pairs3(list1, list2):
    return {(x,y) if x < y else (y,x) for x in list1 for y in list2 if x != y}

Benchmarking shows:
Timeit results:
foo_1 (OP) ran in 8.308585199993104e-06 seconds using 1000000 iterations
foo_2 (list/set/comprehension) ran in 4.874373900005594e-06 seconds using 1000000 iterations

So it's about 2x as fast for your examples.
Here's another benchmark for lists of length 10 with 2 overlapping values, showing about a 6x improvement:
list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list2
[0, 1, 10, 11, 12, 13, 14, 15, 16, 17]

Timeit results:
foo_1 (OP) ran in 0.0002618508199986536 seconds using 10000 iterations
foo_2 (list/set/comprehension) ran in 4.290239999827463e-05 seconds using 10000 iterations

And one more with lists of length 20 and 4 overlapping values shows performance of 30x:
list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

list2
[0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

Timeit results:
foo_1 (OP) ran in 0.003016028999991249 seconds using 1000 iterations
foo_2 (list/set/comprehension) ran in 0.00018069539999123662 seconds using 1000 iterations

A: This is definitely less code, but you'd have to measure it on some larger lists to see if it's actually any faster.  Using Python's native types tends to be. It also doesn't do an inclusion check which will traverse the list every check.  It relies on the set to get rid of the matches.
def pairs(list1, list2):
    return list(set((tuple(sorted(t)) for t in product(list1, list2) if t[0] != t[1])))

It technically gives you a different output to what you have above because you're sorting (x, y).  You didn't specify which of the two forms you wanted to keep, so if it doesn't matter, then they are technically equivalent.


text:
Q: Could not establish trust relationship for the SSL/TLS secure channel with Invoke-Webrequest from PowerShell When I try to use Invoke-WebRequest on https ,I'm getting some weird error:
"Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
It's My Code:
   [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
    $url = "https://X.X.X.X:4343/officescan/console/html/cgi/cgiChkMasterPwd.exe"
    $r = Invoke-WebRequest $url -SessionVariable office

Any advice for me ??  Thanks a lot.

A: Of course it is an issue with an invalid certificate (autosigned?, expired?)
if using Powershell 7+ simply use the new parameter
Invoke-WebRequest -Uri 'https://trees.com/' -SkipCertificateCheck

if using Powershell 5.1 it is a bit harder:
$code= @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;
        public class TrustAllCertsPolicy : ICertificatePolicy {
            public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) {
                return true;
            }
        }
"@
Add-Type -TypeDefinition $code -Language CSharp
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
Invoke-WebRequest -Uri 'https://trees.com/'

A: You should try this:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
$url = "https://X.X.X.X:4343/officescan/console/html/cgi/cgiChkMasterPwd.exe"
$r = Invoke-WebRequest $url -SessionVariable office

A: You can also try bypassing the PowerShell profile, in case there's something weird in there (my issue).
powershell -noprofile


text:
Q: Submit form and redirect not working EDIT: I should mention the form submits fine manually but with the javascript nothing seems to happen
I'm trying to get a form to autosubmit on page load and then redirect the user. Reason for this is this is part of a PHP page and the data needs to go into my database but then also POST the variables to a 3rd party SMS platform then return to the users dashboard.
My form looks like this:
<html>
   <form action="https://www.example.com" id="myForm" method ="POST">
      <input type="hidden" name="apiKey" value="withheld">
      <input type="hidden" name="message" value="<?php echo $club_name ?> have requested you to play for them this weekend. Please login to your account to see more information and accept.">
       <input type="hidden" name="to" value="<?php echo $to ?>">
       <input type="hidden" name="from" value="withheld">
       <input type="submit" name="submit" id="submit" value="Submit">
   </form>
</html>

This seems to work fine so I assume the Javascript is incorrect which is:
<script>
document.getElementById('myForm').submit();
    window.location.replace("https://www.example.com");
</script>

A: You have to use a different name than
name="submit"
as all name attributes are set as properties on the form,
hence overriding the default "submit" property on the form,
and the default form method "submit()" is gone.
https://developer.mozilla.org/de/docs/Web/API/HTMLFormElement
"Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute)."

A: In your code window.location.replace("https://www.example.com"); line won't make sense because submit() function will try to submit the form and will change the page and then replace function will prevent submitting the form and will redirect the page. The right way to do this via js can be, submit the form via ajax and in the success callback of Ajax run document.getElementById('myForm').submit()


text:
Q: Fedora Spins work on ubuntu or not? I want to run the fedora spins, but on Ubuntu. Ubuntu is way much lighter than the fedora versions, but it is their spin that I am interested in. Is any spin like thing is available on Ubuntu? If not then are fedora spins capable of running on Ubuntu?

A: Fedora spins are absolutely incapable of running on ubuntu, sorry mate :/, what spin do you want exactly ? maybe we can help you find something similar for ubuntu :) ?
Maybie this will help

A: Fedora spins are nothing else than a simple fedora with pre-installed software packages. You can install packages by yourself via Software center or via command line. Once you will have list of your favorite software (spin) it is just about adding some repositories and one install command
how to add app repository you can read here (), mostly used commnad:
sudo add-apt-repository ppa:<repository-name>
sudo apt-get update

Install software packages with
sudo apt-get install application1 application2 ... applicationN

unfortunatelly, I do not know any activity like this going on Ubuntu. Each can be free to install whatever he wants.


text:
Q: add and remove class if radio button is checked I need to add class if second radio button is checked and remove class if radion button is unchecked. It doesn't work when radio button is unchecked.
$(document).ready(function(){
                $('#second').on('change',function(){
                    if ($('#second').attr("checked", "checked")){
                    $(".drag_and_drop").addClass('collapse');
                    } else {
                        $(".drag_and_drop").removeClass('collapse');
                    }
                });
            });

http://jsfiddle.net/7aGEv/34/

A: You need to use
$(document).ready(function(){
    $('input[name="test"]').on('change',function(){
        $(".drag_and_drop").toggleClass('collapse', this.checked && this.id == 'second');
    });
});

Demo: Fiddle

*

*$('#second').attr("checked", "checked") is used to assign the value checked to the checked attibute, not to check whether the checked attribute  == 'checked' for that you need $('#second').attr("checked") == "checked"

*if you register the change event only to second then the change event will not get triggered when you select the first after selecting second. So register the change handler for the group of radio buttons and check whether the second one is checked

*You can use .toggleClass() toggle a class assignment

A: you can try this.
 $(document).ready(function(){
     $('#second').on('change',function(){
        if ($('#second').is("checked")){
           $(".drag_and_drop").addClass('collapse');
        } else {
           $(".drag_and_drop").removeClass('collapse');
       }
    });
 });

A: try this:
   $('input[name="test"]').on('change',function(){
     if ($('#second').is(":checked")){$(".drag_and_drop").addClass('collapse');} else {      $(".drag_and_drop").removeClass('collapse');
   }});

Working Fiddle

A: Change your event selector. try like this:
$(document).ready(function(){

    $('input:[name="test"]').on('change',function(){
                    if ($('#second').attr("checked")){
                       $(".drag_and_drop").addClass('collapse');

                    } else {
                        $(".drag_and_drop").removeClass('collapse');

                    }
                });
       });

demo:


text:
Q: Plotting subsets with different shapes quick question: I have a dataset, which I seperate into a training and a test subset randomly. Then I do some statistical analysis and wanna plot the results together in the same plot, but using different shapes for the two different subsets.
I'm new to ggplot, so my problem is having to supply ggplot with the complete dataset at the beginning. Since I have seperated the data into two sets by random indexing, I can't find the right selection properties for aes()
data=read.csv("...",sep=" ")
data$class = as.factor(data$class - 1)
colnames(data)=c("y","x1","x2")
n = dim(data)[1]
order = sample(n)
test = data[order[1:(n/2)],]
train = data[order[(n/2):n,]
#...
ggplot(train) + geom_point( aes(x =x1, y = x2, color = y))
# this should be done for the whole dataset, kinda like this
# ggplot(data) + geom_point(aes(x=x1, y=x2, color=y, shape=(index is in test and not train)))
# which is obviously not valid

Thanks for your time,
Niklas

A: If we assume that the datasets have the same columns:
# Loading data
data <- structure(list(y = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"), x1 = c(15.6, 11.2, 18.6, 16.8, 21, 15.2, 14.6, 17.6, 14, 16), x2 = c(5.64, 4.38, 5.68, 7.8, 4.32, 6.75, 5.25, 5.05, 5.2, 7.22)), .Names = c("y", "x1", "x2"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), class = "data.frame")
n = dim(data)[1]
order = sample(n)
test = data[order[1:(n/2)],]
train = data[order[(n/2):n,]

test$identifier <- as.factor(1) # mark the test with 1
train$identifier <- as.factor(0) # mark the train with 0

df_out <- rbind(test,train) # combine the dataframes

ggplot(df_out,aes(x = x1,y = x2,color = y, shape = identifier)) + geom_point() # plot the new df

This produces:

A: If you have 2 data sets as in your example, this is an other way of doing it
library(ggplot2)
data = structure(list(y = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"), x1 = c(15.6, 11.2, 18.6, 16.8, 21, 15.2, 14.6, 17.6, 14, 16), x2 = c(5.64, 4.38, 5.68, 7.8, 4.32, 6.75, 5.25, 5.05, 5.2, 7.22)), .Names = c("y", "x1", "x2"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), class = "data.frame")
data = data.frame(data)
n = dim(data)[1]
order = sample(n)
test = data[order[1:(n/2)],]
train = data[order[(n/2):n],]

ggplot(test)+geom_point(aes(y = x1,x=x2))+
  geom_point(data = train, aes(y = x1,x = x2), pch = 10, col = "dargreen")


text:
Q: Jenkins Docker Sidecar with Container Running a daemon command I want to run ZAP as a proxy in my pipeline, and run my selenium tests through the proxy.  Im just using curl in a container in place of selenium for my testing and was able to make this work locally using docker.
In my pipeline, zap starts up, but the pipeline just sits in the zap container after that, never progressing to the second container.  I understand why, Ive launched a process as a daemon, its never going to finish, so the step never finished.  I just dont understand how to accomplish what I need in jenkins.
stage('Run Zap Proxy'){
        docker.image('owasp/zap2docker-weekly').withRun('-p 8090:8090') { c ->
            docker.image('owasp/zap2docker-weekly').inside("-v $WORKSPACE:/zap/wrk:rw") {
                /* Wait until mysql service is up */
                sh """
                   zap.sh -daemon -port 8090 -host 0.0.0.0 -newsession testing -config api.addrs.addr.name=.* -config api.addrs.addr.regex=true -config api.disablekey=true
               """
            }
            docker.image('cfmanteiga/alpine-bash-curl-jq').inside("--link ${c.id}:proxy") {
                sh 'curl -k -x http://proxy:8090 https://my.fqdn.net'
                sh """
                   curl -k -x http://proxy:8090 \
                       -X POST https://my.fqdn.net/api/rest/sessions \
                       -H 'Content-Type: application/json' \
                       -H 'Accept: application/json' \
                       -d '{"username":"username","password":"password"}'
               """
                sh 'sleep 2m'
                sh 'curl -o report.html http://zap/UI/core/other/htmlreport'
                stash includes: 'report.html', name: 'report'
            }
        }
}

I essentially need to start zap with the command im using in the 'inside', and only kill the container when the second containers stages are complete.

A: You could directly pass the zap command in the withRun part:
stage('Run Zap Proxy'){
    docker.image('owasp/zap2docker-weekly').withRun('-p 8090:8090 -v $WORKSPACE:/zap/wrk:rw', 'zap.sh -daemon -port 8090 -host 0.0.0.0 -newsession testing -config api.addrs.addr.name=.* -config api.addrs.addr.regex=true -config api.disablekey=true') { c ->
        docker.image('cfmanteiga/alpine-bash-curl-jq').inside("--link ${c.id}:proxy") {
            sh 'curl -k -x http://proxy:8090 https://my.fqdn.net'
            sh """
               curl -k -x http://proxy:8090 \
                   -X POST https://my.fqdn.net/api/rest/sessions \
                   -H 'Content-Type: application/json' \
                   -H 'Accept: application/json' \
                   -d '{"username":"username","password":"password"}'
           """
            sh 'sleep 2m'
            sh 'curl -o report.html http://zap/UI/core/other/htmlreport'
            stash includes: 'report.html', name: 'report'
        }
    }
}

withRun allows you to overwrite the CMD of the zap-container. Check this API-documentation.


text:
Q: How to get transactions invoked by smart contract from blockchain I want to get all receipt records of some address (address A) from blockchain. I use web3.eth.getBlock and web3.eth.getTransaction to get all transactions related to A.
But I find if ethers are transfered to address A by invoking 'A.send' or 'A.transfer' function in contract, I can only get a contract call transaction which from caller address to contract address. And I can't find relationship between this transaction and address A.
Is there any way to get transactions invoked by contract for A?
Thanks.

A: Short answer: listen to events instead of monitoring transactions.
Why can't I find the transactions "invoked by" the contract?
A contract does not invoke/create its own transaction (it doesn't have a private key to sign one). A contract can call other contracts during its own execution, as you've seen, but those calls are all executed as part of the same transaction.
The recommended way to discover executed function calls is to use events. If the contract you want to watch does not specify an event on the call you want to watch, you may be in for some heavy lifting: tracing every transaction's execution at the EVM level (something that big block explorers do to generate some of the extra info they provide).
If you are stuck tracing: you can find more about using ethereumjs-vm or geth's debug_traceTransaction on this Ethereum StackExchange Question about internal transactions.


text:
Q: if CPT content is empty then I need to be able to do something if the content is empty in a CPT. This works for standard WP posts using the following:
if($post->post_content=="") {

//Do something if there is content is empty

} else {

//Do something if there is content is NOT empty

}

How can I amend this to refer to a CPT as well as a standard post?
Can someone point me in the right direction?


text:
Q: qInstallMsgHandler error while registering log function in Qt I am designing Qt log window, So I am using qInstallMsgHandler() function to log all the debug, critical & warning messages on to QTableWidget (in below code I have not implemented yet). I did as below
int main(int argc, char *argv[])
{
    qInstallMsgHandler(MainWindow::logMessage);
    //qInstallMsgHandler(&MainWindow::logMessage);  //I tried this also

    QApplication a(argc, argv);
    MainWindow w;
    qDebug()    << "info message";
    qWarning()  << "warning message";
    qCritical() << "critical message";
    w.show();

    return a.exec();
}

MainWindow:
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::logMessage(QtMsgType type, const char *msg)
{
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s\n", msg);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s\n", msg);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s\n", msg);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s\n", msg);
        abort();
    }
}

When I compile this code, I am getting below error
main.cpp:27: error: cannot convert 'void (MainWindow::*)(QtMsgType, const char*)' to 'QtMsgHandler {aka void (*)(QtMsgType, const char*)}' for argument '1' to 'void (* qInstallMsgHandler(QtMsgHandler))(QtMsgType, const char*)'
     qInstallMsgHandler(MainWindow::logMessage);

Please let me know if any one had faced this issue.
Note : If I changed void MainWindow::logMessage(QtMsgType type, const char *msg); this function to static function this is working fine.
(But if this function is static, I can not create QTableWidgetItem and add them to tableWidget so I want this function to be non static).
I am using Qt4.8.6 on Windows7
Thanks In Advance.

A: Define a static variable MainWindow in MainWindow which will allow you to access the instance of the MainWindow from a static function e.g.
static MainWindow *_this;

set this Variable in the constructor:
MainWindow::MainWindow()
{
   _this = this;
}

create a static function with the same signature to be registered in qInstallMsgHandler. This function will do only the redirection to the not-static function using the static _this:
static void logMessageHandle(QtMsgType type, const char *msg)
{
   if(_this)
      _this->logMessage(type,msg);
}

Hope this helps.


text:
Q: NullWritable in the context.write() method How can i put only value in my context.write() method.I don't want to write key in my text file so I don't want to emit Key in my context.write() method.
Here is my mapper code:
public class MyMapper extends TableMapper<Text, IntWritable> {
    private final IntWritable ONE = new IntWritable(1);
    private Text text = new Text();
    public void map(ImmutableBytesWritable row, Result value, Context context)
        throws IOException, InterruptedException {
String FundamentalSeriesId = new String(value.getValue(Bytes.toBytes("cf"), Bytes.toBytes("FundamentalSeriesId")));
text.set(FundamentalSeriesId+"|^|"+FundamentalSeriesId_objectTypeId+"|^|"+FundamentalSeriesId_objectType+"|^|"+financialPeriodEndDate+"|^|"+financialPeriodType+"|^|"+LineItemId+"|^|"+analyticItemInstanceKey+"|^|"+AnalyticValue+"|^|"+AnalyticConceptCode+"|^|"+AnalyticValue_currencyId+"|^|"+AnalyticIsEstimated+"|^|"+AnalyticAuditabilityEquation+"|^|"+FinancialPeriodTypeId+""+AnalyticConceptId+"|^|"+AnalyticLineItem_isYearToDate+"|^|"+IsAnnual+"|^|"+FFAction+"|!|");

    context.write(text, ONE);
    }
}

Reducer code:
public class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

    public void reduce(Text key, Iterable<IntWritable> values, Context context)
        throws IOException, InterruptedException {
    int i = 0;
    for (IntWritable val : values) {
        i += val.get();
    }
    context.write(key, new IntWritable(i));
    }
}

A: Try to write NullWritable.get() as Key and specify NullWritable as datatype from mapper to reducer,
i.e
Reducer Definition,
MyReducer extends Reducer<Text, IntWritable, NullWritable, IntWritable>
Reducer Emission
context.write(NullWritable.get(), value);


text:
Q: ArgumentException "parameter is incorrect" I'm trying to make a code that converts memorystream to a png image, but I'm getting a ArgumentException "parameter is incorrect" error on using(Image img = Image.FromStream(ms)). It doesn't specify it any further so I don't know why I'm getting the error and what am I supposed to do to it.
Also, how do I use the Width parameter with img.Save(filename + ".png", ImageFormat.Png);? I know I can add parameters and it recognizes "Width", but I have no idea how it should be formatted so visual studio would accept it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        MemoryStream ms = new MemoryStream();
        public string filename;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFile();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ConvertFile();
        }

        private void OpenFile()
        {
            OpenFileDialog d = new OpenFileDialog();

            if(d.ShowDialog() == DialogResult.OK)
            {
                filename = d.FileName;
                var fs = d.OpenFile();
                fs.CopyTo(ms);
            }
        }

        private void ConvertFile()
        {
            using(Image img = Image.FromStream(ms))
            {
                img.Save(filename + ".png", ImageFormat.Png);
            }
        }
    }
}

A: I suspect the problem is with how you're reading the file here:
fs.CopyTo(ms);

You're copying the content of the file into the MemoryStream, but then leaving the MemoryStream positioned at the end of the data rather than the start. You can fix that by adding:
// "Rewind" the memory stream after copying data into it, so it's ready to read.
ms.Position = 0;

You should consider what happens if you click on the buttons multiple times though... and I'd strongly advise you to use a using directive for your FileStream, as currently you're leaving it open.


text:
Q: How to use the value of an html element in Ruby embedded code I have the following code:
<% @groups.each do |group| %>

   <%= group.id %>
   <%= group.title %>

<% end %>

       <%= @groups.find(3).title %> |
       Close it

When I click on the <%= group.title %> link in the browser I want to get the value stored in  and pass it on at <%= @group.find(3).title %> where 3 is...so instead of 3 i would have the value stored in
How do I achieve this?

A: You can't directly pass a value obtained from javascript (via click event) to Ruby code, because when the javascript code is run, Ruby has already finished its job, and handed the html/js content to the browser. The browser cannot call a Ruby function, it can only make a new request to a Ruby script on the server (e.g., via ajax).
Now, I looked at your code again, and it seems you already have all titles on your HTML, so you could try this:

<% @groups.each do |group| %>

      <%= group.id %>
      <%= group.title %>

<% end %>

         |  Close it

Note: you need jQuery for this example to work.


text:
Q: Compact subspace of $\mathbb{R}$ with lower limit topology must be countable.
Any compact subset of  $\mathbb{R}_{l} $ must be a countable set.

Consider the open cover $\{[n,n+1): n \in \Bbb Z\}$ of $\Bbb R $ which has no subcover. So $\Bbb R $  is not compact with respect to lower limit (or Sorgenfrey) topology.
But how to answer this question?

A: HINT: Supppose that $X\subseteq\Bbb R_\ell$ is uncountable; you want to show that $X$ is not compact. Show that there are an $x\in X$ and a strictly increasing sequence $\langle x_n:n\in\Bbb N\rangle$ in $X$ that converges to $x$ in the usual topology. Then consider a countable open cover of $X$ that includes sets of the form $[x_n,x_{n+1})$, among others.
Added: Let $A$ be the set of points of $X$ that are not the limit of a strictly increasing sequence in $X$.

*

*Show that for each $x\in A$ there is an $\epsilon_x>0$ such that $(x-\epsilon_x,x)\cap X=\varnothing$.

*Explain why $\{(x-\epsilon_x,x):x\in A\}$ is a pairwise disjoint family of non-empty open intervals.

*Deduce that $A$ is countable and hence that $X\setminus A\ne\varnothing$.


text:
Q: boost filesystem get permissions returns (509)dec == (1FD)hex. This value is not in the documentation Reading here boost filesystem. The value of 509 does not exist.
The code that is doing this is:
boost::filesystem::path closest_existing_path = log_dir;

do {
  closest_existing_path = log_dir.parent_path();

} while (!boost::filesystem::exists(closest_existing_path) &&
    closest_existing_path != boost::filesystem::path(""));

std::cout << "Closest existing path --" << closest_existing_path <<
  "-- permissions = " <<
  boost::filesystem::status(closest_existing_path).permissions() <<
  std::endl;

The directory being passed in for sure exists.
The sample output is:

./logger_tester && cat results.txt
  Closest existing path
  --"/usr"-- permissions = 493
  Closest existing path
  --"/home/mehoggan/Devel/RuleSimulator/src/utils/util_tests"-- permissions = 509

A: May I do the math for you:
1FD hex = 111 111 101 bin = 0775 oct = rwxrwxr-x (user & group can read, write and execute; others can read and execute)


text:
Q: Does completing a normed space commute with taking quotients? Let $X$ be a normed vector space and $Y \subset X$ a closed subspace. We consider the quotient $X / Y$ and equip it with the quotient norm. Then we may form the completion $\overline{X / Y}$.
We compare $\overline{X / Y}$ to the following space: denote by $\overline{X}$ the completion of $X$ and by $\overline{Y} \subset \overline{X}$ the closure of $Y \subset \overline{X}$. Now we form the quotient $\overline{X} / \overline{Y}$ with the quotient norm.

Are $\overline{X / Y}$ and $\overline{X} / \overline{Y}$ (naturally) isomorphic, i.e., is there a linear, bijective isometry between them?

A: Yes. We have the canonical map $\varphi = \overline{\pi} \circ \iota \colon X \to \overline{X}/\overline{Y}$ which factors through $X/Y$, and the induced map $\overline{\varphi} \colon X/Y\to \overline{X}/\overline{Y}$ is an isometry, since for every $\xi \in \overline{X}$ we have $\operatorname{dist}(\xi,Y) = \operatorname{dist}(\xi,\overline{Y})$. In particular, for $\xi \in X$, we have
$$\lVert\pi(\xi)\rVert_{X/Y} = \operatorname{dist}(\xi,Y) = \operatorname{dist}(\xi,\overline{Y}) = \lVert \overline{\pi}(\iota(\xi))\rVert_{\overline{X}/\overline{Y}} = \lVert \overline{\varphi}(\pi(\xi))\rVert_{\overline{X}/\overline{Y}}.$$
Since $X$ is dense in $\overline{X}$, the image of $\overline{\varphi}$ is dense:
$$\overline{\overline{\varphi}(X/Y)} = \overline{\varphi(X)} = \overline{\pi(\iota(X))}\supset \pi\left(\overline{\iota(X)}\right) = \pi\left(\overline{X}\right) = \overline{X}/\overline{Y}.$$
The isometry $\overline{\varphi}$ extends to an isometry $\tilde{\varphi}\colon \overline{X/Y} \to \overline{X}/\overline{Y}$. Since $\tilde{\varphi}$ is an isometry, $\tilde{\varphi}\left(\overline{X/Y}\right)$ is a complete subspace of $\overline{X}/\overline{Y}$, hence closed, and since it contains $\overline{\varphi}(X/Y)$, it is a dense subspace. A closed dense subspace must be the entire space, so $\tilde{\varphi}$ is a bijection.


text:
Q: How to calculate transmission delay at the application layer? I am trying to model delay in a P2P overlay simulation and would like to clear some uncertainty with regards to the calculation of transmission delay as I haven't found any similar scenarios to mine.
I am considering only the application layer hence messages are not split according to maximum packet sizes or IP datagram sizes and no protocol overhead is assumed. Also, no interpacket or inter-message delay is considered.
Let's assume that there is a scenario where a server is serving two clients: client 1 and 2.
Server receive speed = 500 Mbps
Server transmit speed = 100 Mbps
Client 1 receive speed = 50 Mbps
Client 1 transmit speed = 20 Mbps
Client 2 receive speed = 300 Mbps
Client 2 transmit speed = 200 Mbps
The server needs to send 2 messages to client 1 and two other messages to client 2. All the messages are ready to be transmitted by the server.
Messages 1 and 2 to be transmitted to client 1 have sizes of 20 Mb and 33 Mb respectively. Messages 3 and 4 to be transmitted to client 2 have sizes of 10 Mb and 15 Mb respectively.
Transmission delay = Number of bits/transmission rate
a) If the server wants to send both messages to client 1 at the same time, will the number of bits be 20+33 = 53 Mb and the transmission rate be 50 Mbps?
b) If the server wants to send both messages to client 2 at the same time, will the number of bits be 10+15 = 25Mb and the transmission rate be 100 Mbps?
c) If the server wants to send messages to client 1 and client 2 at the same time, will the total transmission delay be 53/50 + 25/100-50?
d) If the question is the same as c) but this time client 2 has a download speed of 30 Mbps, would the total transmission delay be 53/50 + 25/30?
For c), I wrote 100-50 because 50 Mbps are used by the server to transmit the messages to client 1 which results in the server only having 50 Mbps of available transmit speed for client 2.

A: Let's assume all three devices are connected to the same fixed-speed medium that exceeds any one device's maximum Tx or Rx rate. For example, a Gigabit Ethernet switch.
Your calculations for (a) and (b) look correct to me.
Unfortunately your calculation for (c) looks wrong to me. You shouldn't be adding the two terms, you should be taking the maximum of the two terms. If the server can send 100Mbps and Client 1 can only consume half of that, then the server will be sending to Client 1 at 50Mbps at the same time as it's sending to Client 2 at (the leftover) 50Mbps. Since Client 2 is only receiving 25Mbits of total data, the transmission from Server to Client 2 will be over long before the transmission from Server to Client 1 is over. So the total delay is just Client 1's 53/50.
Your item (d) contains the same logic error as (c). Once again, the transmission to Client 2 will be done before the transmission to Client 1, so the total delay is just Client 1's 53/50.


text:
Q: How to open device calendar from flutter app? I want to open the local calendar by click on a button from flutter app in IOS and Android platform, with initial parameters such as title, description and date.
In fact, I need open 'Add Event' of the calendar, directly from my app.
I've tried some packages like device_calendar, but it needs to implementation own design for add and edit event form.
It is possible to open new event form of device calendar directly?


text:
Q: Reuse XML Elements to make list? On S1000D, how can I lasso or retrieve all <acronym id="acr-0001"> elements (with contained acronym text data) and make a table list out of them in a data module I'm calling "List of Acronyms"?
In other words, I want to reuse XML elements to make a list out of them.  What S1000D XML code do I setup in "List of Acronyms" data module so that it automatically generates a list of acronym data that is retrieved from numerous data modules once I run it through the Publisher application?

A: you can use notepad++ and regex formula (or search&replace), like
search in all file

and in the result, you can find what are the other tag before and after <acronym___>, like . So you can write in the search window
.<acronym id="acr-\d\d\d\d.
with a care not to valid the search on multiple line
for S&R use this formulas
[]<acronym[]
and you can get the result in a specic file


text:
Q: How to connect two differents nodes types (structures) using pointers? I've been trying to figure out how to connect two different struct nodes using pointers. But I'm was not able to do that. See my draw bellow. At left I
have a "treeNode" with two pointers (below and right). The r-pointer connect to a different node called "branchNode" and for each "treeNode" I have five linked  "branchNodes".
Here is my problem: For example, if the "branchNode" 1
doesn't exist, I wound like to create a temporary node
to insert it. But I don't know how to make this temporary node
receive the memory address of the "branchNode" 2.
see image here
\nSee my code bellow:

main.cpp

#include "table.h"
#include <iostream>

int main(){

    Table xxx;

    xxx.addTreeNodes(2,100);
    xxx.addTreeNodes(3,100);
    xxx.addTreeNodes(1,100);

    return 0;

table.h

#ifndef TABLE_H_
#define TABLE_H_

class Table{
public:
    Table();
    int treeAddress(int newAddress, int dim);
    void addTreeNodes(int pos, int value);

private:
    struct treeNode {
    public: class branchNode;
        int address;
        treeNode* right;
        treeNode* below;
    };

    struct branchNode : public treeNode{
        int address;
        int data;
        branchNode* next;
    };

    treeNode* treeCurr;
    treeNode* treeTemp;
    treeNode* head;
    branchNode* branchHead;

    int branchDim;

};

#endif

table.cpp

#include "table.h"
#include <iostream>
#include <stddef.h>

Table::Table(){
    branchDim = 5;
    head = NULL;
    treeTemp = NULL;
    treeCurr = NULL;

    branchHead = NULL;

}

int Table::treeAddress(int Address, int dim){
    // This function is used to calculate the address
    // of treeNodes.
    float val = 1 + (int)((float)Address/(float)dim);
    if (Address % dim == 0){
        val--;
    }

    return val;
}

void Table::addTreeNodes(int pos, int value){
    // This part will create one treeNode in order, if
    // needed. Works fine, just skip this part.
    treeNode* tn = new treeNode;
    tn -> address = treeAddress(pos, branchDim);

    // if the table doesn't exist. Create one treeNode
    if (head == NULL){
        tn -> below = NULL;
        tn -> right = NULL;
        head = tn;
    }
    else{
        // insert treeNode before.
        if(tn -> address < head -> address){
            tn -> below = head;
            tn -> right = NULL;
            head = tn;
        }
        else{
            treeCurr = head;
            treeTemp = head;
            while(treeCurr != NULL && treeCurr -> address < tn -> address){
                treeTemp = treeCurr;
                treeCurr = treeCurr -> below;
            }

            // insert treeNode on tail.
            if (treeCurr == NULL && tn -> address > treeTemp -> address){
                treeTemp -> below = tn;
                tn -> below = treeCurr;
                tn -> right = NULL;
            }
            else{
            // insert treeNode between two others nodes.
                if (tn -> address < treeCurr -> address){
                    treeTemp -> below = tn;
                    tn -> below = treeCurr;
                    tn -> right = NULL;
                }
                else{
                    delete[] tn;
                }
            }
        }
    }

    // This part will create one branchNode. Here is the big problem...

    branchNode* bn = new branchNode;
    bn -> address = pos;

    treeCurr = head;
    int tPos = treeAddress(pos, branchDim);
    while(treeCurr != NULL && tPos != treeCurr -> address){
        treeCurr = treeCurr -> below;
    }
    //If the branch is empty.
    if (treeCurr -> right == NULL){
        treeCurr -> right = bn;
        bn -> next = NULL;
        bn -> address = pos;
    }

    else{
        //Here I wanna put the branchNode before the first branchNode.
        if (pos < (treeCurr -> right) -> address){
            branchHead = treeCurr -> right; // for some reason, I don't know why,
            bn -> next = branchHead;        // I can't do that!!!!!!!!!!.
            treeCurr -> right = bn;
            bn -> data = value;
        }
    }
}

A: Assuming there exist only one "treeNode" and some "branchNode" for simplicity. I was able to point correctly to another type of node, following the hint of @Rabbid76 (thanks!). Maybe there's another way, but I'm already happy.

main.cpp

#include "table.h"
#include <iostream>

int main(){

    Table xxx;

    xxx.addTreeNodes(5,100);
    xxx.addTreeNodes(3,140);
    xxx.addTreeNodes(2,20);

    xxx.print();

    return 0;
}

table.h

#ifndef TABLE_H_
#define TABLE_H_

class Table{
public:
    Table();
    void addTreeNodes(int pos, int value);
    void print();

private:
    struct treeNode {
    public: class branchNode;
        treeNode* right;
        treeNode* below;
    };

    struct branchNode : public treeNode{
        int address;
        int data;
        branchNode* next;
    };

    branchNode* branchCurr;
    treeNode* head;
    treeNode* tn;
};

#endif

table.cpp

#include "table.h"
#include <iostream>
#include <stddef.h>

Table::Table(){
    head = NULL;
    branchCurr = NULL;
    tn = new treeNode;
}

void Table::addTreeNodes(int pos, int value){

    branchNode* bn = new branchNode;
    bn -> address = pos;
    bn -> data = value;

    tn -> below = NULL;

    if (head == NULL){
        head = tn;
        bn -> next = NULL;
        tn -> right = bn;
    }
    else{
        if (pos < ((branchNode*)head -> right) -> address){
            branchCurr = (branchNode*)head -> right;
            bn -> address = pos;
            bn -> data = value;
            tn -> right = bn;
            bn -> next = branchCurr;
        }
        else{
            delete[] bn;
        }
    }
}

void Table::print(){
    branchCurr = (branchNode*)head -> right;
    while(branchCurr != NULL){
        std::cout << "address: " << branchCurr -> address
                  << ", stored value: " << branchCurr -> data <<  std::endl;
        branchCurr = branchCurr -> next;
    }
}


text:
Q: Migrating from Visual studio 2008 to 2015 I have code for a software written in C++ with MFC in Visual Studio 2005. Now I need to migrate it to Visual Studio 2015. How can I do it and what are the challenges to be countered?

A: Like said in comments, open your solution, it will be converted. The issues I had when doing so:

*

*Only blocking issue for compilation I had was to change the Unicode handling option in project options because one of the related options disapeared/changed its values. There is a report after the conversion is complete, read it!

*All possible issues with such a huge gap in compilator versions are still possible then. So be carefull of the warnings (activate them if not done)

*Running some code analysis may be a good idea to detect deprecated syntax/methods, I had some unexpected behaviour on old Microsoft methods that were a bit too permissive before (clearly it was my fault but for some reason the old compilator was kind with some of my mistakes).


text:
Q: PHP - Find previous value in multidimensional array I have this array:
$test = array( "a" => "b",
                "c" => array("foo" => "bar",
                                "3" => "4",
                            ),
              "e" => "f",);

I want to create a function that finds the previous value in this array, given a certain value, for example find("bar", $test); should return "b".
This is what I got:
function find($needle, $array, $parent = NULL)
{
//moves the pointer until it reaches the desired value
  while (current($array) != $needle){
    //if current value is an array, apply this function recursively
    if (is_array(current($array))){
      $subarray = current($array);
    //passes the previous parent array
      find($needle, $subarray, prev($array));
    }
    //once it reaches the end of the array, end the execution
    if(next($array) == FALSE){
      return;
    }
  }
  //once the pointer points to $needle, run find_prev()
  find_prev(prev($array), $parent);
}

function find_prev($prev, $parent = NULL)
{
  // in case there is no previous value in array and there is a superior level
  if (!$prev && $parent) {
    find_prev($parent);
    return;
  }

  // in case previous value is an array
  // find last value of that array

  if (is_array($prev) && $prev){
    find_prev(end($prev), $parent));
    return;
  } else {
  $GLOBALS['pre'] = $prev;
  }
}

For pedagogical reasons and since I have devoted some time to this function, it would be great if you could provide any hints about why this isn't working rather than any other simpler solution that you might have.

A: The function find() calls itself recursively for sub-arrays but it doesn't check if the inner call found something or not and keep searching. This is why the first call to find_prev() runs with $test['b'] as its first parameter (prev() of the last element in $test). You expect it to run with $test['a'].

A: You have an infinite loop. Your algorithm is a bit complicated for what you want to do. Maybe you should just keep the previous value in a variable and return it when you find the $needle. Here is the corresponding code. I tried to not modify your code as much as I could:
function find($needle, $array, $lastValue = NULL)
{
  $previousValue = null;

  //moves the pointer until it reaches the desired value
  while (current($array) != FALSE) {
    $value = current($array);

    //if current value is an array, apply this function recursively
    if (is_array($value)) {
      $subarray = $value;
      //passes the previous value as the last value for the embedded array
      $value = find($needle, $subarray, $previousValue);
      if ($value !== NULL) {
        return $value;
      }
    } else if ($value === $needle) {
      //returns the previous value of the current array
      if ($previousValue !== NULL) {
        return $previousValue;
      //returns the last checked value of the parent array
      } else if ($lastValue !== NULL) {
        return $lastValue;
      } else {
        return;
      }
    } else {
      $previousValue = $value;
    }

    next($array);
  }
}

$test = array(
  "a" => "b",
  "c" => array(
    "foo" => "bar",
    "3" => "4"
  ),
  "e" => "f"
);

$result = find("bar", $test);

if ($result === null) {
  print('no previous value');
} else {
  $GLOBALS['pre'] = $result;
  print($GLOBALS['pre']);
}

You may try TDD to code this kind of algorithm. It could help you.


text:
Q: Implementing a MySQL trigger with a where condition including a count function The requirement is to implement a trigger that checks an exception table for entries that meet a set of criteria, multiple times over the past 1 hour.  Basically we don't want to be alerted on transient exceptions.
This is where I have got;
CREATE TRIGGER trException AFTER INSERT ON Exception
 FOR EACH ROW
 BEGIN
  IF NEW.ExceptionMessage like '%The operation is timed out%' or
    NEW.ExceptionMessage like '%https://....%' THEN
    INSERT INTO NotificationLog ('Message','InsertedTime') SELECT 'Time out error',now()
    WHERE (SELECT COUNT(ExceptionId) FROM Exception
           WHERE CreateTimestamp > NOW() - INTERVAL 1 HOUR
           AND ExceptionMessage LIKE '%The operation has timed out%'
           AND ExceptionMessage LIKE '%https://....%') > 10;
  ELSEIF NEW.ExceptionMessage like '%Error...%' THEN
            ...Next insert scenario with critria
  END IF;
END;

I think the issue is the count in the embedded SELECT statement.  The code works fine when it is run outside the insert statement. What can I do to solve this?

A: I have resolved the problem.  By adding a table (ExceptionNotificationMessage) to hold the notification messages, I was able to add a FROM clause to the first SELECT statement and that fixed the problem.
CREATE TRIGGER trException AFTER INSERT ON Exception
 FOR EACH ROW
 BEGIN
  IF NEW.ExceptionMessage like '%The operation is timed out%' or
    NEW.ExceptionMessage like '%https://....%' THEN
    INSERT INTO NotificationLog ('Message','InsertedTime')
      SELECT 'Message','InsertedTime'
      **FROM ExceptionNotificationMessage**
      WHERE (SELECT COUNT(ExceptionId) FROM Exception
           WHERE CreateTimestamp > NOW() - INTERVAL 1 HOUR
           AND ExceptionMessage LIKE '%The operation has timed out%'
           AND ExceptionMessage LIKE '%https://....%') > 10;
  ELSEIF NEW.ExceptionMessage like '%Error...%' THEN
            ...Next insert scenario with criteria
  END IF;
END;

Martin


text:
Q: Thread safety with a linked list in C Socket Programming I am using threads and TCP to implement a P2P file transfer in C. I have a tracker, which keeps track of all of the peers who are connected to it. When a peer first connects, it sends its files from its current directory to the tracker who places all the peer's files in a shared linked list. Each peer has its own thread in the tracker and when a peer exits, the tracker closes that peer's connection and removes all of the files from that peer from the linked list. What I am concerned about is locking the linked list when nodes are being added and also deleted. I want to safely be able to make changes to the linked list from various threads. I have written my code to add/delete from my linked list and also search (not sure if I need to use locking when I search) How can I modify my code to ensure linked safety between the threads?

A: Please consider using mutexes to protect data or other resources from concurrent access.
In the context of POSIX Threads the pthread_mutex_t type (from sys/types.h, The Open Group Base Specifications Issue 7, IEEE Std 1003.1, 2013 Edition) is used for the mutexes.
pthread_mutex_lock() and pthread_mutex_unlock() functions (The Open Group Base Specifications Issue 7, IEEE Std 1003.1, 2013 Edition) can be used to protect the instance of linked-list type from concurrent access for both operations:

*

*read operation: when enumerating the list (i.e. reading next pointer) and using (reading/writing) the data being stored in the node;

*write operation: changing the node: both next pointer and the data being stored in the node.

Also, the same mutex can be used to protect access to the head [of the linked-list] pointer.
Example:
// ...

pthread_mutex_t list_mutex = PTHREAD_MUTEX_INITIALIZER;

// ...

void *peer_handler(void *p)
{
    // ...

    pthread_mutex_lock(&list_mutex);
    if (numNodes == 0) {
        head = newNode;
        tail = newNode;
        tail->next = NULL;
        numNodes++;
    }
    else {
        tail->next = newNode;
        tail = newNode;
        tail->next = NULL;
        numNodes++;
    }
    pthread_mutex_unlock(&list_mutex);

    // ...

    pthread_mutex_lock(&list_mutex);
    struct fileNode *ptr = head;
    while (ptr != NULL) {
        if ((strcmp(ptr->ip, temp_ip) == 0) && ptr->port == temp_port) {
            cmd = htonl(200);
            break;
        }
        ptr = ptr->next;
    }
    pthread_mutex_unlock(&list_mutex);

    // ...
}

void sendList(int newsockfd)
{
    // ...
    pthread_mutex_lock(&list_mutex);
    struct fileNode *ptr;
    ptr = head;
    while (ptr != NULL) {
        // ...

        ptr = ptr->next;

        // ...
    }
    pthread_mutex_unlock(&list_mutex);
}

void removeFiles(uint32_t port, char *client_ip)
{
    pthread_mutex_lock(&list_mutex);

    // ...

    pthread_mutex_unlock(&list_mutex);
}

void print()
{
    // ...
    pthread_mutex_lock(&list_mutex);
    struct fileNode *ptr;
    ptr = head;
    while (ptr != NULL) {
        // ...

        ptr = ptr->next;

        // ...
    }
    pthread_mutex_unlock(&list_mutex);
}

It is worth noting that reducing lock contention — an important part of performance tuning concurrent applications.
Socket-related problems
The send() and recv() functions do not guarantee that all the specified number of bytes will be sent/received with one function call.
The appropriate loop should be used to send or receive the required (expected) number of bytes. For the additional details, please refer to the article: TCP/IP client-server application: exchange with string messages.
Also, be careful with such constructions:
n = recv(newsockfd, buffer, sizeof(buffer), 0);
// ...
buffer[n] = '\0';

The expected number of bytes (or, in this case, characters) to be received should be sizeof(buffer) - 1. Otherwise, there is a data loss: the last character is overwritten with the terminating null character.

A: The simplest solution is to have one pthread_mutex_t that you lock before any access to the list, and unlock once finished.  Declare it alongside the list variables:
struct fileNode *head, *tail;
int numNodes = 0;
pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER;

eg. when adding a node:
pthread_mutex_lock(&list_lock);
if (numNodes == 0) {
    head = newNode;
    tail = newNode;
    tail->next = NULL;
    numNodes++;
}
else {
    tail->next = newNode;
    tail = newNode;
    tail->next = NULL;
    numNodes++;
}
pthread_mutex_unlock(&list_lock);

or when traversing the list:
//check if peer is in the file list
pthread_mutex_lock(&list_lock);
ptr = head;
while(ptr != NULL) {
    // if peer is found
    if((strcmp(ptr->ip, temp_ip) == 0) && ptr->port == temp_port){
        cmd = htonl(200); //set cmd to 1
        break;
    }
    ptr = ptr->next;
}
pthread_mutex_unlock(&list_lock);

Since your list is accessed relatively rarely, this should be fine.  If you run into scalability problems caused by contention on this lock, you can move to a more complicated locking scheme.


text:
Q: How to create an emulator that uses a user-generated Android API I was able to compile my own modified version of the Android SDK by following the answer to this question: Configure eclipse to use my own Android SDK (framework.jar).
I imported this modified SDK in an Android Eclipse project. After doing so, I'm able to call methods that I added in the modified SDK at compilation time, but at run time the emulator throws a noSuchMethod exception.
I'm under the assumption that I also need to copy the system images generated after the compilation. I tried to copy the files in the folder system-images, and also modifying the build.prop file as in the question above, but had no success.
What am I missing?


text:
Q: shell скрипты на fedora Есть вопрос: работаю програмистом на линуксе, и каждый день нада запускать перед работой много программ для работы, по типу терминала, ide, проектов, папок и куча всего. Недавно узнал про существование shell файлов, которые при запуске запускают команды в терминал, а так как я лентяй, и мне лень каждый раз запускать много программ для работы пришла идея создать свой shell, в котором будет прописан запуск всех нужных мне программ.
Идея следующая: зайти в папку к проге, которая нужна, найти там его исполняющий файл, и потом ./имя_файла, или как то так.
Вопрос: так вообше можна, или это мои влажные фантазии?
Зарание спасибо за ответ.

A:
запуск всех нужных мне программ

Здесь есть три принципиально разных варианта. Соответственно и запускаются они по разному.

*

*Прикладная программа, которая запускается в Вашем сеансе после логина. Например, у меня, это почтовый клиент, клиент "Телеграм" и т.д. Принципиально важно, что это ваш сеанс. Запускаются либо через .profile / .bashrc (там прописано, где их можно вставлять), либо в настройках системы (по разному, для разных дистрибутивов) в разделе "Программы, запускаемые при старте".

*Прикладные программы, которые должны запускать вне Вашего сеанса, независимо от того, вошли Вы в систему, или - нет. Например - HTTP сервер. В разных дистрибутивах это делается по разному. В современных дистрибутивах, как правило, с помощью systemd.

*Программы, запускаемые по расписанию. Как правило, это делается с помощью какой-то разновидности cron. Всякие бэкапы, проверки диска и т.д. Они тоже делятся на две категории: в вашем сеансе и общесистемные.

A: Можно cделать просто alias в конф файле .bashrc


text:
Q: The code executable cannot continue: libgcc_s_seh-1.dll was not found I have a problem that I cannot solve, When I run the executable of my program it gives me the following error:
The code executable cannot continue because libgcc_s_seh-1.dll was not found. To fix the problem, try reinstalling the program

I tried to manually copy and paste the file (libgcc_s_seh-1.dll) into the folder where I keep the executable but I get the following error:
The application could not be started correctly (0xc000007b)

Additional information:

*

*I use windows 10 64 bit

*I Use mingw81_64

*I use version 6.1.2 of Qt

What can I solve the problem?

A: I guess you double-clicked in exe file that provides after building in release mode :
For Deploy and create Exe output with QT in windows you should follow this way:

*

*put your compiler path in your system path. now you use mingw81_64 you should set it. something like  Qt/tools/mingw81_64/bin

*copy exe file that provides after building in release mode in one folder and run mingw81_64 cmd (it has separate cmd)
and cd to that folder path

*windeployqt  app.exe
This command will get all dll needs for your app and your exe will work .
if you use qml
windeployqt --qmldir (the path of its directory ) app.exe

and also see these youtube videos for more info:
https://www.youtube.com/watch?v=LdSTgR0xJco
https://www.youtube.com/watch?v=hCXAgB6y8eA

A: For specific error of libgcc_s_seh-1.dll was not found, please try to copy libgcc_s_seh-1.dll, libstdc++-6.dll, libwinpthread-1.dll into your compiler path like Qt/tools/mingw81_64/bin.

A: You should copy libgcc_s_seh-1.dll, libstdc++-6.dll, libwinpthread-1.dll into your exefile path after executing windeployqt.exe with all files are in correct version.


text:
Q: How to extend floating child div to parent div with other siblings I am creating HTML Table view using HTML DIVs dynamically. Cell created by DIV should be expandable also As In near future i would need to implement Drag and Drop functionality also.
For this i have created a layout which look like below and code is available at fiddle .

There are 8 div cells arranged in a floating manner such that they acquire 12.5% of the width, Here any divs can be increased to 20-25 lines and they will have increased height without any scrolls. while other divs will have lesser lines.
My Problem is -- I want to show border of 1px between rendered cells(As show in below screenshot), but all divs are not expanded to its 100%, so how can I manage it

So Summary is ,
1) I need to extend DIV and whole row of that DIV if content of the cell(DIV) is increased,
2) I need border at left and bottom ,
3) I don't want to use table, or display: table, table-cell

A: if you're dead set against display: table, table-cell, would you consider using flexbox? Note: Flexbox is not supported in IE9 and might behave a little weirdly across different browsers. Make sure to test thoroughly!

div {
  font-family: Verdana, Arial, Helvetica, sans-serif;
  font-size: 11px;
}
.cg-holiday-head,
.cg-dateinfo-head {
  overflow: hidden;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}
.cg-info-cell,
.cg-calendar-cell {
  width: 12.5%;
  float: left;
  padding: 3px 5px;
  overflow: hidden;
}
*,
*:before,
*:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.cg-holiday {
  background-color: #1B7EAD;
  color: white;
  text-align: center;
  padding: 2px;
  border: 1px solid #8CBBD6;
}
.cg-patient-head {
  background-color: #29A5E3;
  color: white;
  padding: 5px;
  border-right: 1px solid #ADE1F8;
}
.cg-dateinfo {
  padding: 5px;
  background-color: #E7F7FF;
  flex: 1;
}
.cg-weekend-day {
  background-color: #86CFF0;
}
.cg-row-container {
  border-bottom: 2px solid #68BFE8;
  min-height: 30px;
  /*display: table;*/
  overflow: auto;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}
.cg-row-container .cg-info-cell,
.cg-row-container .cg-calendar-cell {
  border-right: 1px solid black;
}
.cg-calendar-cell:last-child {
  border-right: none;
}
.cg-row-container:nth-of-type(even) {
  background-color: #ebf7ff;
}
.cg-container {
  height: 100%;
  overflow-y: scroll;
}
.cg-cell-border {
  position: absolute;
  top: 0px;
  bottom: 0px;
  margin: 1px 0 1px -2px;
  border: 1px solid lightgray;
}
/*----------------------- CSS BROWSER HACKS -----------------------------*/

/* Chrome Hacks */

.cg-holiday-head:not(*:root),
.cg-dateinfo-head:not(*:root) {
  /*margin-left: 17px;*/
  /*No Need for a hack at the moment*/
}
/* End of Chrome Hacks */

/*End of  CSS BROWSER HACKS */

HOLIDAYYY!!!

HOLIDAY2

PATIENT

SUNDAY - 3/19

MONDAY - 3/20

TUESDAY - 3/21

WEDNESDAY - 3/22

THURSDAY - 3/23

FRIDAY - 3/24

SATURDAY - 3/25

Finley, Angela

(387)

status

vacation

absence

visit

visit

visit

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

Stanton, Ella

(132)

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

inservice

inservice

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice

status

vacation

absence

visit

inservice


text:
Q: cargo always starts with " Blocking waiting for file lock on build directory" I recently installed rustup on my Windows machine and incorporated it into Atom as my editor. Everything works fine, but as soon as I do a cargo run on my project, the first thing that Cargo says is:
 Blocking waiting for file lock on build directory

This blocks the whole process for about a minute before the actual compile and run starts. As far as I remember this did not happen before (I use Cargo under OS X but without rustup).
Is there any way to disable this or at least reduce the timeout?

A: The tokamak Atom plugin runs cargo commands. Since you cannot run cargo twice at the same time, you get this notice.
I don't think there is something you can do, unless waiting for the compiler to speed up.
Perhaps playing with the options like save_buffers_before_run in tokamak.toml could make a difference.

A: Today I facing the same problem, and this command works for me:
rm -rf ~/.cargo/.package-cache

Once you run the code, just run cargo build


text:
Q: Android VideoView and NavigationBar I have fullscreen activity and video view in my application.
NavigationBar hides automaticaly in 5 seconds, when i don't touch a screen.
I've tried to add onSystemUiVisibilityChangeListener to videoview, and tried setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE), and i had no positive results.
What I need to do to prevent hiding navigationbar?

A: you can simply add like this.
public class mediaController extends MediaController {
    @Override
    public void hide() {
    }
}


text:
Q: update textbox value on designer file windows form in C#.net I want to update the textbox value in designer file default value to programmatically, help with me any one how to do this update textbox value in form designer file on C#.net.
Help with me any code or tutorial!
Thanks!


text:
Q: Генерация графиков в цикле в Python Есть датасет. Нужно построить "ящики с усами" для данных из всех его столбцов. Названия столбцов отличаются друг от друга числом по нарастающей: 'feature_1', 'feature_2'  и т.д. Код почему-то загоняет все 5 столбцов в один график, а не генерирует 5 графиков.
import pandas as pd
from matplotlib import pyplot as plt
result = pd.read_csv('result.csv', encoding='utf-8')

for i in range (1, 6):
    n = "feature_" + str(i)
    plt.title("Распределение " + n)
    plt.boxplot(result[n])

Нужно, чтобы код генерировал в цикле все 5 графиков по отдельности, а не перемешивал все данные в один график.

A: Чтобы каждый график был в отдельной картинке, нужно делать перед каждым графиком так:
plt.figure() # тут можно ещё `figsize=(размерX,размерY)` задать

Можно ещё сделать графики в несколько колонок для экономии места, тогда нужно использовать plt.subplots, пример.


text:
Q: Why is the -i argument to supervisor important to get an interactive shell? in order to impersonate as superuser1 I need to run command like this
sudo -u superuser1 -i

I did try sudo -u superuser1 which means switch to superuser1 and its totally making sense, but it doesn't work
I also read about the sudo man page -i option

-i, --login
  Run the shell specified by the target user's password database entry
  as a login shell. This means that login-specific resource files such
  as .profile or .login will be read by the shell. If a command is
  specified, it is passed to the shell for execution via the shell's -c
  option. If no command is specified, an interactive shell is executed.
  sudo attempts to change to that user's home directory before running
  the shell. The command is run with an environment similar to the one a
  user would receive at log in. The Command environment section in the
  sudoers(5) manual documents how the -i option affects the environment
  in which a command is run when the sudoers policy is in use.

I can see, it puts the command into interactive mode, but it doesn't explain why
sudo -u superuser1 doesn't work.
can any one explain what exactly -i does, and why without it doesn't work

A: This is given, explicitly, in the man page content you quoted in the question itself:

If no command is specified, an interactive shell is executed.

That's behavior specific to sudo -i. If you want an interactive shell, then, you need to either run sudo -i, or something like sudo -u user1 -- bash -i -l.

A: As you can see from the man page, the -i option, not only puts the command into interactive mode but also execute the content of .profile and presumably .bashrc. I imagine that to run your command you must specify some environment variable that is automatically loaded when you use the "-i" option.


text:
Q: Detect whether email is sent or not + Blackberry I am facing a little problem with Transport.send(msg) function of Blackberry API. In my application i need to send a sound file. But I want to know what happens if the device loses connectivity in middle of sending the email.
I tried to enclose the Transport.send(msg) call within try catch block but it never throws exception even if i manually turn off the wifi from the device while the file is being sent.If by any chance email could not be sent i want to show the user a Dialog saying that email could not be sent.
Kindly help.
Regards,
tek3

A: You can catch SendFailedException which is thrown when a message cannot be sent.
You can monitor the messages by calling getStatus() on a message which should return you the values given here