text:
Q: "Indentation size" disabled in Eclipse XML plugin When I edit XML files in eclipse, I want tabs to be 4 spaces. I know where to go to change this, but the option is disabled. See the attached screenshot.

How do I make it let me set that to 4?

A: You can make it simple: set cursor left of the number and scroll the wheel =) It works. Checked.

A: If you are on Linux or Mac, try
eclipse --launcher.GTK_version 2
It could be a GTK 3 bug.
In any case, you can edit .metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs and place indentationSize=4 there. Better to do so when Eclipse is closed.


text:
Q: merging dataframe does not give any result with inner join I have 2 dataframe namely accidents_data which has 15 columns and bad_air_quality_districts dataframe whch has 2 columns.[accidents_data image[][1]][bad_air_quality_districts]
now i want to join both dataframes on column 'District Name' and finally keep only the data from accidents_data whose districts name matches with the district name of bad_air_quality_districts.

I tried merging both the dataframes using the below line but it does not show any results.
enter code here
pd.merge(accidents_data, bad_air_quality_districts, on='District Name', how='inner')

Kindly advise!

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSString property: copy or retain? Let's say I have a class called SomeClass with a string property name:
@interface SomeClass : NSObject
{
    NSString* name;
}

@property (nonatomic, retain) NSString* name;

@end

I understand that name may be assigned a NSMutableString in which case this may lead to errant behavior.

*

*For strings in general, is it always a good idea to use the copy attribute instead of retain?

*Is a "copied" property in any way less efficient than such a "retain-ed" property?

A:
For strings in general, is it always a good idea to use the copy attribute instead of retain?

Yes - in general always use the copy attribute.
This is because your NSString property can be passed an NSString instance or an NSMutableString instance, and therefore we can not really determine if the value being passed is an immutable or mutable object.

Is a "copied" property in any way less efficient than such a "retain-ed" property?

*

*If your property is being passed an NSString instance, the answer is "No" - copying is not less efficient than retain.
(It's not less efficient because the NSString is smart enough to not actually perform a copy.)

*If your property is passed an NSMutableString instance then the answer is "Yes"  - copying is less efficient than retain.
(It's less efficient because an actual memory allocation and copy must occur, but this is probably a desirable thing.)

*Generally speaking a "copied" property has the potential to be less efficient - however through the use of the NSCopying protocol, it's possible to implement a class which is "just as efficient" to copy as it is to retain. NSString instances are an example of this.

Generally (not just for NSString), when should I use "copy" instead of "retain"?

You should always use copy when you don't want the internal state of the property changing without warning. Even for immutable objects - properly written immutable objects will handle copy efficiently (see next section regarding immutability and NSCopying).
There may be performance reasons to retain objects, but it comes with a maintenance overhead - you must manage the possibility of the internal state changing outside your code. As they say - optimize last.

But, I wrote my class to be immutable - can't I just "retain" it?

No - use copy. If your class is really immutable then it's best practice to implement the NSCopying protocol to make your class return itself when copy is used. If you do this:

*

*Other users of your class will gain the performance benefits when they use copy.

*The copy annotation makes your own code more maintainable - the copy annotation indicates that you really don't need to worry about this object changing state elsewhere.

A: For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify copy in your @property declaration.  Specifying retain is something you almost never want in such a situation.
Here's why you want to do that:
NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];

Person *p = [[[Person alloc] init] autorelease];
p.name = someName;

[someName setString:@"Debajit"];

The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, but @"Chris" if the property is marked copy.
Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy.  (And if you write the setter yourself instead of using @synthesize you should remember to actually use copy instead of retain in it.)

A: I try to follow this simple rule:

*

*Do I want to hold on to the value of the object at the point in time when I am assigning it to my property? Use copy.

*Do I want to hold on to the object and I don't care what its internal values currently are or will be in the future? Use strong (retain).
To illustrate: Do I want to hold on to the name "Lisa Miller" (copy) or to I want to hold on to the person Lisa Miller (strong)? Her name might later change to "Lisa Smith", but she will still be the same person.

A: Surely putting 'copy' on a property declaration flies in the face of using an object-oriented environment where objects on the heap are passed by reference - one of the benefits you get here is that, when changing an object, all references to that object see the latest changes. A lot of languages supply 'ref' or similar keywords to allow value types (i.e. structures on the stack) to benefit from the same behaviour. Personally, I'd use copy sparingly, and if I felt that a property value should be protected from changes made to the object it was assigned from, I could call that object's copy method during the assignment, e.g.:
p.name = [someName copy];

Of course, when designing the object that contains that property, only you will know whether the design benefits from a pattern where assignments take copies - Cocoawithlove.com has the following to say:
"You should use a copy accessor when the setter parameter may be mutable but you can't have the internal state of a property changing without warning" - so the judgement as to whether you can stand the value to change unexpectedly is all your own. Imagine this scenario:
//person object has details of an individual you're assigning to a contact list.

Contact *contact = [[[Contact alloc] init] autorelease];
contact.name = person.name;

//person changes name
[[person name] setString:@"new name"];
//now both person.name and contact.name are in sync.

In this case, without using copy, our contact object takes the new value automatically; if we did use it, though, we'd have to manually make sure that changes were detected and synced. In this case, retain semantics might be desirable; in another, copy might be more appropriate.

A: Through this example copy and retain can be explained like:
NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];

Person *p = [[[Person alloc] init] autorelease];
p.name = someName;

[someName setString:@"Debajit"];

if the property is of type copy then ,
a new copy will be created for the [Person name] string that will hold the contents of someName string. Now any operation on someName string will have no effect on [Person name].
[Person name] and someName strings will have different memory addresses.
But in case of retain,
both the [Person name] will hold the same memory address as of somename string, just the retain count of somename string will be incremented by 1.
So any change in somename string will be reflected in [Person name] string.

A: Copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).

A: @interface TTItem : NSObject
@property (nonatomic, copy) NSString *name;
@end

{
    TTItem *item = [[TTItem alloc] init];
    NSString *test1 = [NSString stringWithFormat:@"%d / %@", 1, @"Go go go"];
    item.name = test1;
    NSLog(@"-item.name: point = %p, content = %@; test1 = %p", item.name, item.name, test1);
    test1 = [NSString stringWithFormat:@"%d / %@", 2, @"Back back back"];
    NSLog(@"+item.name: point = %p, content = %@, test1 = %p", item.name, item.name, test1);
}

Log:
    -item.name: point = 0x9a805a0, content = 1 / Go go go; test1 = 0x9a805a0
    +item.name: point = 0x9a805a0, content = 1 / Go go go, test1 = 0x9a84660

A: You should use copy all the time to declare NSString property
@property (nonatomic, copy) NSString* name;

You should read these for more information on whether it returns immutable string (in case mutable string was passed) or returns a retained string (in case immutable string was passed)
NSCopying Protocol Reference

Implement NSCopying by retaining the original instead of creating a
  new copy when the class and its contents are immutable

Value Objects

So, for our immutable version, we can just do this:

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

A: Since name is a (immutable) NSString, copy or retain makes no difference if you set another NSString to name. In another word, copy behaves just like retain, increasing the reference count by one. I think that is an automatic optimization for immutable classes, since they are immutable and of no need to be cloned. But when a NSMutalbeString mstr is set to name, the content of mstr will be copied for the sake of correctness.

A: If the string is very large then copy will affect performance and two copies of the large string will use more memory.


text:
Q: Backup Exec 2014 Insert Over writable Media into the robotic library We have Backup exec 2014 along with IBM TS3100 Tape Library.  I have made partitions defined (one for each day of the week) and all of my jobs run fine.  From few weeks we are getting 'Inset overwriteable media into the robotic library' errors very frequently. In JOB settings, I am using "Overwrite media" when this job begins.
We thought it might be dueto tapes, we inserted new un-used tapes but still getting error.

A: Step 1:
Run a Import Job on the media/slot to change the "Export Pending" state to "No" to allow the media to be written to for a backup job.
If the media still shows up as "Export Pending Yes" after running the import job as mentioned in step 1 then perform steps mentioned in step 2.
Step 2:
Make a copy of Backup Exec catalogs folder (Just in case the changes needs to be rolled back).

Note: The default location of catalog folder for Backup Exec for Windows Servers 11d and above is the C:\Program Files\Symantec\Backup Exec\Catalogs.
Move the media which is in the state of "Export Pending Yes" to retired media set and then delete it.
Re-inventory the slot containing the media.  Now the export pending on that slot should show as 'No' and the media should be usable again
Source https://www.veritas.com/support/en_US/article.000033762


text:
Q: How to add Kotlin PSI source files to IDEA Plugin project configuration I am trying to add support for kotlin for one of the IDEA plugins.
So far, I found this page and understood that I need to work with kotlin PSI files, such as KtClass and others.
When I was setting up my project I added idea source files to sdk(by cloning this repo), to make it easier to debug + see documentation.
However it seems that these idea source files doesn't include kotlin source files, such as mentioned KtClass and others, which I use in my project. Currently I see only decompiled version of these files.
Is there any way to add them like with other IDEA source files?

A: Those source files belongs to the Kotlin plugin, which is not strictly a part of IntelliJ IDEA distribution. You need to add the Kotlin plugin source to the project as well as the IDEA source.
There're two modules needed:

*

*https://github.com/JetBrains/kotlin/tree/master/idea

*https://github.com/JetBrains/kotlin/tree/master/compiler/psi/src/org/jetbrains/kotlin


text:
Q: Apple сделала reject приложению Ребята, у меня в принципе простое приложение. Которое должно проигрывать музыку посредством AVPlayer'a.
Вроде все хорошо, сделал чтобы она играла и тогда когда приложение идет в background.
Но я все сделал так как Apple говорит Здесь
И так:

First, declare your application provides specific background services
  and must be allowed to continue running while in the background. To do
  this, add the UIBackgroundModes key in your app's Info.plist file. Its
  value is an array that contains one or more strings that identify
  which background tasks your application supports. Specify the string
  value audio to indicate the application plays audible content to the
  user while in the background:

Плюс так:

Listing 1  Setting the audio category to allow playback when the
  screen locks or when the Ring/Silent switch is set to silent.

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

NSError *setCategoryError = nil;
BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!success) { /* handle the error condition */ }

NSError *activationError = nil;
success = [audioSession setActive:YES error:&activationError];
if (!success) { /* handle the error condition */ }

Но сегодня пришел реджект со словами:

June 17, 2015 at 6:12 AM От: Apple
    2.16 - Multitasking Apps may only use background services for their intended purposes: VoIP, audio playback, location, task completion,
    local notifications, etc.
    2.16 Details

Your app declares support for audio in the UIBackgroundModes key in
  your Info.plist, but we were unable to play any audible content when
  the application was running in the background.
Next Steps
The audio key is intended for use by applications that provide audible
  content to the user while in the background, such as music player or
  streaming audio applications. Please revise your app to provide
  audible content to the user while the app is in the background or
  remove the "audio" setting from the UIBackgroundModes key.
Resources
If you have difficulty reproducing a reported issue, please try
  testing the workflow described in Technical Q&A QA1764: How to
  reproduce bugs reported against App Store submissions.
If you have code-level questions after utilizing the above resources,
  you may wish to consult with Apple Developer Technical Support. When
  the DTS engineer follows up with you, please be ready to provide:
  - complete details of your rejection issue(s)
  - screenshots
  - steps to reproduce the issue(s)
  - symbolicated crash logs - if your issue results in a crash log

Подскажите что не так делаю, запутался если честно((
Заранее спасибо!

A: В принципе все так как советовал товарищ  Sega-Zero.

*

*в коде исправил мелкие недочеты

*написал развернутое сообщение интервьюеру, от том как правильно запустить и зачем, а главное когда нужно воспроизведения музыки в фоне

После чего получил одобрение в apple store.


text:
Q: source address of packets in a wifi network is the router and not the pc I executed ping fron machine A (wireless PC) to machine B (wired PC to the wireless router). When I check the packets in machine B with wireshark they have the source address of the router (192.168.1.1). I would expect the source address to be the one of the machine A (192.168.1.10) the one pinging. What is the correct behavior?

A: The source address of the packet would be the address of the last interface the packet has left to get to the destination, which in this case, would be your router.

A: I rebooted the router (d-link with DDWRT) now it works ok. The IP source address is the one of the machine (interface) that is the source of the packet, not the one of the router.


text:
Q: onViewableItemsChanged isn't called in a nested ScrollView (React-Native) I have a ScrollView for the entire screen and inside it there is a FlatList. when I place onViewableItemsChanged inside the flatlist it does not work, unless I make the ScrollView a normal View.
What should I do to solve this ?


text:
Q: how to solve (settingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.)?
This my code to create a new column with a calculation in a data frame

df1['Cases/Tests/1M pop']= (df1['Tot Cases/1M pop']/ df1['Tests/ 1M pop'])*100

and I got this error message in the output

settingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
 df1['Cases/Tests/1M pop']= (df1['Tot Cases/1M pop']/ df1['Tests/ 1M pop'])*100


text:
Q: Model First with DbContext, Fails to initialize new DataBase I give up.
I found this:
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
And thought, that's cool.
So I quickly redesigned my model to take advantage of best of two worlds.
But now my model fails at creating new database (or adding tabls to existing one).
I get this error:

Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.

At:
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

And that's my connection string:
    <add name="ForumContextContainer"
 providerName="System.Data.SqlClient"
 connectionString="Data Source=.\SQLExpress; Initial Catalog=iForum; Integrated Security=True"/>

Note. I added Initial Catalog later, to try if it going to work, but It was exactly the same.

A: This is wrong connection string. Once you are using model-first / database-first (EDMX) you must use Entity connection string with referencing .ssdl, .msl and .csdl metadata files. Also be aware that you must create your database in design time when creating model from EDMX = you must generate SQL script and execute it to create the database.

A: I guess this error usually appears when someone adds the EDMX/db first to a class library in the solution. If you do so make sure that the connection string added in App.config file in the class library project is available in the web.config or the exe project config file (so just copy/paste it there).

A: Add this connection string to web config and make changes:

<add name="Entities"
connectionString="
metadata=res://*/EFmodel.csdl|res://*/EFmodel.ssdl|res://*/EFmodel.msl;
provider=System.Data.SqlClient;provider
connection string="
data source=SAI-PC;
initial catalog=OrderDB;
user id=sa;
password=Pass$123;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />

EFmodel is my .edmx file name.

OrderDB is database name.

A: Delete or comment this :
//protected override void OnModelCreating(DbModelBuilder modelBuilder)
//{
//    throw new UnintentionalCodeFirstException();
//}

And change your connection string to valid one.


text:
Q: how to declare variable of NSString with double pointer I wanna use double pointer and I tried to declare like this.
NSString **a;

but, Xcode showed me the error "Pointer to non-const type 'NSString *' with no explicit ownership" and it couldn't be compiled.
Finally I wanna do like this.
NSString **a;
NSString *b = @"b";
NSString *c = @"c";
a = &b;
*a = c;

NSLog(@"%@",b);//I wanna see "c"

Let me know any advise please.

A: Change to this so that you can explicitly specify the ownership:
NSString *__strong *a;
NSString *b = @"b";
NSString *c = @"c";
a = &b;
*a = c;

NSLog(@"%@",b);//I wanna see "c"

Output:
 c

Here is the documentation on __strong.


text:
Q: facebook API error : Uncaught OAuthException: Error validating access token guys i'm getting this error
Fatal error: Uncaught OAuthException: Error validating access token. thrown in /home/techtud1/public_html/library/facebook.php on line 543
i'm a newbie to facebook development but i'm using the exact steps of this tutorial
http://www.joeyrivera.com/2010/facebook-graph-api-app-easy-w-php-sdk/
when i tried to get the information of the user i got it once , but when i tried to do it again i got this error . and whatever i'm doing , i'm getting this error as a result
HELP PZ

A: I had this problem and what solved it in my case was deleting the App from the FB User's profile and adding it again creating a new ACCESS_TOKEN. I do not know why, but this solved by problem.

A: If your application is FBML, header() doesnt work. You need to use fb:redirect
http://developers.facebook.com/docs/reference/fbml/redirect/

A: I suggest you start learning from the official facebook php-sdk example.php.
I found it a lot easier to kick-off and straight forward.

A: Check This
$app_id         = "YOUR_APP_ID";
$app_sec        = "APP_SEC";
$canvas_page    = "APP_CANVAS_PAGE_URL";
$scope          = "&scope=user_photos,email,publish_stream";
$auth_url       = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page) . $scope;

$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
if (empty($data["user_id"]))
{
    echo("");
}
$access_token   = $data["oauth_token"];
$user_id        = $data["user_id"];
$user           = json_decode( file_get_contents( "https://graph.facebook.com/me?access_token=" . $access_token ) );

function get_facebook_cookie($app_id, $application_secret)
{
    $args = array();
    parse_str(trim($COOKIE["fbs" . $app_id], "\""), $args);
    ksort($args);
    $payload = "";
    foreach ($args as $key => $value) {
        if ($key != "sig")
        {
            $payload .= $key . "=" . $value;
        }
    }
    if (md5($payload . $application_secret) != $args["sig"])
    {
        return null;
    }
    return $args;
}

$cookie = get_facebook_cookie($app_id, $app_sec);


text:
Q: Create a dictionary from two lists and then print the data in python I am new to python and am trying to grasp a few things. I would like to create a dictionary from two lists. I have two sets of data:
Person  |    Name
--------|--------
1       |   Jimmy
2       |    Mike
3       | Stanley
4       |    Will

I have both of these in lists, one called "person" and one called "name". I do this in a script which runs through multiple files to pull the data. each list is a different length with different data in it. Essentially, what I want to do is print the data as like this:
1 \t Jimmy
2 \t Mike
3 \t Stanley
4 \t Will

I pull the data from an xml file and here is the code I use to pull the data:
for people in xml.iter('people'):
  person.append(people.find('person').text)
  name.append(people.find('name').text)

So far the script works great and I can print out the two lists separately. What I don't know how to do is print them out together and so my thought is to store them to a dictionary instead, but I don't really know how to do that.

A: If you just want to print the two lists you can use zip (doc)
for num,name in zip(num_list,name_list):
    print str(num) + '\t' + name

you can use the same form to put the pairs in a dictionary (after you have the lists)
name_dict = {}
for num,name in zip(num_list,name_list):
    name_dict[num] = name

and then print
for num,name in name_dict.iteritems():
    print str(num) + '\t' + name

A: I don't think you need a dict here. To pair the elements of lists together, just use zip:
In [27]: zip(person, name)
Out[27]: [(1, 'Jimmy'), (2, 'Mike'), (3, 'Stanley'), (4, 'Will')]

For example,
person = [1,2,3,4]
name = ['Jimmy', 'Mike', 'Stanley', 'Will']
for p, n in zip(person, name):
    print('{p}\t{n}'.format(p = p, n = n))

yields
1   Jimmy
2   Mike
3   Stanley
4   Will

PS. If, for some reason, you do want a dict, it is easy to form too:
In [28]: dict(zip(person, name))
Out[28]: {1: 'Jimmy', 2: 'Mike', 3: 'Stanley', 4: 'Will'}

A: In elementary python.
people_dict = {}
for people in xml.iter('people'):
  person = people.find('person').text
  name = people.find('name').text
  people_dict[name] = person

A: Create the dict using the zip builtin function:
dct = dict(zip(person, name))

Then to print the dict, you can do something like this:
for k in dct:
    print '%s\t%s' % (k, dct[k])

good luck
Mike

A: If all you need to do is print them out together, then a list of tuples might be more appropriate than a dictionary, since a dictionary does not maintain order.  Here is how you could do this:
people = []
for person in xml.iter('people'):
    people.append((person.find('person').text, person.find('name').text))

Then to print:
for p, name in people:
    print p + '\t' + name

A: Use the zip builtin function.
In [3]: person = range(1,5)

In [4]: name = ['Jimmy', 'Mike', 'Stanley', 'Will']

In [5]: zip(person, name)
Out[5]: [(1, 'Jimmy'), (2, 'Mike'), (3, 'Stanley'), (4, 'Will')]

In [6]: for p,n in zip(person, name):
   ...:     print p, '\t', n
   ...:
1   Jimmy
2   Mike
3   Stanley
4   Will

A: If you are in Python 2.7 or newere, Dict comprehensions are available.  They may be overkill for your particular situation, but they are a good technique to know and resolve this issue gracefully.


text:
Q: Adding time to Nov. 2nd gives error I'm having some problems adding a date.
$test = strtotime('nov 02 2014');
$test_date = date('D, M. jS, Y' ,(1.0*86400) + $test);
echo $test_date;

returns Sun, Nov. 2nd, 2014
changing input to nov 01 and nov 03 return the expected strings.

A: Daylight Saving Time ended on November 2, 2014. This means that November 2, 2014 lasted longer than the 86,400 seconds you're adding to the date!

A: This should work for you:
$test = "nov 02 2014";
echo $test_date = date('D, M. jS, Y' ,strtotime($test . ' + 1 day'));


text:
Q: Haskell Yahoo Finance Command Line Tool I am trying to use this module to create a command line tool that will grab a quote from yahoo finance for a symbol. When I try to compile I receive this error.
Couldn't match expected type `[t0]'
                with actual type `IO
                                    (Maybe (Map (QuoteSymbol, QuoteField) QuoteValue))'
    In the return type of a call of `getQuote'
    In a stmt of a 'do' expression:
        q <- getQuote [arg] ["s", "l1", "c"]
    In the expression:
      do { q <- getQuote [arg] ["s", "l1", ....];
           case q of {
             Nothing -> error "symbol not found"
             Just m -> m } }

I am just starting to learn haskell, which is an incredibly different but powerful language, and I can not quite figure out what the problem is. Any help would be greatly appreciated and I would also appreciate any feedback on if I'm doing this the "haskell" way and if not any improvements I can make. Thanks!
module Main where

import Finance.Quote.Yahoo
import Data.Time.Calendar
import Data.Map
import System( getArgs )
import System.Console.GetOpt
import Data.Maybe ( fromMaybe )

data Options = Options
    { optVerbose     :: Bool
    , optShowVersion :: Bool
    , optOutput      :: Maybe FilePath
    , optInput       :: Maybe FilePath
    , optLibDirs     :: [FilePath]
    , optSymbol      :: String
    } deriving Show

defaultOptions    = Options
    { optVerbose     = False
    , optShowVersion = False
    , optOutput      = Nothing
    , optInput       = Nothing
    , optLibDirs     = []
    , optSymbol      = "YHOO"
    }

options :: [OptDescr (Options -> Options)]
options =
    [ Option ['v']     ["verbose"]
        (NoArg (\ opts -> opts { optVerbose = True }))
        "chatty output on stderr"
    , Option ['V','?'] ["version"]
        (NoArg (\ opts -> opts { optShowVersion = True }))
        "show version number"
    , Option ['o']     ["output"]
        (OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output")
        "FILE")
        "output FILE"
    , Option ['c']     []
        (OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input")
        "FILE")
        "input FILE"
    , Option ['L']     ["libdir"]
        (ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR")
        "library directory"
    , Option ['s']     ["symbol"]
        (ReqArg (\ s opts -> opts { optSymbol = getSymbol s }) "SYMBOL")
        "symbol SYMBOL"
    ]

compilerOpts :: [String] -> IO (Options, [String])
compilerOpts argv =
    case getOpt Permute options argv of
        (o,n,[]  ) -> return (foldl (flip id) defaultOptions o, n)
        (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
    where header = "Usage: ic [OPTION...] files..."

main = do
    args <- getArgs
    compilerOpts args

getSymbol :: String -> String
getSymbol arg = do
  q <- getQuote [arg] ["s", "l1", "c"]
  case q of
    Nothing -> error "symbol not found"
    Just m -> m

A: This is wrong:
getSymbol :: String -> String
getSymbol arg = do
  q <- getQuote [arg] ["s", "l1", "c"]
  case q of
    Nothing -> error "symbol not found"
    Just m -> m

It should probably be:
getSymbol :: String -> IO String
getSymbol arg = do
  q <- getQuote [arg] ["s", "l1", "c"]
  case q of
    Nothing -> fail "symbol not found"
    Just m -> return m

Note I have changed the type signature and the final two lines. (Since I have changed the type of getSymbol, you will have to use the result differently wherever you call it.)
A partial explanation:
You are using do syntax, which results in a monadic value. The return type of getSymbol was String, which is the same as [Char]. Lists are monads, so this is fine.
But then you call getQuote on the right of a <-, which results in an IO value. IO is monadic, but IO is not the same as lists, so we have an error. (You have to use the same monad on the right hand side of a <- as the do block results in.)
Edit: The above code change isn't going to be enough. m has type Map (QuoteSymbol, QuoteField) QuoteValue which obviously isn't the same as String, so you want to compute something from m instead of returning it directly. I don't know exactly what you want to do here.
Also, you're using getSymbol in your option parsing code. It's better if your save the input to getSymbol in your Options, and call getSymbol later with that value, after you have processed the command line options. (Otherwise you might contact Yahoo's servers only to discover that a different command line option is wrong and throw the answer away. Not to mention that the optSymbol field can't hold IO.)

A: The trouble is that getSymbol has no business in the definition of options, since it is an IO action as we can see from the fact that it uses getQuote:
getQuote :: [QuoteSymbol]
         -> [QuoteField]
         -> IO (Maybe (Map (QuoteSymbol, QuoteField) QuoteValue))

So where you say optSymbol =  getSymbol s you should just put the string s.  The crucial line should certainly read
(ReqArg (\ s opts -> opts { optSymbol =  s }) "SYMBOL")

not
(ReqArg (\ s opts -> opts { optSymbol =  getSymbol s }) "SYMBOL")

At the moment you are just parsing arguments. What you do with the optSymbol string -- e.g. go to Yahoo to find out about it via getSymbol -- belongs in main or some preliminary action you need to define.  Here is a module that typechecks, it barely does anything, acting like this:
-- $ ./yahoo -s STD.F  -- Standard Chartered?
-- STD.F c -0.396 - -1.99%
-- STD.F l1 19.492
-- STD.F s STD.F

module Main where

import Finance.Quote.Yahoo
import Data.Time.Calendar
import Data.Map
import Prelude
import qualified Prelude
import System.Environment( getArgs )
import System.Console.GetOpt
import Data.Maybe ( fromMaybe )
import System.IO.Unsafe

main = do
    args <- getArgs
    (options, strs) <- compilerOpts args
    whatIDoWithTheUsersOptions options strs

-- This is not doing much with all this user input ...
whatIDoWithTheUsersOptions :: Options -> [String] -> IO ()
whatIDoWithTheUsersOptions options strs = do
    blather <- getSymbol $ optSymbol options
    putStrLn blather

getSymbol :: String ->  IO String
getSymbol arg =   do
  q <- getQuote [arg] ["s", "l1", "c"]
  case q of
    Nothing -> return $ "symbol " ++ arg ++ " not found"
    Just m -> return $ unlines $ Prelude.map helper (toList m)
 where helper ((a,b), c) = unwords [a,b,c]

data Options = Options
    { optVerbose     :: Bool
    , optShowVersion :: Bool
    , optOutput      :: Maybe FilePath
    , optInput       :: Maybe FilePath
    , optLibDirs     :: [FilePath]
    , optSymbol      :: String
    } deriving Show

defaultOptions    = Options
    { optVerbose     = False
    , optShowVersion = False
    , optOutput      = Nothing
    , optInput       = Nothing
    , optLibDirs     = []
    , optSymbol      = "YHOO"
    }

options :: [OptDescr (Options -> Options)]
options =
    [ Option ['v']     ["verbose"]
        (NoArg (\ opts -> opts { optVerbose = True }))
        "chatty output on stderr"
    , Option ['V','?'] ["version"]
        (NoArg (\ opts -> opts { optShowVersion = True }))
        "show version number"
    , Option ['o']     ["output"]
        (OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output")
        "FILE")
        "output FILE"
    , Option ['c']     []
        (OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input")
        "FILE")
        "input FILE"
    , Option ['L']     ["libdir"]
        (ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR")
        "library directory"
    , Option ['s']     ["symbol"]
        (ReqArg (\ s opts -> opts { optSymbol =  s }) "SYMBOL")
        "symbol SYMBOL"
    ]

compilerOpts :: [String] -> IO (Options, [String])
compilerOpts argv =
    case getOpt Permute options argv of
        (o,n,[]  ) -> return (Prelude.foldl (flip id) defaultOptions o, n)
        (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
    where header = "Usage: ic [OPTION...] files..."


text:
Q: Measurability issues in the proof of Fujisaki, Kallianpur and Kunita for stochastic filtering I'm currently looking over the proof(s) of the theorem of Fujisaki, Kallianpur and Kunita regarding the MRT-like characterisation of square integrable random variables measurable with respect to the augmented observation filtration. Unfortunately I'm seeing problems with respect to measurability in the two proofs I'm aware of:
The proof in Fundamentals of Stochastic Filtering (Crisan and Bain) which most of my intuition about the ideas of the proof revolves around: http://books.google.co.jp/books?id=hE3KF5Wf6ecC&pg=PA18&lpg=PA18&dq=path+regularity+for+optional+projection&source=bl&ots=XoOtAHQ6YG&sig=z1b6Zp_P3c7ExNl2DqpNHGHB54M&hl=en&sa=X&ei=asjCUIjYEO2tiQfj-YCwBA&ved=0CCoQ6AEwAA#v=onepage&q=path%20regularity%20for%20optional%20projection&f=false
The original proof: Link
For the first proof, my understanding breaks down around the bottom of page 36 and the start of page 37, especially where they state that $\int_0^t \|\bar{\pi}_s(h)\| ds$ is continuous.  However, as I understand this process is only equal to a continuous process with respect to indistinguishability, which is not sufficient for the $T^n$ defined later to be $\mathcal{Y}_t^o$ stopping times.
For the original proof (which I've admittely skimmed), the authors seem to suggest defining $\hat{h}$ to be the optional projection of $h$ with respect to the raw (unaugmented) filtration of the observation process $z$ (which I believe can be done by a theorem of Dellacherie and Meyer though I have not read the proof). Later on we would like to define stopping times $T_n$ such that $T_n$ is the hitting time of $|\int_0^t \hat{h}_s \ ds |$ of the level n. For these to be stopping times with respect to the raw observation filtration, we'd need $\int_0^t \hat{h}_s \ ds $ to be continuous, but this can only be done if we have some path regularity of $\hat{h}_s$. In the case of taking the optional projection with respect to an augmented, right continuous filtration, given certain integrability conditions on $h$ we can choose a cadlag version of $\hat{h}$, but in the unaugmented filtration case, as far as I know, this is not possible.
As it stands, I only feel I can prove the theorem in the case $h_t = h(X_t)$ is surely bounded by a deterministic function $K_t$, in which case we don't need to apply any probabilistic stopping arguments.
As this is quite a fundamental result in the field of stochastic filtering, these issues are quite worrying to me. I'm hoping that someone more experienced in this area could help clear things up. My impression so far is that the literature seems rather fraught with problems of this nature (the proof of Lemma A.24 in the book linked, required for the proof of the same theorem, being another example: https://math.stackexchange.com/questions/168566/stopped-filtration-filtration-generated-by-stopped-process).

A: Having looked at the proof in Diffusions, Markov Processes and Martingales Vol. 2 (Rogers and Williams) I believe I have resolved the issue. We define $\mathcal{Y}_t$-stopping times $T_n$ using the cadlag version of $\pi_t(h)$. By continuity of $\int_0^t \pi_s(h) ds$ these are $\mathcal{Y}_{t-}$ stopping times. We then can find $\mathcal{Y}_t^o$-stopping times $S_n$ equal to $T_n$ almost surely. This enough for the proof in the book linked.


text:
Q: Multiple models validation in the same View - Django 1.11 I'm looking for a strategy to validate the uniqueness of the keys of four models that have relationships with each other before finally being able to save them in the database.
In other words, I would like to check the uniqueness of the keys so that there is no inconsistency in the database when using the Model.save() method, and only use it when all the unique keys are really unique.
Following the view below as an example, the fields cnpj, address, and number respectively in LegalPerson, Email and Phone, must be unique.
class StoreRegistrationView(View):
    '''
    Classe responsavel pelo cadastro de lojas
    '''
    def post(self, request):

        if request.method == 'POST':
            #import pdb; pdb.set_trace()
            form = StoreForm(request.POST)

            if form.is_valid():

                lp = LegalPerson(
                    cnpj = form.cleaned_data['cnpj'],
                    corporate_name = form.cleaned_data['corporate_name'],
                    fantasy_name = form.cleaned_data['fantasy_name'],
                    state_inscription = form.cleaned_data['state_inscription'],
                    municipal_inscription = form.cleaned_data['municipal_inscription'],
                    )

                lp.save()

                address = Address(
                    street = form.cleaned_data['street'],
                    neighborhood = form.cleaned_data['neighborhood'],
                    number = form.cleaned_data['number'],
                    complement = form.cleaned_data['complement'],
                    city = form.cleaned_data['city'],
                    estate = form.cleaned_data['estate'],
                    country = 'Brasil',
                    cep = form.cleaned_data['cep'],
                    latitude = form.cleaned_data['latitude'],
                    longitude = form.cleaned_data['longitude'],
                    person = lp,
                    )

                address.save()

                email = Email(
                    address = form.cleaned_data['email'],
                    person=lp,
                    )

                email.save()

                phone = Phone(
                    number=form.cleaned_data['phone_number'],
                    person=lp,
                    )

                phone.save()

                # Mensagem de sucesso que será disponibilizada para o usuário
                messages.success(request, 'Cadastro de loja efetuado com sucesso.')

                return redirect('importar-produtos')

        messages.warning(request, 'Erro durante o cadastro.')
        context = {
            'store_form': StoreForm(),
                }

        return render(request, 'n3oadmin/store-registration.html', context)

I've been researching, and found that models in django have some validating methods like Model.full_clean(), Model.clean(), and Model.validate_unique().

A: Instead of using a regular form, you should create multiple model forms.
class LegalPersonForm(forms.ModelForm):
    class Meta:
        model = LegalPerson
        fields = [...]

class = AddressForm(forms.ModelForm):
    class Meta:
        model = LegalPerson
        exclude = ['person']

Then, use your model forms in your view and template. The model forms will take care of validating unique constraints.
if request.method == 'POST':
    address_form = AddressForm(request.POST)
    legal_person_form = LegalPersonForm(request.POST)

    if address_form.is_valid() and legal_person_form.is_valid():
        person = legal_person_form.save()
        address = address_form.save(commit=False)
        address.person = person
        address.save()

        ...

        return redirect('importar-produtos')
else:
    address_form = AddressForm()
    legal_person_form = LegalPersonForm()

context = {
    'address_form': address_form,
    'legal_person_form': legal_person_form,
}
return render(request, 'n3oadmin/store-registration.html', context)

Note you can exclude foreign key fields in the model form. Then, in the view, you can save with commit=False, set the foreign key, then save the instance.
Note also that we have only instantiated blank forms AddressForm() and LegalPersonForm in the else block (for GET requests). This means that if the form is valid, you get to see the form errors in the template instead of a blank form.

A: You can refer to this here to set a unique field.
https://docs.djangoproject.com/en/1.11/ref/models/fields/#unique


text:
Q: r row-wide conditional replacement Friends
I'm trying t set up a matrix or data.frame for a canonical correlation analysis. The original dataset has a column designating one of x conditions and subsequent columns of explanatory variables. I need to set up an array that sets an indicator variable for each condition "x". eg. Columns in df are:
ID cond task1 taskN
A, x, 12, 14
B, x, 13, 17
C, y, 11, 10
D, z, 10, 13

here "cond" can be x,y,z,... (can vary, so I don't know how many). This needs to go to:
ID, x, y, z, task1, taskN
A, 1, 0, 0, 12, 14
B, 1, 0, 0, 13, 17
C, 0, 1, 0, 11, 10
D, 0, 0, 1, 10, 13

So, I can set up the indicators in an array
iv<-as.data.frame(array(,c(nrow(df),length(levels(cond)))))

and then cbind this to df, but I can't figure out how to go into the array and set the appropriate indicator to "1" and the rest to "0".
Any suggestions?
Thanks
Jon

A: If you code cond as a factor, you can get R to do the expansion you want via model.matrix. The only complication is that to get the coding you chose (dummy variables coding, or sum contrasts in R) we need to change the default constrasts used by R's model formula code.
## data
dat <- data.frame(ID = LETTERS[1:4], cond = factor(c("x","x","y","z")),
                  task1 = c(12,13,11,10), taskN = c(14,17,10,13))
dat

## We get R to produce the dummy variables for us,
## but your coding needs the contr.sum contrasts
op <- options(contrasts = c("contr.sum","contr.poly"))
dat2 <- data.frame(ID = dat$ID, model.matrix(ID ~ . - 1, data = dat))
## Levels of cond
lev <- with(dat, levels(cond))
## fix-up the names
names(dat2)[2:(1+length(lev))] <- lev
dat2

## reset contrasts
options(op)

This gives us:
> dat2
  ID x y z task1 taskN
1  A 1 0 0    12    14
2  B 1 0 0    13    17
3  C 0 1 0    11    10
4  D 0 0 1    10    13

This should scale automatically as the number of levels in cond changes/increases.
HTH

A: Another alternative is to use use cast in the reshape package:
library(reshape)
l <- length(levels(dat$cond))
dat2 <- merge(cast(dat,ID~cond),dat)[,c(1:(l+1),(l+3):(ncol(dat)+l))]
dat2[,2:(1+l)] <- !is.na(dat2[,2:(1+l)])

This gives you logical values rather than 0 and 1 though:
> dat2
  ID     x     y     z task1 taskN
1  A  TRUE FALSE FALSE    12    14
2  B  TRUE FALSE FALSE    13    17
3  C FALSE  TRUE FALSE    11    10
4  D FALSE FALSE  TRUE    10    13

A: That's cool using model.matrix for this. (reshape too.) Always learning something here. A couple more ideas:
indicator1 <- function(groupStrings) {
  groupFactors <- factor(groupStrings)
  colNames <- levels(groupFactors)
  bits <- matrix(0, nrow=length(groupStrings), ncol=length(colNames))
  bits[matrix(c(1:length(groupStrings),
                unclass(groupFactors)), ncol=2)] <- 1
  setNames(as.data.frame(bits), colNames)
}

indicator2 <- function(groupStrings) {
  colNames <- unique(groupStrings)
  bits <- outer(groupStrings, colNames, "==")
  setNames(as.data.frame(bits * 1), colNames)
}

Used as follows
d <- data.frame(cond=c("a", "a", "b"))
d <- cbind(d, indicator2(as.character(d$cond)))

A: Again, a great example of the greatness of open-source! Thanks so much for your help. The initial solution seemed to work best for me. In case someone else might be interested, here is how I implemented this with my (very large) dataset:
 # Load needed libraries if not already so
if("packages:sciplot" %in% search()) next else library(moments)

 # Initialize dataframes. DEFINE THE workspace SUBSET TO ANALYZE HERE
 df<-stroke

 # Make any necessary modifications to the df
 df$TrDif <- df$TrBt-df$TrAt

 # 0) Set up indicator variables (iv) from the factor you choose.
 op <- options(contrasts = c("contr.sum","contr.poly"))
 dat<-subset(df,select=c("newcat"))
 iv<-data.frame(model.matrix(~.-1,data=dat))
 names(iv) <- levels(dat$newcat)
 lbl<-levels(dat$newcat) # need this for plot functions below

 # Select task variables with n > 1150 to be regressed (THIS CAN PROBABLY BE DONE MORE ELEGANTLY).
 taskarr<-subset(df,   select=c("B20","B40","FW","Anim","TrAt","TrBt","TrBerr","TrDif","Snod15","tt","GEMS","Clock3","orient","Wlenc","wlfr","wlcr","wlrec","Snod15Rec","GEMSfr"))

 ## 1) evaluate covariance matrix and extract sub-matrices
 ## Caution: Covariance samples differ due to missing values.
 sig <- cov(cbind(iv,taskarr),use="pairwise.complete.obs")


text:
Q: How to draw a animation upon a background image in Java Swing Here is my code, I used two image, one for background image and one for the pinball animation, but with this code, the ball will wipe off the background image within it's flying trace so I need some help that can allow me draw on a transparent bufferedimage then put it as a mask over the background image. Thanks in advance.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MainTest {

    private final int TABLE_WIDTH = 300;
    private final int TABLE_HEIGHT = 400;
    private final int BALL_SIZE = 16;
    private JFrame f = new JFrame("Pinball game");
    Random rand = new Random();
    private int ySpeed = 5;
    private double xyRate = rand.nextDouble() - 0.5;
    private int xSpeed = (int) (ySpeed * xyRate * 2);
    private int ballX = rand.nextInt(200) + 20;
    private int ballY = rand.nextInt(10) + 20;

    private BackgroundPanel background = new BackgroundPanel();
    private Foreground foreground = new Foreground();
    private int preX = -1;
    private int preY = -1;

    BufferedImage image = new BufferedImage(TABLE_WIDTH, TABLE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
    Image back = new ImageIcon("res/cat1.jpg").getImage();
    Graphics g = image.getGraphics();

    Timer timer;

    public void init() {
//      Graphics2D g = image.createGraphics();
//      image = g.getDeviceConfiguration().createCompatibleImage(30, 30, Transparency.TRANSLUCENT);
        background.setBackground(new ImageIcon("res/cat1.jpg"));
        background.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
        foreground.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
        background.add(foreground);
        f.add(background);

        ActionListener taskPerformer = evt -> {
            if (ballX <= 0 || ballX >= TABLE_WIDTH - BALL_SIZE) {
                xSpeed = -xSpeed;
            }
            else if (ballY <= 0 || (ballY >= TABLE_HEIGHT - BALL_SIZE)) {
                ySpeed = -ySpeed;
            }
            ballY += ySpeed;
            ballX += xSpeed;
            g.setColor(Color.BLUE);
            g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
            if (preX == -1) {
                preX = ballX;
                preY = ballY;
            }
            g.clearRect(preX, preY, BALL_SIZE, BALL_SIZE);
            preX = ballX;
            preY = ballY;
            foreground.repaint();
        };
        timer = new Timer(10, taskPerformer);
        timer.start();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        new MainTest().init();
    }

    public class Foreground extends JPanel {
        private static final long serialVersionUID = 1L;

        public Foreground() {
        }

        @Override
        public void update(Graphics g) {
            paint(g);
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(back, 0, 0, this);
            g.drawImage(image, 0, 0, this);
        }
    }
}

public class BackgroundPanel extends JPanel {

    private static final long serialVersionUID = 6702278957072713279L;
    private Icon wallpaper;

    public BackgroundPanel() {
    }

    protected void paintComponent(Graphics g) {
        if (null != wallpaper) {
            processBackground(g);
        }
    }

    public void setBackground(Icon wallpaper) {
        this.wallpaper = wallpaper;
        this.repaint();
    }

    private void processBackground(Graphics g) {
        ImageIcon icon = (ImageIcon) wallpaper;
        Image image = icon.getImage();
        int cw = getWidth();
        int ch = getHeight();
        int iw = image.getWidth(this);
        int ih = image.getHeight(this);
        int x = 0;
        int y = 0;
        while (y <= ch) {
            g.drawImage(image, x, y, this);
            x += iw;
            if (x >= cw) {
                x = 0;
                y += ih;
            }
        }
    }
}

A: Draw ball after draw background image.
in your case, draw ball after method "processBackground".

A: I got this problem solved, and post the code here, thanks @MadProgrammer and @SuperShark's help.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MainTest {

    private final int TABLE_WIDTH = 300;
    private final int TABLE_HEIGHT = 400;
    private final int BALL_SIZE = 16;
    private JFrame f = new JFrame("Pinball game");
    Random rand = new Random();
    private int ySpeed = 5;
    private double xyRate = rand.nextDouble() - 0.5;
    private int xSpeed = (int) (ySpeed * xyRate * 2);
    private int ballX = rand.nextInt(200) + 20;
    private int ballY = rand.nextInt(10) + 20;

    private BackgroundPanel background = new BackgroundPanel();
    Timer timer;

    public void init() {

        background.setBackground(new ImageIcon("res/cat1.jpg"));
        background.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));

        f.add(background);

        ActionListener taskPerformer = evt -> {
            if (ballX <= 0 || ballX >= TABLE_WIDTH - BALL_SIZE) {
                xSpeed = -xSpeed;
            } else if (ballY <= 0 || (ballY >= TABLE_HEIGHT - BALL_SIZE)) {
                ySpeed = -ySpeed;
            }
            ballY += ySpeed;
            ballX += xSpeed;
            background.repaint();
        };
        timer = new Timer(10, taskPerformer);
        timer.start();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        new MainTest().init();
    }

    public class BackgroundPanel extends JPanel {

        private static final long serialVersionUID = 6702278957072713279L;
        private Icon wallpaper;

        public BackgroundPanel() {
        }

        protected void paintComponent(Graphics g) {
            if (null != wallpaper) {
                processBackground(g);
                drawball(g);
            }
            System.out.println("f:paintComponent(Graphics g)");
        }

        public void setBackground(Icon wallpaper) {
            this.wallpaper = wallpaper;
            this.repaint();
        }

        private void processBackground(Graphics g) {
            ImageIcon icon = (ImageIcon) wallpaper;
            Image image = icon.getImage();
            int cw = getWidth();
            int ch = getHeight();
            int iw = image.getWidth(this);
            int ih = image.getHeight(this);
            int x = 0;
            int y = 0;
            while (y <= ch) {
                g.drawImage(image, x, y, this);
                x += iw;
                if (x >= cw) {
                    x = 0;
                    y += ih;
                }
            }
        }
        private void drawball(Graphics g){
             g.setColor(Color.BLUE);
             g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
        }
    }
}


text:
Q: How can I add error bars to geom_col in ggplot2? How can I add error bars to a geom_col figure in ggplot2? All examples I found googling around are for geom_bar figures. I would like to continue using geom_col rather than convert everything over to geom_bar.
Example
library(dplyr)
library(ggplot2)

beer <- read.csv("http://users.stat.umn.edu/~helwig/notes/MNbeer.csv")

dat <- beer %>%
  group_by(Style) %>%
  summarise(mean_abv = mean(ABV),
            sd_rating = sd(ABV))

ggplot() +
  geom_col(data = dat, aes(x = Style, y = mean_abv),
           position = "dodge", color = "black")

dat$lower <- dat$mean_abv - dat$sd_rating
dat$upper <- dat$mean_abv + dat$sd_rating

#throws error message (Error: geom_errorbar requires the following missing aesthetics: x or y, xmin and xmax)
ggplot() +
  geom_col(data = dat, aes(x = Style, y = mean_abv),
           position = "dodge", color = "black") +
  geom_errorbar(data = dat, aes(ymin = lower,
                                ymax = upper))

A: It's just what the error says: you need also to supply the x aesthetic. Try with:
ggplot() +
  geom_col(data = dat, aes(x = Style, y = mean_abv),
           position = "dodge", color = "black") +
  geom_errorbar(data = dat, aes(x=Style, ymin = lower,
                                ymax = upper))

As an aside: it is usually not recommended to represent means using columns, you'll probably be better off with points and errorbars.


text:
Q: Validating specific date format in Excel I need to verify whether the dates in my Excel table are in the correct format, which is yyyy/mm/dd, so any other formats like mm/dd/yyyy would be incorrect.
I am using this formula:
=IF(NOT(ISERROR(DATEVALUE(TEXT(W2,"yyyy/mm/dd")))),"valid date","invalid date"

While the formula did pick up cells that did not contain a date, it failed to pick up cells that had dates in the wrong format like mm/dd/yyyy.  What am I missing from my formula?  Please help.
Thank you in advance.
Kev

A: If you want to check the format of a cell, put this User Defined Function in a standard module:
Public Function FormatChecker(r As Range) As String
    FormatChecker = r(1).NumberFormat
End Function

With data in column A, in B1 enter:
=FormatChecker(A1)

and copy down.  In C1 enter:
=IF(AND(LEFT(B1,4)="yyyy",MID(B1,6,2)="mm",RIGHT(B1,2)="dd"),"Good","Bad")

NOTE:
If you change the format of a column A cell, you will also need to refresh its contents to re-calculate column B.  Use:  F2 and Enter


text:
Q: Spring 3 Security - what are and how exactly do the subtags under `` work? I am learning Spring 3 Security using an amazing book called Spring in Practice. I have questions regarding how exactly the tags under the <http> tag work behind the scenes.
In the book it says:

the <http> element works by creating a chain of servlet filters to handle
  different aspects of web security. By setting auto-config="true", you
  enable the filters for form-based logins, HTTP basic authentication,
  and logouts. If you prefer, you can set auto-config="false" (that's
  the default) and specify the desired filters manually.

I have 3 questions regarding Spring 3 Security.
1). Is each element under <http> such as <form-login> and <remember-me> a filter that gets created? How does <http> element create the filters?
2). If I was to  set auto-config="false", how would I go about specifying the desired filters manually?
3). As I understand, the <authentication-manager> tag represents the AuthenticationManager interface. But how does a tag do this? There is no bean in the xml called AuthenticationManager.. Same goes for the nested tag <authentication-provider>. The AuthenticationProvider bean is not listed in the Spring xml anywhere...
Thank you in advance for your help.

A: The http element and the authentication-manager element are part of the spring security namespace configuration.
These elements allow to declare what is the end-result that we want from a security point of view (use a form login, this is the logout page, etc.), instead of declaring spring beans and wiring them together.
The end-result is a more declarative, readable and maintainable way of configuring security, as opposed to wiring the beans together and building the filter chain by hand. Also with these elements there is usually less configuration because defaults are applied.
These elements are an example of a security XML based DSL. The way that it works at runtime is like this:
Spring will read all the elements of the http and authentication-manager into memory using XML libraries such as a DOM implementation.
Depending on the contents of the XML a chain of filters will be built in the case of the http element, check class AuthenticationConfigBuilder to see how it's built.
Using this to go over the different questions raised:

*

*Not necessarily, each element does not have to be a filter. Spring can parse the config to do basically anything and not necessarily always create a filter. An element in the config namespace might for example correspond to a component used by one of the filters.

*The http element section of this pdf has several examples

*This is done similarly to the http element in AuthenticationManagerBeanDefinitionParser


text:
Q: pynput events executing twice def pressLetter(charIn):
    val = getKeyValue(charIn)
    PressKey(val)
    return

def KeyboardEvents():
from pynput import keyboard
    with keyboard.Events() as events:
    for event in events:
        if event.key == keyboard.Key.space:
            pressLetter('w')

Pressing space types ww. How would I rewrite this so that it only presses w once?

A: Well, I figured it out. It appears that keyboard.Events() registers button press events on both key pressed and key released. Meaning that...
if event.key == keyboard.Key.space:
            pressLetter('w')

Presses w twice because it executes both on key pressed, and then key released.
The solution I found was to use keyboard.Listener() instead
def pressLetter(charIn):
    val = getKeyValue(charIn)
    PressKey(val)
    return

def on_press(key):
    if key == keyboard.Key.space:
        pressLetter('w')

def on_release(key):
    if key == keyboard.Key.esc:
        return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

listener = keyboard.Listener(on_press=on_press, on_release=on_release)
    listener.start()

A: This worked for me:
def KeyboardEvents():
    from pynput import keyboard
        with keyboard.Events() as events:
            for event in events:
                if isinstance(event, keyboard.Events.Press):
                    if event.key == keyboard.Key.space:
                        pressLetter('w')


text:
Q: Flutter GetX can't assign Set to RxSet I am developing an application and came across a problem, which does not cause an error but pretty frustrating for me.
The situation is that I have an RxSet of CustomClass objects with default initialization to empty Set. When I fetch data from the server, I want to assign the result to this set. As GetX suggests, I should go like myRxSet = dataFetchedFromServer. This gives me a compile time error. myRxSet.value = dataFetchedFromServer still works, but gives an info that I should not assign to .value property.
A sample code can be seen bellow
RxSet<MyCustomClass> myCustomClassEntries = Set<MyCustomClass>().obs;

Future<void> syncData() async {
   myCustomClassEntries = await _fetchDataFromServer(); // this gives me compile time error
   myCustomClassEntries.value = await _ fetchDataFromServer(); // this gives me a warning that RxSet is not intented to be used this way.
}

GetX version: ^4.3.4
Flutter version: 2.2.3
Dart version: 2.13.4
Any idea what I'm doing wrong?
Edit

_fetchDataFromServer() does not matter in this situation, just wanted to give some context to the problem. As simple as it is:
RxSet<MyCustomClass> myCustomClassEntries = Set<MyCustomClass>().obs;

// This line gives me a compile time error. It says Set<MyCustomClass> can't be assigned to RxSet<MyCustomClass>
myCustomClassEntries = new Set<MyCustomClass>();

// This line works, just like everywhere else with GetX, but says .value is no longer intented to be used on RxList, RxSet or RxMap. It recommends to use the syntax above, which gives the error.
myCustomClassEntries.value = new Set<MyCustomClass();

From GetX changelog
Change: You do not need to access the ".value" property of primitives. For Strings you need interpolation. For num, int, double, you will have the normal operators, and use it as dart types. This way, .value can be used exclusively in ModelClasses. Example:
var name = "Jonny" .obs;
// usage:
Text ("$name");

var count = 0.obs;
// usage:
increment() => count ++;
Text("$count");

Thus: List, Map, Set, num, int, double and String, as of this release, will no longer use the .value property.
NOTE: The changes were not break changes, however, you may have missed the details of the documentation, so if you faced the message: "The member 'value' can only be used within instance members of subclasses of 'rx_list.dart' "you just need to remove the" .value "property from your list, and everything will work as planned. The same goes for Maps and Sets.

A: In short, when using a list in Getx, you don't need to use .value.
...
myCustomClassEntries = Set<MyCustomClass>().obs; // just add .obs and treat it like a regular list.
final object = MyCustomClass();
myCustomClassEntries.add(object); // no error here and not using .value

I asked for the _fetchDataFromServer() function because it matters in the sense of what you're trying to return. But regardless, return an observable Set<MyCustomClass>() and then you won't have type casting errors.
Update after follow up questions:
Just return an RxSet<MyCustomClass> from your _fetchDataFromServer function so you have matching types.
Future<RxSet<MyCustomClass>> _fetchDataFromServer() async {
  final tempList = Set<MyCustomClass>().obs;
// ... your code that populates list from server
  return tempList;
}

You don't need to clear the list. Below will update myCustomClassEntries with only what is returned from the function.
myCustomClassEntries = await _fetchDataFromServer();

A: I used them on marker class for google map,markers were not setting after getting current location:
RxSet<Marker> markers = <Marker>{}.obs;

Obx(()=>
                  GoogleMap(
                        zoomControlsEnabled: true,
                        compassEnabled: false,
                        myLocationButtonEnabled: false,
                        onMapCreated: (GoogleMapController controller) {

                        },
                        markers: vm.markers.value,
                      ),
                    )


text:
Q: Plotting data and fitting to a function
I have three sets of data. I would like to plot them in the same graph. Then plot the following fittings to the data. Any help is appreciated!

*

*f(v) = (v^2)*exp(-mv^2/2 kb T)

*f(v) = (v^3)*exp(-mv^2/2 kb T)

data1:
data = Import[
   "/Users/julissavelasquez/Box/1_Harrison Lab/03_Formic \
Acid/Wodtke_2021_Fig4C/Data_Total_Integrated_distribution.xlsx"];

hyperthermal =
  Import["/Users/julissavelasquez/Box/1_Harrison Lab/03_Formic \
Acid/Wodtke_2021_Fig4C/Data_Hyperthermal_distribution.xlsx"];

Plot[data, {x, 0, 2}]

Hyperthermal data:
Data for copying/pasting is in the Google Sheet: https://docs.google.com/spreadsheets/d/1Z-tVwtRmt6UD3v67eMO0e5lws8wwZ6G3hLaZJkETSK0/edit?usp=sharing

A: data = First[Import["~/Downloads/Data.xlsx", "SkipLines" -> 2]][[1 ;; -2]];

total = data[[All, 1 ;; 2]]
hyper = data[[All, 3 ;; 4]]
thermal = data[[All, 5 ;; 6]]

ListLinePlot[{total, hyper, thermal},
 PlotLabels -> {"Total", "Hyper", "Thermal"},
 PlotTheme -> "Detailed",
 ImageSize -> 600]

The fit is not good the model probably needs adjusting or I have misinterpreted it.
totalFit = NonlinearModelFit[total, (v^2)*Exp[-m v^2/(2 k bt)], {m, k, bt}, v]

Show[ListPlot[total], Plot[totalFit[x], {x, 0, 1.2}], Frame -> True]

A: Clear["Global`*"]

data = Import["/Users/roberthanlon/Downloads/Data.xlsx",
    "SkipLines" -> 2][[1]];

Eliminate any missing data
total = data[[All, 1 ;; 2]] /. {"", ""} :> Nothing;

In your model, m/2 kb T acts as a single constant. The split of any derived value into these separate factors is arbitrary. You also need an overall scale factor. Use the model a*(v^n)*Exp[-c v^2] with n being either 2 or 3.
(totalFit2 =
   NonlinearModelFit[total, a*(v^2)*Exp[-c v^2], {a, c}, v]) // Normal

(* 11.1953 E^(-4.6119 v^2) v^2 *)

(totalFit3 =
   NonlinearModelFit[total, a*(v^3)*Exp[-c v^2], {a, c}, v]) // Normal

(* 37.2111 E^(-6.30875 v^2) v^3 *)

Legended[
 Show[
  ListLinePlot[total, PlotStyle -> ColorData[97][3]],
  Plot[{totalFit2[x], totalFit3[x]}, {x, 0, 1.2}],
  Frame -> True],
 Placed[
  LineLegend[ColorData[97] /@ Range[3], {v^2, v^3, "data"}],
  {0.8, 0.7}]]


text:
Q: How to stop git-bash shell from waiting for process to finish? Based on a solution to How do I open a new git bash terminal window at my current location in windows? I can use
$ git-bash

to launch a new terminal from inside a git-bash console window.
However, this will block the original terminal which will be waiting for the result of the new git-bash.
Can I start a new terminal window without having it wait for the result?

A: In Bash, you can append & to run a command in the background.
In order to suppress its shell output (if any), you can also redirect its STDERR and STDOUT to /dev/null.
So, use this:
git-bash & > /dev/null 2>&1

When you close the window, the command should also exit in the background.


text:
Q: Understanding git init What is git init for exactly? Must I do it once per computer or once per project that uses git? I downloaded my project by git clone and got it working, but now it is storing my project also to C:/Users/myUser/git , is that certain folder or I can change it?
I don't really know much about that folder, it seems to be like a local git repo or something, but what "manages" it, or why it is using that path, can you explain it please?
This is what I understand, fix me if I am incorrect, need to get facts straight:

*

*git init is for every project

*The git folder under "Users" is local repo and everytime i do git commit, that folder is updated.

*When I do git push , it takes from that local repo, and puts to remote repository.

*When I want to update to "HEAD", I just do git pull

A: That's actually a lot of questions and misunderstandings. I'm not sure I'd be able to address them all so I'm only going to address what's directly asked.

*

*git init is for every project
Almost correct. git init is used to start using git on a project that's not under git. For projects that are already under git you use git clone.

*The git folder under "Users" is local repo
Almost correct. The folder is actually .git not git. This comes from the unix convention that all files and folders that start with a dot are considered hidden.
Secondly, the folder is not under your Users folder. It is under your project folder. So the folder C:/Users/myUser/ is one project. If this is not your intention then you most likely have accidentally executed git init in your User folder.
Each project has one .git folder in the project's root directory and that is the project's repository. This is one of the reasons git is so fast compared to svn or cvs - the entire repository is processed on the local hard disk without any network traffic.

*When I do git push , it takes from that local repo, and puts to remote
Correct, but only for repos that have remotes (which are usually repos that you create by using git clone to copy a remote repo).
Note that the remote repo does not need to be on another machine. You can git clone a project from a local folder into another folder and then you can push changes from the new folder back to the original folder.
The git clone command automatically sets up the necessary config for your repo to connect back to a remote. But you can also manually configure a repo set up with git init to connect to a remote.

*what "manages" it
The .git folder manages your project's repo. Git doesn't run as a server*. Instead the .git folder acts as your local 'server' that all the git commands communicate with. Basically, running a git command edits the contents of the .git folder.
*note: Remote repos do run servers so you can connect to them. But technically they're not really git servers. They're file servers that git can download from and upload to.

A: Your three four understandings are more or less correct, though you're missing a few details.
git init initialises (i.e. creates) a repository. Each project should be in its own repository.
If you downloaded your project using git clone then you don't need to run git init again.
You should be able to copy your project to another directory without any adverse effects. That path was probably chosen by default. Be sure to move the whole directory. The metadata that git needs to run is stored in hidden files in the project's directory.
Pushing and pulling can get complicated, especially when you're working on a project with others, and when you're using branches. It's not really sensible for me to write out a complete intro to the topic here, so I'd suggest you go read Pro Git for a more thorough explanation.

A: git init is only for when you create your own new repository from scratch. It turns a directory into an empty git repository.
When you use git clone to clone an existing repository into a new one, git init is neither necessary nor desired.

A: @Jaanus just one addition to what @slebetman explained regarding git pull. It's not exactly syncing but rather fetching the commits which are not on your local. This is more of a corner case, consider the following -

*

*Assuming to be dealing with a branch test_branch. A, B and C commits exist for origin/test_branch (the branch on your git server) where C is the most recent commit. You have taken a pull and now have A, B and C on your local branch too.

*Let's say for some reason you had to reset the commit B and force re-write history of origin/test_branch leaving the history to be A and C.

*Now when you perform git pull onto your local. It is going to say everything already up to date but notice you have additional changes of commit B. Therefore, do not consider this as a sync operation but more of a get what I don't have operation.
Hope that was helpful.

A: #!bin/bash
DATE=`date +%m%d%Y.%H%M%S`
TARGET="$1.$DATE"
DIR=`pwd`

function batch_convert() {
for file in `ls $1`
do
if [ -d $1"/"$file ]
then
batch_convert $1"/"$file
else
dos2unix $1"/"$file
#echo $1"/"$file
fi
done
}

##################

echo $TARGET
cd $DIR/DCW
git pull
cd ../
batch_convert DCW
cp -R DCW tmp/$TARGET
cd tmp/$TARGET
find . -type d -name "*git*"| xargs -n20 rm -rf

for db in `cat $DIR/tmp/$TARGET/Dblist` ; do
        echo "********** DB IS $db *******"
       for dbfolder in `find * -maxdepth 0 -type d` ;do
    echo `ls -a`
        echo "***** DBFolder is  $dbfolder *****"
    if [ ! $dbfolder = $db ];then
    cp -R $dbfolder $db
    find $db -name "*.ctl"| xargs -I '{}' mv '{}' $db/${db}.ctl
    fi
    done
done
cd ../
tar -cf $TARGET.tar $TARGET


text:
Q: Dúvida com belongsToMany laravel 7 Tenho um relacionamento N:N que esta me dando problema no retorno usando o with() segue o exemplo de minhas duas models com problema e a forma que faço a chamada da consulta.
Model product_type
public function makes()
{
    return $this->belongsToMany(\App\Models\Make::class);
}

Model make
public function productTypes()
{
   return $this->belongsToMany(\App\Models\ProductType::class);
}

Minha table de relação tem os seguintes campos
make_product_type -> nome da tabela
make_id
product_type_id

Em minha controller estou tentando retornar todos os produtos com suas marcas desta forma
Make::with('productTypes')->get()

mas neste ponto é retornado o seguinte erro:
Trying to get property 'make_id' of non-object
Eu já tentei informar os campos do relacionamento na model mas também não deu certo.
A única forma que deu certo foi sobrescrevendo o método toArray() da model e forçando o relacionamento no retorno, o que para mim não é viável visto que só preciso retornar esse relação em um consulta que é executada.
public function toArray()
{
    return [
       'id' => $this->id,
       'name' => $this->name,
       'product_type' => $this->productTypes()->get()->toArray()
     ];
}

Se alguém puder me explicar o que estou fazendo errado e principalmente o por que esta errado agradeceria muito, pois já li várias vezes a documentação do Laravel e não obtive sucesso em entender qual o problema.
Obs. se houver sugestão de mudança na estrutura da tabela também não há problema pois estou iniciando um projeto e neste momento ainda posso mudar as coisas

A: Qual versão utiliza do laravel?
Fez uma tabela Pivo neste caso de N:N?
Tenta fazer assim:
Model Make
public function Products(){
    return $this->belongsToMany(Product_type::class);
}

Model Product_type
public function makes(){
    return $this->belongsToMany(Make::class);
}

Tabela pivo?
(Em ordem alfabética)
public function up()
{
    Schema::create('make_producttype', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('make_id');
        $table->bigInteger('producttype_id');
        $table->timestamps();
    });
}

Na View seria assim para acessar.
        @foreach($make->productsas $pro)

{{$pro->name}}

         @endforeach


text:
Q: Rails, including relationships in json render I have the following code which returns a json with some data that includes @admin_user.companies:
@admin_user = User.find_by_email(email)

render :json=>{:status=>{:code=>200,:token=>@admin_user.authentication_token,
    :user=> @admin_user,
    :companies => @admin_user.companies }}

Each company also have many "locations". How do I include all the locations for every single company in @admin_user.companies in the json?

A: The conventional way is to use
render json: @admin_user.companies, include: :locations

(Please refer to #as_json for more options.)
You don't need to include the status code in your JSON, since it's already in the HTTP headers. Thus, the following might get you close to what you need.
render :json => @admin_user,
  :include => {
    :companies => { :include => :locations },
  },
  :methods => :authentication_token

Side Note
This is just an example. You will have to configure :include and :methods to get exactly what you want. For even more fine-grained control, look into JBuilder or RABL.

A: Another approach is to use jbuilder which allows you much finer-grained control over how your JSON is generated:

*

*Add the jbuilder gem to your app

*Use JBuilder.encode from your controllers to generate JSON

*Alternatively, create .json.jbuilder templates in your views directories


text:
Q: how to add drop shadow while scrolling floating header in listview android(like Gmail) I am using a https://github.com/diegocarloslima/FloatingGroupExpandableListView ,and I have customised rows in the listviews but I am unable to add dropshadow to header when floating over childviews and when it is back in position the dropshadow should disappear .How can I make that feature work with the current code.I really appreciate any help.Thanks in Advance.
SampleActivity
package com.diegocarloslima.fgelv.sample;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.diegocarloslima.fgelv.lib.FloatingGroupExpandableListView;
import com.diegocarloslima.fgelv.lib.WrapperExpandableListAdapter;

public class SampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sample_activity);

        final FloatingGroupExpandableListView list = (FloatingGroupExpandableListView) findViewById(R.id.sample_activity_list);

        final LayoutInflater inflater = getLayoutInflater();

        final View header = inflater.inflate(R.layout.sample_activity_list_header, list, false);
        list.addHeaderView(header);

        final View footer = inflater.inflate(R.layout.sample_activity_list_footer, list, false);
        footer.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/diegocarloslima/FloatingGroupExpandableListView"));
                startActivity(intent);
            }
        });
        list.addFooterView(footer);

        // Even though the child divider has already been set on the layout file, we have to set it again here
        // This prevents a bug where the background turns to the color of the child divider when the list is expanded
        list.setChildDivider(new ColorDrawable(Color.BLACK));

        final SampleAdapter adapter = new SampleAdapter(this);
        final WrapperExpandableListAdapter wrapperAdapter = new WrapperExpandableListAdapter(adapter);
        list.setAdapter(wrapperAdapter);

        for(int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
            list.expandGroup(i);
        }

        list.setOnScrollFloatingGroupListener(new FloatingGroupExpandableListView.OnScrollFloatingGroupListener() {

            @Override
            public void onScrollFloatingGroupListener(View floatingGroupView, int scrollY) {
                float interpolation = - scrollY / (float) floatingGroupView.getHeight();

                // Changing from RGB(162,201,85) to RGB(255,255,255)
                final int greenToWhiteRed = (int) (162 + 93 * interpolation);
                final int greenToWhiteGreen = (int) (201 + 54 * interpolation);
                final int greenToWhiteBlue = (int) (85 + 170 * interpolation);
                final int greenToWhiteColor = Color.argb(255, greenToWhiteRed, greenToWhiteGreen, greenToWhiteBlue);

                // Changing from RGB(255,255,255) to RGB(0,0,0)
                final int whiteToBlackRed = (int) (255 - 255 * interpolation);
                final int whiteToBlackGreen = (int) (255 - 255 * interpolation);
                final int whiteToBlackBlue = (int) (255 - 255 * interpolation);
                final int whiteToBlackColor = Color.argb(255, whiteToBlackRed, whiteToBlackGreen, whiteToBlackBlue);

                final ImageView image = (ImageView) floatingGroupView.findViewById(R.id.sample_activity_list_group_item_image);
                image.setBackgroundColor(greenToWhiteColor);

                final Drawable imageDrawable = image.getDrawable().mutate();
                imageDrawable.setColorFilter(whiteToBlackColor, PorterDuff.Mode.SRC_ATOP);

                final View background = floatingGroupView.findViewById(R.id.sample_activity_list_group_item_background);
                background.setBackgroundColor(greenToWhiteColor);

                final TextView text = (TextView) floatingGroupView.findViewById(R.id.sample_activity_list_group_item_text);
                text.setTextColor(whiteToBlackColor);

                final ImageView expanded = (ImageView) floatingGroupView.findViewById(R.id.sample_activity_list_group_expanded_image);
                final Drawable expandedDrawable = expanded.getDrawable().mutate();
                expandedDrawable.setColorFilter(whiteToBlackColor, PorterDuff.Mode.SRC_ATOP);
            }
        });
    }
}

SampleAdapter
package com.diegocarloslima.fgelv.sample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class SampleAdapter extends BaseExpandableListAdapter {

    private final Context mContext;
    private final LayoutInflater mLayoutInflater;

    private final String[] mGroups = {
            "Cupcake",
            "Donut",
            "Eclair",
            "Froyo",
            "Gingerbread",
            "Honeycomb",
            "Ice Cream Sandwich",
            "Jelly Bean",
            "KitKat"
    };

    private final int[] mGroupDrawables = {
            R.drawable.cupcake,
            R.drawable.donut,
            R.drawable.eclair,
            R.drawable.froyo,
            R.drawable.gingerbread,
            R.drawable.honeycomb,
            R.drawable.ice_cream_sandwich,
            R.drawable.jelly_bean,
            R.drawable.kitkat
    };

    private final String[][] mChilds = {
            {"1.5"},
            {"1.6"},
            {"2.0","2.0.1","2.1"},
            {"2.2","2.2.1","2.2.2","2.2.3"},
            {"2.3","2.3.1","2.3.2","2.3.3","2.3.4","2.3.5","2.3.6","2.3.7"},
            {"3.0","3.1","3.2","3.2.1","3.2.2","3.2.3","3.2.4","3.2.5","3.2.6"},
            {"4.0", "4.0.1", "4.0.2", "4.0.3", "4.0.4"},
            {"4.1", "4.1.1", "4.1.2", "4.2", "4.2.1", "4.2.2", "4.3", "4.3.1"},
            {"4.4"}
    };

    private final String[][] mChilds2 = {
            {"1.5"},
            {"1.6"},
            {"2.0","2.0.1","2.1"},
            {"2.2","2.2.1","2.2.2","2.2.3"},
            {"2.3","2.3.1","2.3.2","2.3.3","2.3.4","2.3.5","2.3.6","2.3.7"},
            {"3.0","3.1","3.2","3.2.1","3.2.2","3.2.3","3.2.4","3.2.5","3.2.6"},
            {"4.0", "4.0.1", "4.0.2", "4.0.3", "4.0.4"},
            {"4.1", "4.1.1", "4.1.2", "4.2", "4.2.1", "4.2.2", "4.3", "4.3.1"},
            {"4.4"}
    };

    public SampleAdapter(Context context) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getGroupCount() {
        return mGroups.length;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return mGroups[groupPosition];
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        if(convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.sample_activity_list_group_item, parent, false);
        }

        final ImageView image = (ImageView) convertView.findViewById(R.id.sample_activity_list_group_item_image);
        image.setImageResource(mGroupDrawables[groupPosition]);

        final TextView text = (TextView) convertView.findViewById(R.id.sample_activity_list_group_item_text);
        text.setText(mGroups[groupPosition]);

        final ImageView expandedImage = (ImageView) convertView.findViewById(R.id.sample_activity_list_group_expanded_image);
        final int resId = isExpanded ? R.drawable.minus : R.drawable.plus;
        expandedImage.setImageResource(resId);

        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return mChilds[groupPosition].length;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return mChilds[groupPosition][childPosition];
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        if(convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.sample_activity_list_child_item, parent, false);
        }

        final TextView text = (TextView) convertView.findViewById(R.id.sample_activity_list_child_item_text);
        text.setText(mChilds[groupPosition][childPosition]);

        final TextView text2 = (TextView) convertView.findViewById(R.id.textView1);
        text2.setText(mChilds2[groupPosition][childPosition]);

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

}

Group_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/sample_activity_list_group_item_image"
        android:layout_width="66dp"
        android:layout_height="66dp"
        android:layout_gravity="center_vertical"
        android:background="#FFA2C955"
        android:padding="3dp" />

    <RelativeLayout
        android:id="@+id/sample_activity_list_group_item_background"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:background="#FFA2C955"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/sample_activity_list_group_item_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:textColor="#FFFFFFFF"
            android:textSize="20sp" />

        <ImageView
            android:id="@+id/sample_activity_list_group_expanded_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp" />
    </RelativeLayout>

</LinearLayout>

sample_Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFEDEDED"
    android:orientation="vertical" >

    <com.diegocarloslima.fgelv.lib.FloatingGroupExpandableListView
        android:id="@+id/sample_activity_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="@android:color/transparent"
        android:childDivider="#FF000000"
        android:divider="#FF000000"
        android:dividerHeight="1dp"
        android:paddingLeft="10dp"
        android:paddingTop="10dp" />

</LinearLayout>


text:
Q: How to generate a report by duplicate in VS 2008 with Microsoft Report I need the same document to be printed twice, but with one single different word when the user does one click. I have tried everything i could come up with but i can't find a way to do it. Any recommendations?

A: There are severals ways to do it, which depends of what you want to change and when.
You could use parameters in your report. What you do is define in your report a parameter and changes its value to whatever suits your need. In local mode, this usually works out pretty welll since you can use parameter pretty much everywhere. I do not know if it works with server mode.
I personally can't see a reason why it doesn't work, but should it happen, there is another way to do it but I don't recommend it. When you click on your button, you can create a copy of your report (i.e. create a new file) and modify the content of the report according to your need. In other word, change the content of the rdlc file to suit your need. RDLC is in fact a xml file so it's possible to modify it, then open the newly created file. Again, I do not know if it works with Server mode. Like mentionned, I do not recommend this option as it implies string manipulation and if you don't know where you're going, you might end up getting more frustation than solutions. If you know exactly what string to change and that this string is not repeated anywhere, you can use reg exp, but since XMl is not a regular language, you have to be really careful when doing so.
Hopes that help.


text:
Q: php session data sometimes getting lost we have a PHP session problem.
Sometimes our application lost sessions. A schema can not be determined. Most times (99,9%) no error occurs.
It is a very large application (over 7,000 PHP pages). The source code has not been changed since the problem occurs. PHP runs on IIS 7.5 and Windows Server 2008.
The session ID is properly transferred from the cookie. The session files that are affected are either no longer available or empty or missing data. It looks as if the data were deleted because the file structure looks correct.
The session locking works.
The sessions are stored on a SAN. We have already saved the session temporarily on an internal hard drive. Same result.
Does anyone have an idea solving the problem?
kind regards
Paul
PS. Sorry about my english!

A: If you have session try session handler. You probably don't want to hard code all those pages but surely there is one or more losing it. Also, this is attributed to browser limitations. If I start up a session on IE and then admin login in Chrome will kill the first session inherently as other session is no longer recognized when reverted SAN. BTW your session timeout period is not mentioned but your talking about (over 7,000 PHP pages). I would advise you create a session variable and pass it around instead of relying on cookie unless your pages orchestrate release or renew a lot hence why your using cookies. Your going to have to make sure all variable sets are unique first though.

A: You should check on your every page if a particular session is set or not. This is a good programming technique. Have you used it in your php code?
You can search for the page where your data is getting lost and then apply the php code in that page.
    if(isset($_POST['your_session'])){
//body;
}
else{
 echo '<script type="text/javascript">'.
        'alert("Session not set !");'.
        '</script>';
}

By this code, you will get the error on behalf of your sessions.


text:
Q: How to configure Anonymous Share in ADS Security Mode Samba3 I have samba server where its configured in ADS security mode and it works fine.
I can perfectly able to login with AD user, where system already joined to same Domain.
Now i need to configure a share to public and need to access from non-domain computers with anonymous access.
Need your assistance.
Server details
Samba3-3.2.15-40 on RHEL5.4 32 Bit OS
Thank You..

A: The share needs to have guest ok = yes, the [global] section needs usershare allow guests = yes and permissions need to be set so other can write to that directory.