text:
Q: How to convert from Properties file to CSV file which has multiple languages like hu? In property file it looks like,
value1=CÍMSOR (NEM KÖTELEZŐ)
value2=NEM KÖTELEZŐ/NEM ALKALMAZHATÓ

I have loaded this in Java .properties which comes exactly like above, then the problem comes while storing to String. In both values 'Ő' comes as '?'.
I have to store it in a String and save all these values in CSV (comma separated) file.
First I am reading the property file
FileInputStream input = new FileInputStream(new File(fileName));
Properties prop = new Properties();
prop.load(new InputStreamReader(input, Charset.forName("UTF-8")));

This part works properly.
Second reading the values
String value1 = prop.getProperty("value1");

value1 comes like "4. CÍMSOR (NEM KÖTELEZ?)" instead of 'Ő' it comes as '?'
The third part is to add this values into CSV file,
OutputStream stream = new FileOutputStream(outputCSVLocation);
CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(stream, "UTF-8")));
csvWriter.writeNext(value1);

A: I found the answer,
For conversion to String use this,
StringUtils.toEncodedString("".getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"));

For converting this values into csv use this below,
    OutputStream fileWriter = new FileOutputStream(outputCSVLocation);
    //Informing csv to encode in UTF-8
    byte[] enc = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };
    fileWriter.write(enc);
    CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(fileWriter, Charset.forName("UTF-8")));

So When I open file it comes in the language which was in the property file.
But again I got another issue,
When I read the csv file it comes with values like ?"header value" this that too for first  row first column value alone. This comes because of those 3 bytes for encoding which I have added.
Any idea to fix this ??

A: Are you sure your input Properties file is really ISO-8859-1? If so then you should be loading the properties with:
prop.load(new InputStreamReader(input, StandardCharsets.ISO_8859_1));

Or - you can call the default Properties load(InputStream) which makes the assumption that the input stream is ISO-8859-1 character set, and allows for other unicode characters as escape sequences of format \uNNNN.


text:
Q: Deserialize json string to C# anonymous array var data1 = new[] {
              new { Product = "Product 1", Year = 2009, Sales = 1212 },
              new { Product = "Product 2", Year = 2009, Sales = 522 },
              new { Product = "Product 1", Year = 2010, Sales = 1337 },
              new { Product = "Product 2", Year = 2011, Sales = 711 },
              new { Product = "Product 2", Year = 2012, Sales = 2245 },
              new { Product = "Product 3", Year = 2012, Sales = 1000 }
          };
            string jsondata =JsonConvert.SerializeObject(data1);

What I wish to do is deserialize jsondata to same object as in data1 (C# array with anonymous type{string Product, int Year, int Sales})
I tried without success..
var dataj = JsonConvert.DeserializeObject<JArray>(jsondata);
            var data = dataj.ToArray();

How do I know.. Because the following does not work though it works with the original C# array(data1)
foreach (var d in data)
            {
                int a = d.Year;
            }

Without creating a separate class, can I do this..

A: You need to use the dynamic keyword since Year isn't really a property of JToken. The runtime binder can retrieve the value though from introspecting the JToken though.
This is the only line you have to change:
dynamic data = dataj.ToArray();

In your original code the type is anonymous, but that doesn't mean it can't know what properties it has.

A: There are trick, howto deserialize it without dynamics. It should be a liiiiitle bit faster. This also can be as generic solution
public static class Ext
{
    public static IEnumerable<T> Deserialize<T>(this string source, T typeHolder)
    {
        var ltype = typeof(List<>);
        var constructed = ltype.MakeGenericType(new[] { typeHolder.GetType() });

        // deserializing
        return (JsonConvert.DeserializeObject(source, constructed) as IList).Cast(typeHolder);
    }

    public static IEnumerable<T> Cast<T>(this IEnumerable x, T typeHolder)
    {
        foreach (var item in x)
        {
            yield return (T)item;
        }
    }
}

So, usage:
void Main()
{
    var data1 = new[] {
                      new { Product = "Product 1", Year = 2009, Sales = 1212 },
                      new { Product = "Product 2", Year = 2009, Sales = 522 },
                      new { Product = "Product 1", Year = 2010, Sales = 1337 },
                      new { Product = "Product 2", Year = 2011, Sales = 711 },
                      new { Product = "Product 2", Year = 2012, Sales = 2245 },
                      new { Product = "Product 3", Year = 2012, Sales = 1000 }
                  };

    string jsondata = JsonConvert.SerializeObject(data1);
    var ob = new { Product = "Product 1", Year = 2009, Sales = 1212 };
    var deserializedObject = jsondata.Deserialize(ob);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loading a view routed by a URL parameter (e.g., /users/:id) in MEAN stack I am having difficulties with trying to load a user by their id, for some reason my http.get call isn't hitting my controller.
I get the following error in the browser console:
TypeError: undefined is not a function
    at new <anonymous> (http://localhost:9000/scripts/controllers/users.js:10:8)

Update
I've fixed my code up as per comments below, but now my code just enters an infinite loop in the angular users controllers (see code below) and I do not get the error above.
I am using the Angular Express Generator for reference
Backend - nodejs, express, mongo
routes.js:
// not sure if this is required, but have used it before?
app.param('username', users.show);

app.route('/api/users/:username')
    .get(users.show);

controller.js:
// This never gets hit
exports.show = function (req, res, next, username) {
    User.findOne({
        username: username
    })
    .exec(function (err, user) {
        req.user = user;
        res.json(req.user || null);
    });
};

Frontend - angular
app.js:
$routeProvider
    .when('/users/:username', {
        templateUrl: function( params ){ return 'users/view/' + params.username; },
        controller: 'UsersCtrl'
    })

services/user.js:
angular.module('app')
    .factory('User', function ($resource) {

        return $resource('/api/users/:username', {
            username: '@username'
        }, {
            update: {
                method: 'PUT',
                params: {}
            },
            get: {
                method: 'GET',
                params: {
                    username:'username'
                }
            }
        });
});

controllers/users.js:
angular.module('app')
.controller('UsersCtrl', ['$scope', '$http', '$routeParams', '$route', 'User', function ($scope, $http, $routeParams, $route, User) {

        // this returns the error above
        $http.get( '/api/users/' + $routeParams.username )
            .success(function( user ) {
                $scope.user = user;
            })
            .error(function( err) {
                console.log( err );
            });
}]);

If it helps, I'm using this setup

A: angular.module('app')
.controller('UsersCtrl', ['User', '$scope', '$route', '$routeParams', function ($scope,    $http, User, $route, $routeParams) {

you forgot to add $http in your users.js file
try this one
angular.module('app')
.controller('UsersCtrl', ['User', '$scope', '$http','$route', '$routeParams', function ($scope, $http, User, $route, $routeParams) {

A: First we need to clean up your Inline Array Notation (Read -https://docs.angularjs.org/guide/di).
Based on this code
angular.module('app')
.controller('UsersCtrl', ['User', '$scope', '$route', '$routeParams', function ($scope, $http, User, $route, $routeParams) {

        // this returns the error above
        $http.get( '/api/users/' + $route.username ).success(function( user ) {
            $scope.user = user;
        });
}]);

Your $scope variable is actually some User service, your $http is actually your $scope, User is actually $route,  $route is $routeParams, and $routeParams is actually $routeParams if you aren't using a compiler. Change this to the following and tell me what you get:
angular.module('app')
.controller('UsersCtrl', ['$scope', '$http', 'User', '$route', '$routeParams', function ($scope, $http, User, $route, $routeParams) {

        // this returns the error above
        $http.get( '/api/users/' + $route.username ).success(function( user ) {
            $scope.user = user;
        });
}]);


text:
Q: Not able to refer a control in code behind in VS 2008 with WPF I don't know why but for some reason I am not able to refer to my tbText control in my code behind file. Here is the XAML part:

        <ComboBox.ItemTemplate>
            <DataTemplate>
                <ItemsControl x:Name="ic">

                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"></ColumnDefinition>
                            <ColumnDefinition Width="2*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>

                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"></RowDefinition>
                        </Grid.RowDefinitions>
                    </Grid>

                     **<TextBlock x:Name="tbText"  Grid.Column="0" Grid.Row="0"  Margin="10" />**
                     <Image Grid.Column="1" Margin="10" Grid.Row="0" Width="100" Height="100" Stretch="Fill">

                    </Image>

                </ItemsControl>
            </DataTemplate>
        </ComboBox.ItemTemplate>

I cannot refer to the "tbText" control.

A: You can't refer to it because it is inside an Items control.
You'd have to search the ItemsControl children in order to find the textbox.
See Finding control within wpf items control for ways to do this.


text:
Q: Compare lists and give me what isn't in list a that is in list b I have 2 lists. Let's call them A and B. Is there a neat stl trick to see what list B has that list A doesn't without myself manually looping over them with an iterator comparing the elements myself?

A: std::set_difference

The difference of two sets is formed by the elements that are present in the first set, but not in the second one. The elements copied by the function come always from the first range, in the same order.

Note that the two lists have to be sorted.
Here is a sample that shows example of usage:
#include <iostream>
#include <algorithm>
#include <list>

using namespace std;

int main()
{
   list<int> a {1,2,3,4,5,10};
   list<int> b {4,5,6,7,11};
   list<int> out;
   set_difference(b.begin(), b.end(), a.begin(), a.end(), back_inserter(out));
   cout << "out size is " << out.size() << endl;
   for(auto i: out)
   {
      cout << i << endl;
   }
}

A: you might be able to use the set_difference algorithm  set-difference discription
and here is a c++ example cppreference


text:
Q: Mutable Swift array becomes NSArray when I initialize with Obj-C I'm creating my base models in Swift(2.0) and then controlling the views in Objective-C.  I'm still new to Swift, so hopefully I'm just overlooking something simple, but here is the problem:
I'm making a mutable array in Swift, but when I initialize the array in my Objective-c portion of the program, it becomes an NSArray, more specifically it becomes: Swift._SwiftDeferredNSArray
Why is it becoming immutable when I initialize?  Here's my Swift code:
import Foundation

@objc public class Model : NSObject {

    var books:[Book]

    override init(){
        self.books = [Book]()
    }

}

And here's my Obj-c Code;
Model *bookCollection = [[Model alloc]init];

I'm unable to add objects to my bookCollection.books array (because it has become an NSArray) and when I set a breakpoint and po it, I can see that it is a Swift._SwiftDeferredNSArray.  bookCollection.books is supposed to be an NSMutableArray.
Any thoughts?

A:
bookCollection.books is supposed to be an NSMutableArray.

No, it is not. Var does not mean that the bridged Objective-C object is to be mutable: it means that the property can be assigned to.
The Swift array type is a structure, not a class. This has important bridging implications. The reference itself cannot be shared without passing it as an inout value, and even then the references cannot be stored. If it bridged as a NSMutableArray, it would be possible to have undetectable mutating references, and Swift does not allow that.
You should be able to assign a new NSArray to your property from Objective-C code, though. For instance, this should work:
bookCollection.books = [bookCollection.books arrayByAddingObject:myNewBook];

Your other option, obviously, is to declare books as a NSMutableArray from the Swift side.

A: In swift, the difference between mutable and immutable array is;
var books:[Book] // is a mutable array
let books:[Book] = [book1, book2]; // is immutable array due to let

but I don't think, same rule is followed when bridging to ObjC.
Just for a fix, you may have mutableArray specifically.
import Foundation

@objc public class Model : NSObject {

    var books:NSMutableArray = NSMutableArray();

    override init(){
        super.init();
        // other code
    }

}

You will need to parse the values to Book Class when retrieving from the array.


text:
Q: Emit a value after onNext is called after a particular time I want to emit a random value 10 secs after onNext is called. So onNext will be called for 12345 and 10 secs later onNext should be called for a random number. What is the best way to achieve this using RxJava? Thanks in advance.
Observable.create(subscriber -> {
    subscriber.onNext(12345);
}).subscribeOn(...)
.observeOn(...)
.subscribe(new Subscriber<Long>(){
    @Override
    public void onNext(Long aLong) {
        //Do Something
    }
})

A: If you emit your '12345' value right away, then solution is trivial. Just merge this observable with timer and you will get this kind of behavior. However, I am going to assume that your logic in OnSubscribe method you pass to create is doing some work and will emit the value once it is ready ( i.e. network request ). In that case, you need leverage both flatMap and merge operators. Something like this should suffice.
Observable.create(subscriber -> {
    subscriber.onNext(12345);
})
  .flatMap(value -> Observable.just(value)
        .mergeWith(Observable.timer(10, TimeUnits.SECONDS).map(/* define your "random" value here */))
  )
  .subscribeOn(...)
  .observeOn(...)
  .subscribe(new Subscriber<Long>(){
      @Override
      public void onNext(Long aLong) {
        //Do Something
      }
  })

It will take your value and convert it into and observable, which emits this value right away and starts a timer for 10 seconds to emit something else.
Note: Beware that this will take every item your observable emits and create this delayed second response for each of them. So if you plan on emitting multiple values from your source observable, you need to take this into account.


text:
Q: MPI inter communication: What is the peer communicator? I'm trying to understand how to use MPI_Intercomm_create to create a communication handle from one group to another. These two groups are also written in their own C files so there is no way of one group directly accessing the other's communication handle unless I use a global variable or the like. How do I get the "peer_comm" (3rd argument of the call) for the other group? Or am I just not understanding something?

A: MPI_Intercomm_create() operates on communicator (e.g. MPI_Comm) and not on groups (e.g. MPI_Group) so let's use the right semantic here.
If you launch several binaries with the same mpirun command line, then they are all in MPI_COMM_WORLD, and this is likely what you want to use for peer_comm.
If you use MPI_Comm_spawn() in order to launch "the other binaries", then it returns your inter communicator, so you likely do not even need MPI_Intercomm_create().
I strongly encourage you to write a Minimal, Complete, and Verifiable example. Not only it will help you clear some confusion, you will more likely get a precise answer once the issue is clearly stated.


text:
Q: std::string.find_first_not_of, unexpected return value #include <stdio.h>
#include <string>

int main(void)
{
    printf("%u\n", std::string("\n").find_first_not_of(" \t\n\v\f\r", 0, 1));
}

The following program prints 0, not std::string::npos as I expected. Why?

A: Your call matches:
size_t find_first_not_of ( const char* s, size_t pos, size_t n ) const;

n is the number of chars in s, and you're passing 1. So, you're searching for the first char that is not space. The rest of your " \t\n\v\f\r" string is ignored.
Likely you simply want:
find_first_not_of(" \t\n\v\f\r")

A: The third parameter doesn't mean what you think it does.

A: According to this, string::find_first_not_of searches for the first character in the object which is not part of either str, s or c, and returns its position. Since "\t" is such character, return value is 0.

A: Based on what you want to print, I can say the third parameter should be the length of string you passed. So here is the corrected version:
#include <stdio.h>
#include <string>

int main(void)
{
    std::string s=" \t\n\v\f\r";
    printf("%u\n", std::string("\n").find_first_not_of(s.c_str(), 0, s.length()));

   //since now I'm using std::string, you can simply write:
   printf("%u\n", std::string("\n").find_first_not_of(s));
}

Demo at ideone : http://ideone.com/y5qCX

A: See it:
#include <stdio.h>
#include <string>

int main(void)
{
        std::string s("\n");
        if( s.find_first_not_of(" \t\n\v\f\r", 0, 1) != std::string::npos )
                    printf("%u\n", s.find_first_not_of(" \t\n\v\f\r", 0, 1));
        else
                puts("npos");
        return 0;
}

A: The method find_first_not_of interpret the last argument as the number of char to consider in its first argument, not in the string.
size_type std::string::find_first_not_of(
    const char* str, size_type index, size_type num) const;

The argument num is the number to consider in str, not in this ! So in your case, it only consider the first caracter of " \t\n\v\f\r". You code is equivalent to:
#include <cstdio>
#include <string>

int main(void)
{
    printf("%u\n", std::string("\n").find_first_not_of(" ", 0));
}

If you want to only match a substring of the std::string, I think you must call find_first_not_of on an explicit substring, that is:
#include <cstdio>
#include <string>

int main(void)
{
    printf("%u\n", std::string("\n").substr(0, 1).find_first_not_of(" \t\n\v\f\r"));
}

BTW, here is the description of the behavior of the find_first_not_of method:

The find_first_not_of() function either:

*

*returns the index of the first character within the current string that does not match any character in str, beginning the search at index, string::npos if nothing is found,

*searches the current string, beginning at index, for any character that does not match the first num characters in str, returning the index in the current string of the first character found that meets this criteria, otherwise returning string::npos,

*or returns the index of the first occurrence of a character that does not match ch in the current string, starting the search at index, string::npos if nothing is found.


text: Q: Error when I install wubi in windows 7 I have downloaded ubuntu-14.04.1-desktop-i386 for 32 bit(less than 2 gb ram) and inside iso when i run wubi installer directly showing an error showing in temp file wubi-14.04-rev286 and not installing.I have tried same for ubuntu 12.04 also but same problem persist and an error that is shown in folder wubi-12.04-rev266 temp file.Thats why i am unable to install any of ubuntu version.I have urgent need to install it.Please someone help.....


text:
Q: Shuffling lines of a file with a fixed seed? I want to shuffle the lines of a file with a fixed seed so that I always get the same random order. The command I am using is as follows:
sort -R file.txt | head -200 > file.sff

What change could I make it so that it sorts with a fixed random seed?

A: Linux's shuf command can take a file as a fixed source of randomness using the parameter --random-source:
shuf --random-source=some_file.txt file.txt | head -n200 > file.sff

If you don't want to bother with giving a full file, you can pipe one on the go:
shuf --random-source=<(yes 42) file.txt | head -n200 > file.sff

A: The GNU implementation of sort has a --random-source argument. Passing this argument with the name of a file with known contents will result in a reliable set of output.
See the Random sources documentation in the GNU coreutils manual, which contains the following sample implementation and example:

get_seeded_random()
{
  seed="$1"
  openssl enc -aes-256-ctr -pass pass:"$seed" -nosalt \
    </dev/zero 2>/dev/null
}

shuf -i1-100 --random-source=<(get_seeded_random 42)

Since GNU sort is also part of coreutils, the relevant documentation applies there as well:
sort --random-source=<(get_seeded_random 42) -R file.txt | head -200 > file.sff

A: You may not need to use external tools like sort, whose options and usage may vary depending on your operating system. Bash has an internal random number generator accessible through the $RANDOM variable. It's common practice to seed the generator by setting the variable, like so:
RANDOM=$$

or
RANDOM=$(date '+%s')

etc. But of course, you can also use a predictable seed in order to get predictable not-so-random results:
$ RANDOM=12345; echo $RANDOM
28207
$ RANDOM=12345; echo $RANDOM
28207

To reorder the lines of the mapped file randomly, you can read the file into an array using mapfile:
$ mapfile -t a < source.txt

Then simply rewrite the array indices:
$ for i in ${!a[@]}; do a[$((RANDOM+${#a[@]}))]="${a[$i]}"; unset a[$i]; done

When reading a non-associative array, bash naturally orders elements in ascending order of index value.
Note that the new index for each line has the number of array elements added to it to avoid collisions within that range. This solution is still fallible -- there's no guarantee that $RANDOM will produce unique numbers. You can mitigate that risk with extra code that checks for prior use of each index, or reduce the risk with bit-shifting:
... a[$(( (RANDOM<<15)+RANDOM+${#a[@]} ))]= ...

This makes your index values into a 30-bit unsigned int instead of a 15 bit unsigned int.

A: If you're randomly shuffling lines, you're not sorting. I haven't seen a sort with --random-source prompt before. It'd be interesting if it does exist. However, that's not sorting the lines in a fixed order.
I believe you'll have to write a program to that, and I don't think Bash can quite do it.
Actually, it might. The $RANDOM environment variable selects a random number from 0 to 32767. You can assign a seed to RANDOM and the random number sequence will appear over and over. You can use a card dealing algorithm. Read in each line into a Bash array, then use the card dealing algorithm to pick each line.
I'm not going to write a test program -- especially in Bash, but you should get the idea.


text:
Q: Tight border on current matlab figure I know

imshow('myimage.png','border','tight');

will give a tight border around the image. But what if I already have an image open? Is there a way to make it have a tight border?

A: imshow('coins.png')
set(gca, 'Units', 'normalized', 'Position', [0 0 1 1])

A: (1) Select the axis of the figure where the image is shown, by clicking over the image.
(2) Type on the Command Window

axis tight

assuming that this is what you wish to do...  It was not clear from your question what you exactly wanted to do.


text:
Q: I'm using ActiveMQ version 5.15.10 And broker gets block from time to time during 10 to 15 min I have one k8s environment with one single broker and multiple producers and consumers.
I have one single broker with multiple producers and consumers. Producers are in grouped by customer and each customer has 3 to 8 producers, all of them share the same Group ID. A group reset is done by one of the producers every 2 minutes more or less.
On the other side of the broker I have consumers dynamically created and destroyed depending on the size of the broker queue, it could be from 2 to 4 consumers.
Like 4-5 times per week I found cases on which broker stops sending messages to consumers during 10 to 15 minutes. This seems to match with moments in which one or two consumers are terminated because a spot reclaim. Some new consumers are created by k8s, and in some cases they even start  getting a few messages, but then broker stops sending messages during 10 to 15 minutes.
I have try several things, I have increase the time on which the group reset is done, before is was done every few seconds and now is every 120 seconds, initially it was looking like helping but after several weeks I'm not so sure.
I have try to reproduce the problem in a dev environment with no luck.
One of my guess was that it was related with the prefetchSize and I want to try to set it to 1, but it will take some time to be able to test this in production.
I have configured this vales.
<policyEntry queue=">" consumersBeforeDispatchStarts="2" timeBeforeDispatchStarts="30000"/>

Could it be a random bug couting the consumers in the broker?
The prefetchSize is right now 1000, could it be a problem with the messages still not processed stored in the terminated consumers.


text:
Q: ADC resolution selection I want to convert analog output of an accelerometer to digital codes.
I understand that the sampling rate of the ADC should be with reference to Nyquist criteria.
Please let me know how to decide on the resolution needed.

A: It depends on the significance you need and the supported range. Consider an accelerometer that outputs 0 to 5 volts (range), and you want to measure with two decimal (significance). That would mean you would have \$5\cdot100=500\$ possible values. To get that amount of possible values in a binary number, you would need \$\lceil\log_2{(500)}\rceil=9\$ bits. In case you only want one decimal, you would have \$5\cdot10=50\$ possible values, needing \$\lceil\log_2{(50)}\rceil=6\$ bits.
You should indeed consider sample rate as well. When you use a higher resolution, the ADC will not be able to handle as much conversions as it would be when using a lower resolution. How much it differs can be find in the relevant datasheet.
Sometimes / most of the time, you can only choose between a few resolutions, for example 8 or 16 bits. You can calculate the significance you get with, for example, 8 bits, like this: \$2^8=256\$, so we have 256 possible values. On a range of 5V, that would give a significance of \$5/256=0.0195V\$.
In the datasheet of the accelerometer, you can find how 1V translates to the data you need. For a temperature sensor for example, you will find something like '5K/V' - this would mean one Volt difference means a 5K (Kelvin) difference. That means the output will change with 0.2V when the temperature changes with 1K. When you want a resolution of 0.1K, that would mean a resolution of 0.02V. This would mean you need \$5/0.02=250\$ values, needing \$\lceil\log_2{250}\rceil=8\$ bits.

A: Noise is the determining factor.
You first must start with the noise level of what your Accelerometer + Amplifier puts out, lets call this N for noise.  Then you need to find what your accelerometer puts out at it's maximum, we will assume that this will be some RMS value and call it S for signal.
Your SNR (signal to noise ratio) \$=\frac{S}{N}\$
The base number of Bits you need is \$ B = log_2(SNR)\$
But this is not sufficient as the ADC will have some inherent noise itself.  to ensure that the ADC noise does not interfere, or to put it another way , to ensure that the ADC noise does not factor into the signal you must ensure that the resolution is greater than the B value calculated above.  For a very strict definition the noise from the ADC should be 10% of the signal noise but you may find that 25% is adequate.
In your ADC data sheet you'll find a number called ENOB (Effective number of bits).
In the 10% case:
ENOB > B + \$log_2(10)\$ > B + 3.32
In the 25% case:
ENOB > B + \$log_2(4)\$ > B + 2
Next you have to scale the output of your accelerometer and buffer amplifier so that the max of is a little less than the maximum of what the ADC can handle (again from the datasheet).
If you have matched the ENOB and the scale then everything else is taken care of.

A: Resolution of ADC is the measure of its preciseness. It depends upon how much sensitivity do you require for your design. For your case it will be converting accelerometer's voltage signals into digital output.
First measure your peak voltage from accelerometer say 100mv, then decide how much sensitivity do you require e.g. your design must be sensitive to 0.5mv signals. Divide 100mv by 0.5mv you get 200. This is the number of voltage steps you want to divide your signal into and the closest resolution for this number is log(200)/log(2) = 7.6 which is rounded off to 8. so you need an 8 bit ADC for this particular example.
NOTE: In above example it has been assumed that the input signals are of positive polarity only. In case of a negative polarity you need to shift the signal into positive polarity.

A: @Vicky Rao I think the reply by @Arslan Abbas is very relevant..
use the formula :
ADC bit resolution = (log ((VD * E) / (R * Vs))) / (log (2)) + B
here     VD is full scale I/P voltage range of ADC.
    Vs is full scale O/P voltage range of measured signal.
    E is value represented in engineering units that Vs represent.
    R is the resolution that is required.
    B = 1 if ADC used is bipolar else 0.
The LSB achieved by the ADC can be calculated (LSB represents the smallest increment that the converter can resolve)
Q = VD / 2^a
where VD is The input analog voltage range of the ADC and a is the resolution of ADC selected
consider the example : VD = (+2.5V – (-2.5V)) = 5V (The input analog voltage range of the bipolar ADC is set at ±2.5V) and a 16 bit resolution is selected hence
Q = 5/ 2^16
Q = 76.29µV


text:
Q: SVG image size in React I have an SVG image that must be imported. The original image is too big so it must be made smaller.
This is the image added in code:
  render() {
    return (

        <Grid>

          //other elements
        </Grid>

    );
}

Playing with Developers tools I had discovered that if in Styles > element.style it is added: height: 10% the image size is shrunk to the desired size. Like here:

So how can this be done in code?
I added it like inline CSS but doesn't work:
  render() {
    return (

        <Grid>

          //other elements
        </Grid>

    );
}

Tried with saving it in a css file and import it with className='myClassName', same, no changes. The image has the original size.
How can this be done?

A: You might have a typo:
// not heigth

.imgClassName {
  height: 10%;
}

  <Grid>

  </Grid>


text:
Q: What is the design logic behind Fragments as static inner classes vs standalone public classes? I am not able to understand one important aspect of Android software design which I am just starting out with, from what I know Fragment design has been adopted in order to decouple the code, where the intuition is that the Activity remains as is and Fragment can be reused else where, maybe even in a different activity, or maybe along side other fragments, in something like a Master/Detail flow or landscape UI.
Okay so I have seen quite a handful of questions on SO asking as to why Fragments are placed as static inner classes within an Activity and the answer there is that if we do not make them static, the Fragment may hold a reference to the activity and something like a screen rotation or a re-draw might leak the activity or something.
This brings me back to square one and I have the question that, well, if the Fragment design has been adopted in order to decouple the code, then why are we marrying the Fragment to the Activity by putting it inside the activity class and not putting them as standalone public classes? Isn't that totally contradicting to the very existence of Fragments?
What is the down side of having a project structure as such? Where each Fragment is a separate class of its own? Given that my Fragment code can grow to like a 1000 lines especially when trying to do animations I am seeing this as far more neater, decoupled and reusable within activities other than it's intended parent Activity.

*

*Do we still suffer from the memory leak issue mentioned above?

*Am I missing something about the design logic? Please educate me.

*Is there a way where the Fragments stay as an inner class and still be used elsewhere? I might be missing something here as well... so do inform me.

Any other project design methods, concepts, corrections to my intuition are more than welcome since I am just starting out here, I would love to know all my options.
Thank you :)

A: I'd like to better know the logic against your idea; I make Fragments in their own class all the time, and my apps run like a rock during reorients. I do use an interface to speak to the managing Activity, use adapters to manage the Fragments, and perform basic accounting to ensure I'm not launching several background threads from re-loading.
So I check http://developer.android.com/guide/components/fragments.html
which is always worth a re-read, and whaddya know, the example at the bottom is just what you suggest, and I use every day: two public fragments in stand-alone classes that are attached to and by an activity.
If someone is really suggesting what you say, I suspect they are taking the line "A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle." way, way too literally; they mean embedded in the runtime.
gl hf!

A:
This brings me back to square one and I have the question that, well, if the Fragment design has been adopted in order to decouple the code, then why are we marrying the Fragment to the Activity by putting it inside the activity class and not putting them as standalone public classes? Isn't that totally contradicting to the very existence of Fragments?

The main driver for fragments isn't decoupling but rather composition: reusable pieces of user interface that can be easily composed together in different configurations. From composability follows modularity and from it decoupling so yes, decoupling is there but it's not the primary concern.
Read on about fragment design philosophy.
The modularity coin has another side: if two things belong together such as an activity and a fragment that is only used with that activity, they are best kept together and not spread out all over the codebase so they are easier to evolve together. A project structure like in your question where activities and fragments are in separate packages would not really follow this principle.
One commonly seen way to keep fragments in separate classes but close to related activities and such is to use a naming prefix so they sort together in alphabetical lists within the same package: e.g. FooActivity with FooDetailsFragment.
For simple fragments where there isn't that much code and the fragment is only used in one activity, it's perfectly fine to have them as static inner classes in that activity.
Just try to be consistent so other people reading the code can easily find their way around in the codebase and the WTFs/minute code metric is kept low.

Do we still suffer from the memory leak issue mentioned above?

No, the leak applies only to non-static inner classes that hold a reference to the outer class. Package-level classes do not have any outer class to held a reference to.
Since fragments share the hosting activity's lifecycle, leaking the outer object is not really the concern with fragments. It's just that the framework needs to be able to instantiate the fragments without any outer class objects, and static is a requirement for that.

Is there a way where the Fragments stay as an inner class and still be used elsewhere? I might be missing something here as well... so do inform me.

You can refer to public inner classes with the dot notation Outer.Inner in code or Outer$Inner with reflection (e.g. XML files).
While this is technically possible, doing so says you're relying on the internals of a class and that's a design smell. I'd really refer to inner classes in the outer class code itself.


text:
Q: Picasso - get path of loaded image I am using Picasso in my Android application to load images from URL. These images are displayed in some ListView. When user clicks on some item in this ListView, I need to create a sharing Intent with selected image.
I create sharing intent with this code:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(localPath));
shareIntent.putExtra(Intent.EXTRA_TEXT, mUrl);
shareIntent.setType("image/jpg");
startActivity(Intent.createChooser(shareIntent, getString(R.string.label_share)));

In code above, there is a local variable localPath. This variable has to contain path to image. I suppose that Picasso has some cache, where downloaded images are stored. Is there any way how can I retrieve the path of selected image?
UPDATE: Partial solution
Finally, I found a solution which works for me. But I do not know, if this is a correct solution or if better solution exists.
I created a class which implements com.squareup.picasso.Target interface and in method onBitmapLoaded(Bitmap bitmap, LoadedFrom from) I provided this implementation:
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
    mImageView.setImageBitmap(bitmap);
    mImageUri = getBitmapUri(bitmap, mName));
}

private Uri getBitmapUri(Bitmap bitmap, String title) {
     ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
     String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, title, null);
     return Uri.parse(path);
}

After that, I have mImageUri which I can pass to sharing intent. Maybe this part of code will be useful for someone.
But I don't know if better solution exist. In my solution I have to store Bitmap on disk, but maybe there is a same image on disk already, because Picasso loaded it. And also, I do not know if I have to delete image from MediaStore when I do not need it anymore.


text:
Q: Oracle SQL Query - where clause starting and end in certain values I just want to check whether my query is correct. I have written a simple query on one table and against a field in that table where we are looking for all rows where the value in that field is starting with a certain characters and ending in certain characters, but must not contain certain characters in that field's value. Thus -
           WHERE field_1 LIKE 'ABC%' AND field_1 LIKE '%XWY' AND field_1 NOT LIKE '%GHI12XY%'

The result is no rows, which is what we wanted, but I am not 100% sure whether the query is spot on and would like other whether this is correct

A: It looks correct to me. A good idea in all database software development is to create and load one or more test tables with rows that can be used to verify your logic. Then run your query against the test table(s) and see if you get the results you expect. Ideally, the rows in your test table will cover all the possibilities, for example, where you're supposed to get output, and where you're not supposed to get any.


text:
Q: PixelSearch occasionally not finding colours found by PixelGetColor I was trying to create a script which would perform an action when a colour is detected but experienced issues with PixelSearch.
I am using PixelSearch rather than matching with PixelGetColor as the colour is transparent and therefore requires PixelSearch Variation feature.
After experiencing issues with not finding a colour which was definitely there I tried to create a script to find a colour with PixelGetColor then pass it to PixelSearch and search for it with 0 variation.
This ensures that the colour was actually there, the script worked most of the time but frequently responded with ErrorLevel 1 (Not found which should be impossible).
I worked both on inactive and active windows but occasionally failed on both.
The script is posted below can anyone explain why this issue may be occurring
All test colours were static and not changing images with no transparency.
Why does this error occur and can it be fixed?
CoordMode, Pixel,Screen
CoordMode,Mouse,Screen

*$PGDN::
    MouseGetPos, PosX, PosY
    PixelGetColor, cRGB , %PosX%, %PosY%,RGB
    PixelGetColor, cBGR , %PosX%, %PosY%
    PixelSearch,Colour_SearchX,Colour_SearchY,PosX+10,PosY+10,PosX-10,PosY-10,cRGB,RGB Fast
    If ErrorLevel = 0
    {
        Search_Result:= "Found"
    }
    Else
    {
        Search_Result:= "Not Found"
    }
    MsgBox,% PosX ", " PosY "`nRGB: (" cRGB " ) - BGR: (" cBGR ")"  "`n" Search_Result ":" cRGB " at: " Colour_SearchX "," Colour_SearchY
Return

A: This code works the changes I made include
PixelSearch,Colour_SearchX,Colour_SearchY,PosX-10,PosY-10,PosX+10,PosY+10,cRGB,RGB Fast

This is because the search area numbers are wrong (X1,Y1 values are larger than X2,Y2)
CoordMode,Pixel,Screen
CoordMode,Mouse,Screen

*$PGDN::
    MouseGetPos, PosX, PosY
    PixelGetColor, cRGB , %PosX%, %PosY%,RGB
    PixelGetColor, cBGR , %PosX%, %PosY%
    PixelSearch,Colour_SearchX,Colour_SearchY,PosX-1,PosY-1,PosX+1,PosY+1,cRGB,50,RGB Fast

    If ErrorLevel = 0
    {
        Search_Result:= "Found"
    }
    Else
    {
        Search_Result:= "Not Found"
    }
    MsgBox,% PosX ", " PosY "`nRGB: (" cRGB " ) - BGR: (" cBGR ")"  "`n" Search_Result ":" cRGB " at: " Colour_SearchX "," Colour_SearchY
Return


text:
Q: GetIt not registering dependencies I am using GetIt (get_it: ^5.0.3) and have written a unit test to validate my usage. Each dependency is tested separately. All they do is test to see if the dependency is registered. The first three dependencies are registered. The remainder retrun false from the isRegestered function. The three successful ones are all testing dependencies that are imported from external packages. The remainder - the failing dependencies - are all classes developed as part of the project. Obviously this leads me to the conclusion that I am doing something fundamentally wrong. I know no other Flutter/Dart developers, so... Anyway, I am including the dependency injection/service locator file, the test thereof, and the code for the first failing class.
The dependency injection/service locator:
import 'package:get_it/get_it.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import 'core/network/network_info.dart';
import 'core/presentation/converter/input_converter.dart';
import 'features/schedule/data/repositories/pill_box_set_repository_impl.dart';
import 'features/schedule/data/datasources/pill_box_set_local_data_source.dart';
import 'features/schedule/data/datasources/pill_box_set_remote_data_source.dart';
import 'features/schedule/domain/repositories/pill_box_set_repository.dart';
import 'features/schedule/domain/usecases/get_pill_box_set.dart';
import 'features/schedule/presentation/bloc/pill_box_set_bloc.dart';

final sl = GetIt.instance;

Future<void> init() async {
  //! Features - Schedule
  // Bloc
  sl.registerFactory(() =>
      PillBoxSetBloc(
          pillBoxSetGetter: sl.get<GetPillBoxSet>(),
          inputConverter: sl.get<InputConverter>(),
      )
  );

  // Use cases
  sl.registerLazySingleton(() => GetPillBoxSet(sl.get<PillBoxSetRepository>()));

  // Repository
  sl.registerLazySingleton<PillBoxSetRepository>(() =>
      PillBoxSetRepositoryImpl(
          networkInfo: sl.get<NetworkInfo>(),
          localDataSource: sl.get<PillBoxSetLocalDataSource>(),
          remoteDataSource: sl.get<PillBoxSetRemoteDataSource>(),
      )
  );

  // Data sources
  sl.registerLazySingleton<PillBoxSetLocalDataSource>(
      () =>  PillBoxSetLocalDataSourceImpl(sharedPreferences: sl())
  );
  sl.registerLazySingleton<PillBoxSetRemoteDataSource>(
      () => PillBoxSetRemoteDataSourceImpl(client: sl.get<http.Client>())
  );

  //! Core
  sl.registerLazySingleton<InputConverter>(() => InputConverter());
  sl.registerLazySingleton<NetworkInfo>(() =>
      NetworkInfoImpl(sl.get<DataConnectionChecker>())
  );

  //! External
  final sharedPreferences = await SharedPreferences.getInstance();
  sl.registerLazySingleton<SharedPreferences>(() => sharedPreferences);
  sl.registerLazySingleton<http.Client>(() => http.Client());
  sl.registerLazySingleton<DataConnectionChecker>(() => DataConnectionChecker());
}

The test:
import 'package:data_connection_checker/data_connection_checker.dart';
import 'package:pusherman/core/presentation/converter/input_converter.dart';
import 'package:pusherman/features/schedule/data/datasources/pill_box_set_local_data_source.dart';
import 'package:pusherman/features/schedule/data/datasources/pill_box_set_remote_data_source.dart';
import 'package:pusherman/features/schedule/domain/repositories/pill_box_set_repository.dart';
import 'package:pusherman/features/schedule/domain/usecases/get_pill_box_set.dart';
import 'package:pusherman/features/schedule/presentation/bloc/pill_box_set_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test/test.dart';
import 'package:http/http.dart' as http;

import 'package:pusherman/core/network/network_info.dart';

import '../lib/service_locator.dart' as di;

void main() async {
  await di.init();

  group('is registered', () {
    test('DataConnectionChecker', () async {
      expect(di.sl.isRegistered<DataConnectionChecker>(), isTrue);
    });
    test('http.Client', () {
      expect(di.sl.isRegistered<http.Client>(), isTrue);
    });
    test('SharedPreferences', () {
      expect(di.sl.isRegistered<SharedPreferences>(), isTrue);
    });
    test('NetworkInfo', () async {
      expect(di.sl.isRegistered<NetworkInfo>(), isTrue);
    });
    test('InputConverter', () {
      expect(di.sl.isRegistered<InputConverter>(), isTrue);
    });
    test('PillBoxSetLocalDataSource', () {
      expect(di.sl.isRegistered<PillBoxSetLocalDataSource>(), isTrue);
    });
    test('PillBoxSetRemoteDataSource', () {
      expect(di.sl.isRegistered<PillBoxSetRemoteDataSource>(), isTrue);
    });
    test('PillBoxSetRepository', () {
      expect(di.sl.isRegistered<PillBoxSetRepository>(), isTrue);
    });
    test('GetPillBoxSet', () {
      expect(di.sl.isRegistered<GetPillBoxSet>(), isTrue);
    });
    test('PillBoxSetBloc', () {
      expect(di.sl.isRegistered<PillBoxSetBloc>(), isTrue);
    });

  });
}

The failing dependency:
import 'package:dartz/dartz.dart';

import '../../error/failure.dart';

class InputConverter {
  static final InputConverter _instance = InputConverter._();

  factory InputConverter() => _instance;

  InputConverter._() { }

  Either<Failure, int> toUnsignedInteger(String s) {
    try {
      var i = int.parse(s);
      if (i < 0) throw FormatException();
      return Right(i);
    } on FormatException {
      return Left(InvalidInputFailure());
    }
  }

  Either<Failure, String> toWordString(String s) {
    if (s == null) {
      return Left(InvalidInputFailure());
    }
    String trimmedString = s.trim();
    if (trimmedString.isEmpty) {
      return Left(InvalidInputFailure());
    }
    return Right(trimmedString);
  }
}

class InvalidInputFailure extends Failure {}

I have read the docs, searched and looked at Flutter GetIt Plugin - No type xxx is registered inside GetIt to no avail. I realize I am missing something fundamental.


text:
Q: Is there a way to make Maven warn or error on bad file extensions? IntelliJ defaults to locating a new Spock test in the java/ folder rather that the groovy/ folder, so we periodically wind up with groovy tests in our java directory, which are not run.
Is there an option in Maven, or in a plugin, to fail a build based upon the presence of a file with an unwanted extension?

A: The Maven Enforcer Plugin allows the writing of custom rules, which can applied to the build lifecycle. The plugin can be configured to fail on the first rule that does not pass.


text:
Q: Can we get native C++ code coverage in VS2012 or VS2010 without MSTest? We would like to measure code coverage for our own automated regression test system run over a fairly large native app. This is a sophisticated, scripted test system using the inbuilt scripting of our app. It has thousands of tests and is not going to be replaced by MSTest unit tests.
Whilst we're using VS2012 (Premium) as the IDE currently it is still compiled with the VS2010 compilers & libraries. That could change sooner if it was a prerequisite to getting code coverage going.
We can do separate builds for this - instrumenting is not a problem.
I'm just confused reading the MS documentation which seems to all start from an assumption you're running unit tests using their inbuilt test framework. That's when I'm not struggling to find stuff which actually talks about native support for ALM in the first place!
thanks

A: I realize this is an old post, but I believe the answer still is relevant.
With all the things that I used to have at my disposal in C#, I didn't really like what I saw when I moved to Visual C++. Also, like you the MSTests only partially worked for me; I'm used to have my own test applications as well.
Basically what I wanted was the following:

*

*Run MS tests or an EXE file

*Get code coverage right in Visual Studio.

After doing some research, I noticed that VS Enterprise supports this feature today with test adapters.
If you're not on VSE, I noticed there are some other tools, each providing users with an independent UI. Personally I don't like that; I want my coverage right in Visual Studio, preferably in Visual Studio Community edition.
So I decided to build this addin myself and - while it's not as sophisticated as VSE - it does the trick for me.

*

*I wrote a VSIX code coverage tool on https://github.com/atlaste/CPPCoverage . Basically it manages the highlighting in Visual Studio, generates a clickable report, and integrates in solution explorer.

*For the coverage measurements themselves, I used to use https://opencppcoverage.codeplex.com/ . Basically that allows you to perform code coverage tests on any debuggable (native) executable. Nowadays, I'm using my own code coverage measuring tools (which are open sourced above as well).

A: Visual Studio 2012's code coverage tool is entirely separate from the test execution system (full disclosure: I wrote it, but the team that inherited it after I left Microsoft removed some fairly useful functionality).  It was rewritten from the ground up in VS 2012 to dynamically instrument native (x86 and x86-64) and managed code (.NET and Silverlight) when it loads into the process instead of modifying executables on disk.
You can find CodeCoverage.exe in "%ProgramFiles%\Microsoft Visual Studio 11.0\Team Tools\Dynamic Code Coverage Tools".
To collect data:
CodeCoverage.exe collect /output:foo.coverage foo.exe foos_args

A configuration file (there's a default one in that directory called CodeCoverage.config) can be specified to control collection.
To analyze the coverage data, you can open foo.coverage in Visual Studio 2012 or use the coverage tool itself to do the analysis:
CodeCoverage.exe analyze /output:results.xml foo.coverage

Note: for instrumentation to take place, .pdb files must be discovered for your modules.  Since you are building with 2010, they may not work with 2012's DIA so you may have to rebuild with 2012's toolset.  If you are not seeing the modules you expect in the coverage analysis, pass /include_skipped_modules to the analyze command; there will be a "reason" attribute telling you why the module was skipped (excluded, no debug information, etc.).
Edit: Also, unlike previous versions of Visual Studio, 2012's coverage file format is completely self-contained.  The modules and .pdbs don't need to be present at analysis time.


text:
Q: Getting errors in including the WebView component in JavaFx and scene builder I am using Eclipse (javafx) and Scene Builder developing an app and I need to use a webview.
My program is working smoothly, but when I add a webview component into an anchor pane, I got this error.
Caused by: java.lang.ClassNotFoundException: javafx.scene.web.WebView
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at javafx.fxml/javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2931)
at javafx.fxml/javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2920)
at javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2861)
... 16 more
Exception running application view.Main

I tried to use the initialize function but still getting same errors, Can anyone tell me why?
Thanks in advance.

A: After i had this exact same error for a longtime, i solved adding the following arguments on eclipse>run>run configurations... then select the "Arguments" tab and add the text bellow to the "VM Arguments"
--module-path "%PHYSICAL_PATH_TO_JAVAFX%\lib" --add-modules javafx.controls,javafx.fxml,javafx.web
The main problem was that everywhere you go, they tell you to add the controls and fxml modules, but they never say that you may need to add more modules to those arguments. so i added the "javafx.web" and it solved my problem.


text:
Q: Реализуйте функцию minmax(), которая принимает как массив чисел, так и строк, без использования Math.max(), Math.min() Я новичок в JavaScript, только учусь. Помогите, пожалуйста.
Учитывая массив значений, функция minmax() должна вернуть массив, который содержит минимальное и максимальное значения в массиве, всегда с минимумом в индексе 0 и максимальным в индексе 1.
Использовать Math.max() или Math.min() нельзя.
Массив может быть списком строк в нижнем регистре вместо чисел. В этом случае min - это строка, которая будет отсортированная по алфавиту с начала, а max - строка, отсортированная по алфавиту с конца ("a" <"b", а "ab" > "aa" и т. д.).
Массивы смешанного типа (строки и числа) нас не интересуют.
function minmax(list) {

}

Примеры ожидаемого вывода:
console.log(minmax([1, 2, 3, 4, 5]));// returns [1, 5]
console.log(minmax([90, 89, 123, 3]))// returns [3, 123]
console.log(minmax(["apple", "banana", "canada"]));// returns ["apple", "canada"]
console.log(minmax([]));// returns [undefined, undefined]

Помогите, пожалуйста.

A:

function minmax(list) {
  var result = [list[0], list[0]];
  for (var i = 1; i < list.length; i++) {
    if (list[i] < result[0])
      result[0] = list[i];
    else if (list[i] > result[1])
      result[1] = list[i];
  }
  return result;
}

console.log(JSON.stringify(minmax([1, 2, 3, 4, 5])));// returns [1, 5]
console.log(JSON.stringify(minmax([90, 89, 123, 3])));// returns [3, 123]
console.log(JSON.stringify(minmax(["apple", "banana", "canada"])));// returns ["apple", "canada"]
console.log(minmax([]));// returns [undefined, undefined]


text:
Q: why does not focusManager work in Jetpack Compose? I am trying move focus from user textfield to password textfield with imeAction onNext and focusDirection.down, but the focus is cleared when I press the next button of the keyboard.
UI image
I show the code here:
val focusManager = LocalFocusManager.current
//we start to implement login screen UI-->
    LazyColumn(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        item {

        item {
            OutlinedTextField(

                value = emailValue.value,
                keyboardOptions = KeyboardOptions(
                    imeAction = ImeAction.Next,
                    keyboardType = KeyboardType.Password
                ),
                keyboardActions = KeyboardActions(
                    onNext ={
                        focusManager.moveFocus(FocusDirection.Down)
                    }

                ),

A: Set singleLine , please try
OutlinedTextField(
...
singleLine = true,
)

simple example
@Composable
fun Test() {
    val focusManager = LocalFocusManager.current
    var text1 by remember {
        mutableStateOf("")
    }
    LazyColumn() {
        items(2){
            OutlinedTextField(value = text1, onValueChange = {
                text1 = it
            },
                keyboardOptions = KeyboardOptions(
                    imeAction = ImeAction.Next,
                    keyboardType = KeyboardType.Text
                ),
                keyboardActions = KeyboardActions(
                    onNext ={
                        focusManager.moveFocus(FocusDirection.Down)
                    }
                ),
                singleLine = true
            )
        }
    }
}


text:
Q: how can i highlight my image view awhen user touching it?
Possible Duplicate:
Tasks with my UIImageView

How can i highlight my UIImageview and display a deleteButton(cross button) on top of the imageview when user touching the UIImageview?.

A: You need to create a IBAction that adds the cross button and wire it to the touchDown event in interface builder. You could probably make a timer that will give it a couple seconds before activating.
Option 2: read about gestureRecognizers, they are very simple and I learned them in a couple hours.
http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizers/GestureRecognizers.html <-- all about recogizers

A: It's pretty straight forward. Use

UILongPressGestureRecognizer

In the methods below write a code for detecting gestures and popping up a delete button.
- (void)handleGesture; //or
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;

For deleting use
- (void)removeTarget:(id)target action:(SEL)action


text:
Q: How to add archive file to release using github actions? I am trying to add an artifact file, and DEPLOY.md file from a sub directory to a release when triggered by pushing tag on github actions.
Here is my code for the work flow
---
name: Module Three Task Three
on:
   push:
   schedule:
      - cron: '0 0 * * *'
jobs:
   Explore-GitHub-Actions:
      runs-on: ubuntu-latest
      steps:
         - name: Checkout
           uses: actions/checkout@v2
         - name: Clone
           run: |
              git clone https://github.com/mittsahl/validation
         - name: Hugo
           run: |
              brew install hugo
         - name: Create package
           run: |
              cd validation/module3_task3
              make build
              make package
         - name: Archive artifacts
           uses: actions/upload-artifact@v2
           with:
             path: |
               validation/module3_task3/awesome-website.zip
         - name: Release
           uses: softprops/action-gh-release@v1
           if: startsWith(github.ref, 'refs/tags/')
           with:
            files: |
              DEPLOY.md
              awesome-website.zip

The zip file awesome-website.zip and DEPLOY.md are in the directory validation/module3_task3/.
I can create the release on the push of a tag and the archive of awesome-website.zip, but it just gives me a zip file of the entire repo in the release.  What I want is only the DEPLOY.md and artifact or awesome-website.zip file.  When I look in the github actions it gives me the message
Run softprops/action-gh-release@v1
 Pattern 'DEPLOY.md' does not match any files.
 Pattern 'awesome-website.zip' does not match any files.
 Creating new GitHub release for tag 1.0.0...
 Release ready at https://github.com/mittsahl/validation/releases/tag/1.0.0
 DEPLOY.md,awesome-website.zip not include valid file.

I have tried giving it the full path to those files each without any success.  Any input would be greatly appreciated.  Thank you


text:
Q: Why are randomly drawn vectors nearly perpendicular in high dimensions I am struggling understanding this finding. Can somebody explain intuitively why randomly drawn high-dimensional vectors will tend to be mutually orthogonal? I realize that intuition in high dimensions might be too much to ask for, still, an explanation without having to integrate over several pages of symbols would be preferred.

A: Here's an excerpt from Lecture 2 of Keith Ball's An Elementary Introduction to Modern Convex Geometry:

See the link for details, but as the image shows, the measure of a spherical cap cut off by a hyperplane which is $\varepsilon$ away from the origin is bounded above by the ratio between volume of a ball of radius $\sqrt{1-\varepsilon^2}$ and the volume of a ball of radius 1, that is, $(1-\varepsilon^2)^{n/2}$.  So if $X$ and $Y$ are independent random unit vectors (uniform on the sphere), then the portion of the cap area is
$$ P(\langle X,Y\rangle > \varepsilon) \le (1-\varepsilon^2)^{n/2} \le e^{-n\varepsilon^2/2} $$
which is close to $1$ when $n$ is large (if $\varepsilon$ is fixed, at least).

A: A random uniform unit vector is $X/\|X\|$ where $X$ is standard normal, thus the scalar product of two independent unit vectors $U$ and $V$ is $\langle U,V\rangle=\langle X,Y\rangle/(\|X\|\cdot\|Y\|)$ where $X$ and $Y$ are independent and standard normal. When $n\to\infty$, by the law of large numbers, $\|X\|/\sqrt{n}\to1$ almost surely and $\|Y\|/\sqrt{n}\to1$ almost surely, and by the central limit theorem, $\langle X,Y\rangle/\sqrt{n}$ converges in distribution to a standard one-dimensional normal random variable $Z$.
Thus, $\sqrt{n}\cdot\langle U,V\rangle\to Z$ in distribution, in particular, for every $\varepsilon\gt0$, $P(|\langle U,V\rangle|\geqslant\varepsilon)\to0$. In this sense, when $n\to\infty$, the probability that $U$ and $V$ are nearly orthogonal goes to $1$.
Likewise, $k$ independent uniform unit vectors are nearly orthogonal with very high probability when $n\to\infty$, for every fixed $k$.

A: In statistics orthogonality is deeply linked to correlation. Random vectors are orthogonal when the values they contain are uncorrelated, meaning that in the $x_i$ values of $\vec{v_1}$ and $\vec{v_2}$ do not appear common patterns. The higher the dimension is the higher is $i$ and so the probability is higher that $x_{i}$ value of $\vec{v_1}$ and the $x_i$ values of $\vec{v_2}$ have no common pattern, because the higher the dimension the higher the possibilities (in an urn problem increase the number of balls ...). Equivalent to the statement that $\vec{v_1}$ and $\vec{v_2}$ have no common patterns is the statement that they are uncorrelated what is equivalent to the statement that they are orthogonal.
So the key to understand why randomly drawn vectors are perpendicular in high dimensions is the deep link between orthogonality and statistical correlation :
https://stats.stackexchange.com/questions/171324/what-is-the-relationship-between-orthogonal-correlation-and-independence
This is linked to a more philosophical question if real randomness actually exists. There are strong hints that this is not the case, i.e. nonlinear dynamical systems (chaotic systems) are able to generate white noise in a deterministic way :
https://ieeexplore.ieee.org/document/1236865 - Chaotic maps generating white noise

A: Here is one way to reason, chosen for simplicity of calculations: Consider the unit vector $e=(1,0,0,\ldots,0)\in\mathbb R^n$. One way to measure how 'orthogonal' $e$ is to other vectors is to calculate the average of $(e\cdot x)^2$ as $x$ ranges over the unit sphere. If $S$ denotes the surface measure on the unit sphere corresponding to (normalized) area, then
$$
\int |e\cdot y|^2 dS(y) =\int |y_1|^2 dS(y)=\frac{1}{n}\int \sum_{j=1}^n |y_j|^2 dS(y)=\frac{1}{n}.
$$
Thus, in this sense, vectors are generally 'more' orthogonal in higher dimensional spaces.
Edit: This line of reasoning follows closely the argument given by JyrkiLahtonen in the comments above, as one sees by considering a random $\mathbb R^n$-valued vector $Y$, uniformly distributed on the unit sphere. If we consider the random variable $e\cdot Y$, then
$$
E \; e\cdot Y=\int e\cdot y \;dS(y)=0,
$$
because $S$ in invariant under the transformation $y\mapsto -y$. On the other hand
$$
V(e\cdot Y)=\int |e\cdot y|^2 dS(y) =\frac{1}{n},
$$
as shown above. Therefore, intuitively, $e\cdot Y$ is small when $n$ is large. Rigorously, we can employ Chebyshev's inequality to obtain
$$
P(|e\cdot Y|\geq \epsilon)\leq \frac{1}{n\epsilon^2}.
$$

A: For intuition let us reframe asking why some vector is orthogonal to most others as, why is some random vector almost orthogonal to most standard basis vectors?
Now the unit vector which is in some sense least orthogonal to every basis vector is
$$\tfrac1{\sqrt{d}}(1, \dots, 1).$$
Notice how we have to make this vector more orthogonal in some basis $e_i$ if we want to make it less orthogonal for some other basis $e_j$. Therefore the total "orthogonalness" stays the same. So if we do not concentrate our values in some dimensions, all of them will decrease at rate roughly $\frac1{\sqrt{d}}$ with the dimension. And this is the result proven by the accepted answer

A: As the brief proof showed below, it does not matter to suppose that the vector c is the diagonal vector of the n vector from the standard basis in the n-dimensional vector space with inner-product. It means that the projection vector of c onto vi is the same length(norm) with each other (irrelevant to i). Any randomly drawn vector is the same as c.


text:
Q: How to add dot on C numbers I have function ticketVipCounter to calculate prices
int ticketVipCounter( int ticketVip ){
    return ticketVip * 250000;
}

printf("Prices Is: %d", ticketVipCounter(4));

If i run the code,
The result will be 1000000
How do i change the code so the result will be 1.000.000, any idea?, Thankyou

A: See this similar question:
How to format a number from 1123456789 to 1,123,456,789 in C?
It looks like if your printf supports POSIX 2008, you can set a locale and use the ' flag.
#include <stdio.h>
#include <locale.h>

int main(void)
{
    setlocale(LC_NUMERIC, "");
    printf("%'d\n", 1123456789);
    return 0;
}


text:
Q: set div position to overlay another div I am trying to set an overlay panel on a container on click of some button. Container gets hidden/shown on click of an arrow image button but the problem is the position is getting changed. I want to set middle div in center and it should not move.
JQuery ::
    $('#slickbox').hide();
$('#slick-slidetoggle').click(function() {
    $('#slickbox').show('slide', 400);
    return false;
});
$('#close').click(function() {
    $('#slickbox').hide('slide', 400);
    return false;
});

CSS
#middle_panel {
    position:relative;
    padding: 5px;
    margin-left: auto;
    margin-right: auto;
    /*padding-top:;*/
    margin-top:80px;
    border: solid 1px red;
    text-align: center;
    background-color: #D0D0D0;
    height: 500px;
    width: 48%;
    margin-left: 28%;
}

#slidingpanel {
    position :relative;
    border: solid 1px red;
    text-align: center;
    background-color: yellow;
    height: 500px;
    width: 1%;
    float:left;
    word-break: break-all
}

#slickbox {
    background: #EEE;
    border: 1px solid #900;
    height: 135px;
    display: none;
}

HTML :

    This is the box that will be shown and hidden and toggled at your whim. :)
     close

A: If you want to put a div inside another div or any other element, you have to set the position of the parent as relative and the child as absolute. I rewrote your html code as follow:

    <title></title>

This is the box that will be shown and hidden and toggled at your whim. :)

     close


text:
Q: Java applet embedded in HTML hangs the browser when sends email I'm trying to make a website that sends me an email when someone opens it. It's stored locally, so I can't use php. I decided to go with Java applet and after much work (Firefox has some serious issues with applets) it almost works. Applet is fully loaded, initialized, started and reacts to a html button.
I'm using Javamail 1.4.4 and what happens is that Firefox and Opera (both browsers react in the same way) hang and after about 20 seconds they work normally again but mail is not sent. This is the stack trace:
DEBUG: setDebug: JavaMail version 1.4.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
network: Cache entry not found [url: http://smtp.gmail.com/crossdomain.xml, version: null]
network: Connecting http://smtp.gmail.com/crossdomain.xml with proxy=DIRECT
network: Connecting http://smtp.gmail.com:80/ with proxy=DIRECT
java.security.PrivilegedActionException: java.net.ConnectException: Connection timed out: connect
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.net.CrossDomainXML.check(Unknown Source)
    at com.sun.deploy.net.CrossDomainXML.check(Unknown Source)
    at sun.plugin2.applet.SecurityManagerHelper.checkConnectHelper(Unknown Source)
    at sun.plugin2.applet.AWTAppletSecurityManager.checkConnect(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getByName(Unknown Source)
    at java.net.InetSocketAddress.<init>(Unknown Source)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
    at javax.mail.Service.connect(Service.java:295)
    at mai.Mai$1.run(Mai.java:66)
    at mai.Mai$1.run(Mai.java:42)
    at java.security.AccessController.doPrivileged(Native Method)
    at mai.Mai.send(Mai.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.<init>(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at com.sun.deploy.net.CrossDomainXML$2.run(Unknown Source)
    ... 39 more
java.security.AccessControlException: access denied ("java.net.SocketPermission" "smtp.gmail.com" "resolve")
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkConnect(Unknown Source)
    at sun.plugin2.applet.SecurityManagerHelper.checkConnectHelper(Unknown Source)
    at sun.plugin2.applet.AWTAppletSecurityManager.checkConnect(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getByName(Unknown Source)
    at java.net.InetSocketAddress.<init>(Unknown Source)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
    at javax.mail.Service.connect(Service.java:295)
    at mai.Mai$1.run(Mai.java:66)
    at mai.Mai$1.run(Mai.java:42)
    at java.security.AccessController.doPrivileged(Native Method)
    at mai.Mai.send(Mai.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
    at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
    at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

and this is the code of my applet (I read somewhere that I should use doPrivileged() but it seems to not make a difference in the stack trace):
package mai;

import java.applet.Applet;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mai extends Applet{

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final int SMTP_HOST_PORT = 465;
    private static final String SMTP_AUTH_USER = "myMail@gmail.com";
    private static final String SMTP_AUTH_PWD = "myPassword";

    @Override
    public void init(){
        System.out.println("init");
    }

    public void send(){
        System.out.println("send");

        AccessController.doPrivileged(new PrivilegedAction<String>() {

                @Override
                public String run() {
                     try{

                        Properties props = new Properties();

                        props.put("mail.transport.protocol", "smtps");
                        props.put("mail.smtps.host", SMTP_HOST_NAME);
                        props.put("mail.smtps.auth", "true");
                        // props.put("mail.smtps.quitwait", "false");

                        Session mailSession = Session.getDefaultInstance(props);
                        mailSession.setDebug(true);
                        Transport transport = mailSession.getTransport();

                        MimeMessage message = new MimeMessage(mailSession);
                        message.setSubject("Testing SMTP-SSL");
                        message.setContent("This is a test", "text/plain");

                        message.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("myMaill@gmail.com"));

                        transport.connect
                          (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

                        transport.sendMessage(message,
                            message.getRecipients(Message.RecipientType.TO));
                        transport.close();
                    }catch(Exception e){

                        e.printStackTrace();
                    }finally{
                         return "send";
                     }
                }
            });

    }
}

I also read that I could sign my applet but it would invoke a pop-up every time my applet loads, which is not an option as it must be a little bit hidden.
Any ideas what I'm doing wrong?
(If You think using an applet here is too complicated, please show me a better way. From what I know JavaScript can't send email, I don't have a server so I can't use php or something like node.js and all other libraries which send information require login from the user).

A: Welcome to the club of malicious code writers (where malicious includes tracking). You are running afoul of the same-origin policy of browsers w.r.t. new network connections, meaning that the only place you can connect to without requiring signing is the host that served the original page.


text:
Q: Ubuntu 10.10 as guest VMware on Windows7 64-bit - really slow internet - how do I speed it up? I may have my terminology wrong here but bear with me:

*

*Running Kubuntu 10.10 in VMware player on Windows 7 64-bit host

*When I load something on the internet (eg. web browser page load, git pull / push) there is a pregnant pause of at least 5 to 10 seconds, a though the VM is having trouble getting out onto the internet and is performing some sort of lookup. You can clearly see that for example if you load Facebook, it will do the lookup for facebook.com, pause, get it, and then pause again when it does a separate lookup for the cdn the images are hosted on for facebook.

Is there some settings I can play with to speed this up?

A: This sounds like a DNS issue as opposed to a VMWare issue.  The network is obviously working as you can get out to the internet (albeit with delays).
Check what is in /etc/resolv.conf on the guest and ensure that you can reach all the nameserver machines listed in there.


text:
Q: Looking for an open-source PHP e-commerce system that supports a number of features I would like it to have the following features:

*

*Supports multiple languages

*Allows admin to define a discount
period on a number of products

*Allows members to register, login,
add products to shopping cart and buy
them (probably all e-commerce system
support this)

*Members can pay by paypal

*Having a contact us page (with a
working contact form)

*Products can be searched by users

*On each product detail page, there is
an "Email to your friend" function.
What are the PHP open-source e-commerce systems that you know of, supports all/most of the features mentioned above?
Many many thanks to you all.

A: Check out OpenCart, features list here: http://www.opencart.com/index.php?route=feature/feature
It appears to support most of what you requested, and there will be extensions for that of which it doesn't support by default.
To be completely honest with you, the open-source eCommerce solutions are virtually non-existent, or where they are, not very good. opencart is the best I've used so far, and quite surprisingly it's very nice.

A: Magento  http://www.magentocommerce.com/


text:
Q: matplotlib get rid of max_open_warning output I wrote a script that calls functions from QIIME to build a bunch of plots among other things.  Everything runs fine to completion, but matplotlib always throws the following feedback for every plot it creates (super annoying):

/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py:412: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_num_figures).
    max_open_warning, RuntimeWarning)

I found this page which seems to explain how to fix this problem , but after I follow directions, nothing changes:
import matplotlib as mpl
mpl.rcParams[figure.max_open_warning'] = 0

I went into the file after calling matplotlib directly from python to see which rcparams file I should be investigating and manually changed the 20 to 0.  Still no change.  In case the documentation was incorrect, I also changed it to 1000, and still am getting the same warning messages.
I understand that this could be a problem for people running on computers with limited power, but that isn't a problem in my case.  How can I make this feedback go away permanently?

A: Try setting it this way:
import matplotlib as plt
plt.rcParams.update({'figure.max_open_warning': 0})

Not sure exactly why this works, but it mirrors the way I have changed the font size in the past and seems to fix the warnings for me.

A: Another way I just tried and it worked:
import matplotlib as mpl
mpl.rc('figure', max_open_warning = 0)

A: Check out this article which basically says to plt.close(fig1) after you're done with fig1. This way you don't have too many figs floating around in memory.

A: When using Seaborn you can do it like this
import seaborn as sns
sns.set_theme(rc={'figure.max_open_warning': 0})

A: In Matplotlib, figure.max_open_warning is a configuration parameter that determines the maximum number of figures that can be opened before a warning is issued. By default, the value of this parameter is 20. This means that if you open more than 20 figures in a single Matplotlib session, you will see a warning message. You can change the value of this parameter by using the matplotlib.rcParams function. For example:
import matplotlib.pyplot as plt
plt.rcParams['figure.max_open_warning'] = 50

This will set the value of figure.max_open_warning to 50, so that you will see a warning message if you open more than 50 figures in a single Matplotlib session.


text:
Q: RecyclerView shuffling items images I'm new to android and I wanted to create a chat in my app, it's like a global roomchat based on firebase. Messages are displayed via RecyclerView and the problem is that when it's loaded the images of people, their names are somehow mixed up. When I go back to previous activity and open the chat activity again everything becomes OK. But the when a new message is added the rows shuffle again. I'm sure that it should be very ease to fix, but I can't...Please help. Thank you!

This is the chat activity oncreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_chat);

    main_recycler_view = (RecyclerView) findViewById(R.id.messages_list);
    main_recycler_view.setVisibility(View.GONE);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    progressBar.setVisibility(View.VISIBLE);
    mAuth = FirebaseAuth.getInstance();

    if (mAuth.getCurrentUser() != null) {

        mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());

    }
    FirebaseUser currentUser = mAuth.getCurrentUser();

    if (currentUser == null) {

        sendToStart();

    } else {

        mUserRef.child("online").setValue("true");
        String transp = "https://firebasestorage.googleapis.com/v0/b/chatqs-a4c10.appspot.com/o/profile_images%2Ftransp.png?alt=media&token=fc7b2315-f24b-453a-926e-364fff55e31b";
        mUserRef.child("version").setValue(transp);

        mToolbar = (Toolbar) findViewById(R.id.chattb);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(R.string.chat_title);

        imageButton_send = (Button) findViewById(R.id.chat_send_btn);
        editText_message = (EditText) findViewById(R.id.chat_message_view);

        database = FirebaseDatabase.getInstance();
        databaseRef = database.getReference();
        mContext = (MainChatPage.this);

        adapter = new MainAdapter(mContext, messageArrayList);
        main_recycler_view.setAdapter(adapter);

        main_recycler_view.setLayoutManager(new LinearLayoutManager(c));

        databaseRef.child("the_messages").limitToLast(50).addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                progressBar.setVisibility(View.GONE);
                main_recycler_view.setVisibility(View.VISIBLE);
                final Message new_message = dataSnapshot.getValue(Message.class);

                final String userid = dataSnapshot.child("userID").getValue().toString();

                mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

                final String current_uid = mCurrentUser.getUid();
                mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
                mDatabase.addValueEventListener(new ValueEventListener() {

                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if (dataSnapshot.child(userid).exists()) {

                            messageArrayList.remove(new_message);

                        }
                        adapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
                main_recycler_view.scrollToPosition(adapter.getItemCount() - 1);
                messageArrayList.add(new_message);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }

        });

My adapter:
public MainAdapter(MainChatPage context, ArrayList<Message> data) {
    this.data = data;
    this.mContext = context;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_single_layout, null);
    message_profile_layout = (CircleImageView) view.findViewById(R.id.message_profile_layout);

    MyViewHolder viewHolder = new MyViewHolder(view);

    return viewHolder;
}

@Override
public void onBindViewHolder(final MyViewHolder myViewHolder, final int i) {

    final Message message = data.get(i);
    final String userid = message.getUserID();
    mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

    final String current_uid = mCurrentUser.getUid();
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
    mDatabase.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
            mUserDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    String thumb = dataSnapshot.child("thumb_image").getValue().toString();
                    String nome = dataSnapshot.child("name").getValue().toString();
                    String dialog_name = nome;
                    String vers = dataSnapshot.child("version").getValue().toString();
                    //String proic = "https://firebasestorage.googleapis.com/v0/b/chatqs-a4c10.appspot.com/o/profile_images%2Ficonfinder-pro-icon-icon.png?alt=media&token=1ca05e32-f3e7-4f73-af54-2be17ad0fed6";

                //    Picasso.with(myViewHolder.mes_proicon.getContext()).load(proic)
                //            .placeholder(R.drawable.transp).into(myViewHolder.mes_proicon);
                //                        myViewHolder.name_text_layout.setText(nome);
                    Picasso.with(myViewHolder.message_profile_layout.getContext()).load(thumb)
                            .placeholder(R.drawable.default_avatar).into(myViewHolder.message_profile_layout);
                    Picasso.with(myViewHolder.mes_proicon.getContext()).load(vers)
                               .placeholder(R.drawable.transp).into(myViewHolder.mes_proicon);
                                            myViewHolder.name_text_layout.setText(nome);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
            String formatted_date = SCUtils.formatted_date(message.getTimestamp());

            myViewHolder.message_text_layout.setText(Html.fromHtml(message.getMessage()));

            myViewHolder.time_text_layout.setText(Html.fromHtml(formatted_date));

            myViewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (!userid.equals(current_uid)) {

                        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

                        LayoutInflater inflater = mContext.getLayoutInflater();
                        View dialogView = inflater.inflate(R.layout.dialog, null);
                        TextView dialog_name = (TextView) dialogView.findViewById(R.id.dialog_name);
                        CircleImageView dialog_icon = (CircleImageView) dialogView.findViewById(R.id.dialog_icon);

                        builder.setView(dialogView);
                        dialog_name.setText(myViewHolder.name_text_layout.getText());
                        dialog_icon.setImageDrawable(myViewHolder.message_profile_layout.getDrawable());

                        builder.setPositiveButton(R.string.block, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
                                mDatabase.child(userid).push().setValue("");
                            }
                        })
                                .setNegativeButton(R.string.open_profile, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        Intent chatIntent = new Intent(mContext, UserProfileActivity.class);
                                        chatIntent.putExtra("user_id", userid);

                                        mContext.startActivity(chatIntent);
                                        mContext.finish();
                                    }
                                });

                       builder.show();

                    } else {
                        Intent Intent = new Intent(mContext, ProfileFragment.class);

                        mContext.startActivity(Intent);
                        mContext.finish();
                    }
                }

            });
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
@Override
public int getItemCount() {
    return data.size();

}
  public class MyViewHolder extends RecyclerView.ViewHolder {
  View mView;

  protected TextView message_text_layout;
protected TextView name_text_layout;
protected TextView time_text_layout;

    protected CircleImageView message_profile_layout;
protected CircleImageView mes_proicon;

public MyViewHolder(View itemView) {
    super(itemView);

    mView = itemView;

  this.message_text_layout = (TextView) mView.findViewById(R.id.message_text_layout);
  this.name_text_layout = (TextView) mView.findViewById(R.id.name_text_layout);
  this.time_text_layout = (TextView) mView.findViewById(R.id.time_text_layout);
  this.mes_proicon = (CircleImageView) mView.findViewById(R.id.mes_proicon);

  this.message_profile_layout = (CircleImageView) mView.findViewById(R.id.message_profile_layout);

}
}

A: just remove .placeholder. I dont know why but sometimes it happens because of this method


text:
Q: Share a photo on user's facebook profile on iOS I'm trying to share a photo from my app to facebook, exactly like Instagram does by toggling on "Share on facebook", where the user result in having a beautiful large photo on his wall.
I followed exactly the "Custom Stories with Open Graph" tutorial on Facebook at:
https://developers.facebook.com/docs/ios/open-graph
I even downloaded Facebook's sample project on iOS that follows the tutorial code. I copied this code and replaced the namespace, action and object with mine. Here's the code:
// stage an image
  [FBRequestConnection startForUploadStagingResourceWithImage:image completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    if(!error) {
      NSLog(@"Successfuly staged image with staged URI: %@", [result objectForKey:@"uri"]);

      // instantiate a Facebook Open Graph object
      NSMutableDictionary<FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];

      // specify that this Open Graph object will be posted to Facebook
      object.provisionedForPost = YES;

      // for og:title
      object[@"title"] = @"Roasted pumpkin seeds";

      // for og:type, this corresponds to the Namespace you've set for your app and the object type name
      object[@"type"] = @"fbogsample:dish";

      // for og:description
      object[@"description"] = @"Crunchy pumpkin seeds roasted in butter and lightly salted.";

      // for og:url, we cover how this is used in the "Deep Linking" section below
      object[@"url"] = @"http://example.com/roasted_pumpkin_seeds";

      // for og:image we assign the uri of the image that we just staged
      object[@"image"] = @[@{@"url": [result objectForKey:@"uri"], @"user_generated" : @"false" }];

      // Post custom object
      [FBRequestConnection startForPostOpenGraphObject:object completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        if(!error) {
          // get the object ID for the Open Graph object that is now stored in the Object API
          NSString *objectId = [result objectForKey:@"id"];
          NSLog(@"object id: %@", objectId);

          // create an Open Graph action
          id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
          [action setObject:objectId forKey:@"dish"];

          // create action referencing user owned object
          [FBRequestConnection startForPostWithGraphPath:@"/me/fbogsample:eat" graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
            if(!error) {
              NSLog(@"OG story posted, story id: %@", [result objectForKey:@"id"]);
              [[[UIAlertView alloc] initWithTitle:@"OG story posted"
                                          message:@"Check your Facebook profile or activity log to see the story."
                                         delegate:self
                                cancelButtonTitle:@"OK!"
                                otherButtonTitles:nil] show];
            } else {
              // An error occurred, we need to handle the error
              // See: https://developers.facebook.com/docs/ios/errors
              NSLog(@"Encountered an error posting to Open Graph: %@", error.description);
            }
          }];

        } else {
          // An error occurred, we need to handle the error
          // See: https://developers.facebook.com/docs/ios/errors
          NSLog(@"Encountered an error posting to Open Graph: %@", error.description);
        }
      }];

    } else {
      // An error occurred, we need to handle the error
      // See: https://developers.facebook.com/docs/ios/errors
      NSLog(@"Error staging an image: %@", error.description);
    }
  }];

Here's the log:

The problem is, the posts never makes it to my wall, even though the object appears created in the Objects Browser. Going to my app dashboard on developers.facebook.com and open graph, I see the story exists, but no stories have been shared even though the app says so.
What's wrong ? Help, please!


text:
Q: Trigger drone tag event with api? I'm using the drone downstream plugin and it doesn't appear to be able to trigger a tag event in the downstream repo, only push. From there I was looking into the drone api to determine if I can hit the api to trigger a tag, but I'm not seeing it in docs or drone-go code. I'm afraid I'm missing it somewhere obvious, anyone know if you can trigger tag event in drone through api?
drone downstream plugin config:
pipeline:
trigger:
  when:
    event: [push, tag]
    branch: master
  image: plugins/downstream
  server: https://drone6.company.com
  fork: true
  repositories:
    - org/cars-v1
  secrets: [ downstream_token ]