Q:

msdeploy overwrite existing file

I am trying to automate the process of importing an application with the IIS Web Deployment Tool. Now we are doing this manually from within the IIS Manager.
I'm using a zip file that is created by using the publish operation from Visual Studio 2015 as source for the package.
When doing this import manually I can choose to overwrite existing files because I am deploying to an existing application. We always choose to only append the files without deleting existing files and folders because we need a folder named "CermData" that contains a certain .ini file that is not included in the zip file.

Using the following line in command promt:
msdeploy.exe -verb:sync -source:package=c:\Users\Administrator\Desktop\Web4Labels\CermWebServices.zip -dest:auto

results in the package being imported the way I want but I lose the "CermData" folder. Is there any way I can make sure the existing files are not overwritten?
Or am I using a wrong approach to do this? I'd like to make this automatic using cmd only if possible.

A:

With msdeploy you'll need to add a the -enableRule:DoNotDeleteRule rule to prevent deletions.
See https://technet.microsoft.com/en-us/library/dd568992(v=ws.10).aspx for details.


Q:

How to save an audio file from firebase while its streaming

So I've been able to setup avplayer to stream the audio directly from firebase link, and I've also been able to set it up to download from firebase. What I'm trying to figure out is if its possible to basically save the file to a file URL while its streaming or when it's done streaming, because performing download task and also setting the players currentitem to stream basically takes twice the network resources.
Also im looking for a swift language solution preferably

A:

In case anyone needs this I solved it by calling this function when the AVplayeritem finished buffering
func saveTrack(asset: AVURLAsset)
{
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A)`

        let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("YourApp/documents/Track01.m4a")

        exporter?.outputURL = fileURL
        exporter?.outputFileType = AVFileType.m4a

        exporter?.exportAsynchronously(completionHandler: {
            print(exporter?.status)
            print(exporter?.estimatedOutputFileLength)
            print(exporter?.maxDuration)
            print("finished ssaving file")
            print()
        })
}


Q:

IPtables - Accept Arbitrary Packets

I've achieved a lot on blocking attacks on GameServers but I'm stuck on something. I've blocked major requests of game-server which it aceepts in the form "\xff\xff\xff\xff" which can be followed by the actual queries like get status or get info to make something like "\xff\xff\xff\xff getstatus " but I see other queries if sent to the game-server will cause it to reply with a "disconnect" packet with the same rate as input so if the input rate is high then the high output of "disconnect" might give lag to the server. Hence I want to block all queries except the ones actual clients use which I suppose are in the form "\xff\xff\xff\xff" or .... so,
I tried using this rule :
    -A INPUT -p udp -m udp -m u32 ! --u32 0x1c=0xffffffff -j ACCEPT

    -A INPUT -p udp -m udp -m recent --set --name Total --rsource
    -A INPUT -p udp -m udp -m recent --update --seconds 1 --hitcount 20 --name Total --rsource -j DROP

Now where the rule does accept the clients but it only blocks requests in the form "\xff\xff\xff\xff getstatus " ( by which GameServer replies with status ) and not just "getstatus " ( by which GameServer replies with disconnect packet ). So I suppose the accept rule is accepting the simple "string" as well. I actually want it to also block the non-(\xff) queries. So how do I modify the rule?

A:

You might want to develop a UDP proxy. UDP is very easy to be proxied, each packet is a complete data structure, so it's easy to filter it.
UDP proxy would be an Linux C application which is receiving packets on port X and resending it to port Y. This could be simple as single loop. In this loop, you can run any kind of check and drop packets by simply not forwarding them.
It's that easy because it seems it's not encrypted traffic.


Q:

Usort Date Xml PHP

I'm trying to order my XML by date but code doesn't work well.
Here is my code
$xml = simplexml_load_file ('http://xml.dsautoestoque.com/?l=09086369000133');
$arr=array();
foreach($xml->veiculo as $aTask)
{
    $arr[]=$aTask;

}

usort($arr, function($a, $b) {
  $ad = new DateTime($a['cadastro']);
  $bd = new DateTime($b['cadastro']);

  if ($ad == $bd) {
    return 0;
  }

  return $ad > $bd ? 1 : -1;
});

I did like this
foreach($arr as $aTask)
{
    $data1 = $aTask->cadastro;
}

But is not returning by date, it is returning this
03/08/2015 18:22
24/11/2015 11:16
22/10/2015 17:36

A:

I think $a and $b are of type SimpleXMLElement and $a['cadastro'] and $b['cadastro'] are null.
So you are instantiating your DateTime's like this new DateTime(null) and that will match this line: if ($ad == $bd) { and your array will not get sorted.
Maybe you can do it like this:
$xml = simplexml_load_file ('http://xml.dsautoestoque.com/?l=09086369000133');

$arr = array();
foreach ($xml->veiculo as $aTask) {
    $arr[] = $aTask;

}

usort($arr, function ($a, $b) {
    $ad = DateTime::createFromFormat('d/m/Y H:i', $a->cadastro->__toString());
    $bd = DateTime::createFromFormat('d/m/Y H:i', $b->cadastro->__toString());

    if ($ad == $bd) {
        return 0;
    }

    return $ad > $bd ? 1 : -1;
});


Q:

Evaluate AngularJS expression within Material Design Lite's mdl-menu

I am building a tiny single-page-application using Angular for the functionality and mdl for the design. I wanted to have a dropdown select box and since mdl doesn't provide this out of the box I built one using mdl-menu. The problem is now that Angular seems to have troubles evaluating expressions I put inside this menu, maybe because the menu is only opened when you click the button? I tried using expressions within the list items and this gives the expression output but also the original expression, which I obviously don't want. I also tried to ng-repeat the list items and then they just don't show up.
<button id="demo-menu-lower-left"
        class="mdl-button mdl-js-button mdl-button--icon">
  more_vert
</button>

{{5+5}}

Another Action

Disabled Action

Yet Another Action

Result pic (Look at the evaluation in the top left, but the original expression is the actual "clickable" action)
Thx in advance!

A:

MDL's javascript (denoted by the mdl-js CSS classes) will probably fool around with the HTML before Angular can do anything, eventually creating HTML that gives strange results when 'parsed' by Angular. It would be best to ensure your HTML gets processed in a strict order: Angular first, MDL second.
If you need to work with the HTML after the initial loading and rendering of the page, it would help to inspect the HTML in the browser instead of relying on the source HTML. Any javascript code (including Angular) will have to work with this and not the HTML represented by the source.


Q:

How to push a value but not a reference

I want to push an array in the other array.I know concat() but what i want is not this.
Two dimensional array
perhaps:
    var a = [],b = [],c = [];
a.push(1);
b.push(a);
console.log(b);      //[[1]]
a.push(2);
console.log(b)       //[[1,2]]
a.push(3);
console.log(b)       //[[1,2,3]]

b will be changed if a is changed,what i want is
 var a = [],b = [],c = [];
a.push(1);
b.push(a);
console.log(b)       //[[1]]
a.push(2);
console.log(b)       //[[1]]
a.push(3);
console.log(b)       //[[1]]

A:

You could point to a two dimension array like b[1][0].
you could use the following code to push an array values into another array
b.push(JSON.parse(JSON.stringify(a));


Q:

Set initial state from navigation props

I am using React Navigation to route between screen. I have an initial screen which contains a FlatList, onclick of an item I route to a new screen while passing params like this.
props.navigation.navigate('Details', {
    id: props.id,
    title: props.title
});

In the Details screen I can receive it using the following code but how do I set the state considering it's a static function and I do not have access to this.setState().
static navigationOptions = ({navigation}) => {
    const {params} = navigation.state;

    console.log(params);
};

A:

This will allow you to handle it in the constructor, which is the other location anything that used to be placed in componentWillMount can go.
constructor(props) {
    super(props)
    this.state = {
        params: props.navigation.state.params
    }
}

For reference, by passing in the props as an argument to constructor and then running the super function on them, you gain the ability to set your initial state or run other one-time functions before any other life-cycle functions are called.


Q:

need help figuring out dynamic menu generation in django

I need to dynamically generate a code like this in the resulting html:

>> gallery one

gallery two

about the author

our news

I do have menu_code string variable created in views.py (it is generated depending on an item number of the current page passed — 1 in the case above), which contains that long string with the code shown above. It is (well, supposed to) passed by locals() into the html template (all other variables are passed that way successfully):
return render_to_response('gallery_page.html', locals())

I have this:
{% include menu_code %}

inside the template html. But instead of being interpreted as code it is just shown as text in the browser.
What am I doing wrong? How to make it work as a dynamically generated menu?

A:

Turned out it's necessary to surround the line in a template with autoescape like that:
{% autoescape off %}
{{ menu_code }}
{% endautoescape %}


Q:

What should I do for my questions to be answered by other users rapidly

I am working as Android programmer. I am working on some Android projects, where I need assistance from the Android experts here in Stack Overflow.
I posted my queries to Stack Exchange accounts, but the number of users that participate in answering the question quite few and also the response time is quite slow.
I found only 20 or 30 views on my post, although I have seen some posts with 200+ views.
What should I do to improve user participation and response time on my posts?

A:

You can offer a bounty on your questions. It attracts the attention of other users to a better extent.
For bounty related queries, refer to  "How do I get attention for old, unanswered questions?"
However wrapping question with suitable set of words can also do the task. For guidelines about how to phrase questions, read the guidelines and FAQs


Q:

find() for std::set

I have a question on how the objects stored in set are compared.
class A
{
public:
char * name;
};

I am storing objects of A in a set. I am provide a comparator class which provides implementation of operator() ( A &ob1, A & ob2 ). Here I compare ob1.name & ob2.name and return true when ob1.name is lesser than ob2.name.
Will I be able to search for an object using the find() of set ? I have provided implementation only for operator(). Will this be sufficient ? Could someone explain how find() works in this case ?
Thanks in advance

A:

Will I be able to search for an object using the find() of set ? I have provided implementation only for operator(). Will this be sufficient ?

Yes, it will be sufficient to provide only comparator class with implementation for operator ()(A&,A&) only. See default comparator std::less<>.

Could someone explain how find() works in this case ?

Very simple speaking: std::set<T,comparator>::find(k) returns iterator it if and only if both comparison fails:

false == comparator(k,*it)
false == comparator(*it, k)

Otherwise it returns std::set<>::end()...

Speaking in mathematical sense - std::set define equality by its weak ordering by this formula:
  a == b  <==>  !(a < b) && !(b < a)

A:

The function that will be used in std::set::find() is an instance of the Comparator class that you declared as a template parameter of your set.
template < class Key, class Compare = less<Key>,
           class Allocator = allocator<Key> > class set;

Concretely, the comparator instance will be passed to Key objects and should return true if the first is located before the second. So yes, your implementation is fine.
Now, to dig further: if you want to convince yourself, you can dig into the source code of gcc’s implementation of the standard library, and you’ll find:
  template<typename _Key, typename _Val, typename _KeyOfValue,
           typename _Compare, typename _Alloc>
    typename _Rb_tree<_Key, _Val, _KeyOfValue,
              _Compare, _Alloc>::iterator
    _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::
    find(const _Key& __k)
    {
      iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k);
      return (__j == end()
          || _M_impl._M_key_compare(__k, _S_key(__j._M_node))) ? end() : __j;
    }

You can see that _M_key_compare (which is an instance of the _Compare class you provided), is called with __k as a first parameter (one of your Key) and the return value of _S_key(...) which is a key. The return value of _M_key_compare is used in a ternary expression, so it should be a boolean.


Q:

Вопросы по поводу inline (встраивания) геттеров

Я пытался разобраться со встраиванием сам, но не особо уверен в некоторых деталях.
Насколько я понял встраивание происходит автоматически, и никаких дополнительных ключевых слов для этого не надо.

Как конкретно встраиваются геттеры? допустим есть геттер:
int getSize() const noexcept { return _size; }
где _size переменная типа int, объявлённая в классе, с этим геттером.
что выдаст компилятор при вызове геттера: obj.getSize();?
этот код просто заменится на obj._size;?
Встраиваются ли функции из статических библиотек?
Встраиваются ли методы шаблонных классов?
Не повредит ли скорости работы программы использование геттеров в методах того же класса, где определены эти самые геттеры. (иногда это просто улучшает читаемость)

Ps. компилятор - Visual c++ самой последней версии.

A:

Все функции встраиваются одинаково. Никаких особенностей именно для "геттеров" нет. На уровне языка вопроса "как встраиваются функции" не существует, ибо такое встраивание ни в чем не проявляется. А все остальное - детали реализации. Да, вполне возможно, что код просто заменится на obj._size.
Однако буквальный код obj.getSize(); обычно будет удален вообще, ибо побочных эффектов у функции нет, а результат вызова никак не используется.

Встраиваться могут только функции, чьи определения целиком и полностью видны в точке их вызова во время компиляции. Так что "статические библиотеки" тут вообще ни при чем. Встраиваемые функции по этой причине определяются в заголовочных файлах. А с каким типом библиотеки идет этот заголовочный файл - никакого значения не имеет.

Шаблонность класса никак не влияет на встраиваемость методов. Это совершенно ортогональные вопросы.
В то же время шаблонность может побочно помогать встраиваемости, ибо шаблоны обычно целиком определяются в заголовочных файлах.

Не повредит. А дальше: пробуйте и смотрите.


Q:

ChangeCalculator for calculating money denominations in change

I'm doing some exercises in OOP and I just created a program that calculates amounts of denominations in a change at the shop. So, let's say something costs 10, I give 25.30 (for some reason), so I should get as a change: one 10, one 5, one 0.20, one 0.10.
When I started to create the program, I thought it would be nice if client of the ChangeCalculator had an option to specify his way of calculating the amounts - for example to use his own currency. That's why I created interfaces.
My program consists of:

IChangeCalculator - represents change calculator
ChangeCalculatorPLN - implementation that returns MoneyAmountPLN (money denominations amounts in PLN currency)
IMoneyAmount - represents data about amounts of denominations
MoneyAmountPLN - represents money denominations amounts in PLN
IMoneyToCoinsConverter - represents converter that converts given money to something that implements IMoneyAmount
MoneyToCoinsConverterPLN - converts given amount of money to MoneyAmountPLN

Here is the source code:
public interface IChangeCalculator<T> where T : IMoneyAmount
{
    T Calculate(decimal price, decimal payedAmount);
}

public class ChangeCalculatorPLN : IChangeCalculator<MoneyAmountPLN>
{
    IMoneyToCoinsConverter<MoneyAmountPLN> _moneyToCoinsConverter;

    public ChangeCalculatorPLN( IMoneyToCoinsConverter<MoneyAmountPLN> moneyToCoinsConverter )
    {
        _moneyToCoinsConverter = moneyToCoinsConverter;
    }

    public MoneyAmountPLN Calculate(decimal price, decimal payedAmount)
    {
        var change = payedAmount - price;
        if (change < 0)
            throw new Exception("The given amount of money is not enough!");
        if (change == 0)
            return MoneyAmountPLN.Empty;

        var amount = GetAmount(change);
        return amount;
    }

    private MoneyAmountPLN GetAmount(decimal change)
    {
        return _moneyToCoinsConverter.Convert(change);
    }
}

public interface IMoneyAmount
{
    IEnumerable<int> GetAmounts( );
}

//MoneyAmountPLN is quite long, because it contains fields for each denomination: 500, 200, 100, 50, 20, 10, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01. I'll not put it here.

public interface IMoneyToCoinsConverter<T> where T : IMoneyAmount
{
    T Convert(decimal money);
}

public class MoneyToCoinsConverterPLN : IMoneyToCoinsConverter<MoneyAmountPLN>
{
    public MoneyAmountPLN Convert(decimal money)
    {
        //logic doesn't really matter here. It returns MoneyAmountPLN with corrects amounts of denominations.
    }

}

The program works, I did some unit tests. My real issue is that I'm not sure if this implementation is a good one. Did I do some mistakes? Could some parts be done better? Personally I think that maybe the structure is a little too complicated? If I saw a program like this for the first time, I would probably feel lost, but I'm not a very good programmer, so I can't say if my feeling is right.
Adding new currency requires creation of new classes that implement: IChangeCalculator, IMoneyAmount, IMoneyToCoinsConverter.
I think that this is too much. I think that ChangeCalculator shouldn't need to be reimplemented for each new currency, but I didn't know how to do that, since each currency requires different IMoneyAmount implementation. Calculate method of ChangeCalculator needs to know what type of IMoneyAmount it returns.
Please provide constructive feedback, it would be great to hear any of your advices.

A:

The main problem with your code is that you've been encoding currency denomination data in C#'s type system: one type for each currency. That somehow led to a complicated interface/generics design, all without providing any real benefits. In fact, this design has several drawbacks:

Each new currency requires additional code (3 extra classes in total).
Apparently the core money-to-coins algorithm needs to be duplicated for each new currency - a proper design should make this reusable across different currencies.
Those generic interfaces aren't very useful: IChangeCalculator<MoneyAmountPLN> is not interchangeable with IChangeCalculator<MoneyAmountEuro>, despite being the 'same' interface.
The IChangeCalculator layer doesn't seem to provide much value: this could easily be done at the call-site.
Wrapping the results in an IMoneyAmount object on which the caller has to call a GetAmounts method seems a little pointless - why not just return those amounts directly?

This can be simplified a lot with a data-driven approach. The core money-to-coins method needs an amount and knowledge about a currency's denominations, and returns a list of coin (or bill) amounts:
public (int amount, decimal denomination)[] SplitIntoDenominations(
    decimal amount,
    decimal[] denominations)

Such a method can easily be reused for different currencies:
var euroDenominations = new decimal[] { 500m, 200m, 100m, ..., 0.05m, 0.02m, 0.01m };
// Denomination arrays can be stored anywhere: in hard-coded arrays,
// in a currency-name/denominations dictionary, or loaded from a file, etc.

var returned = SplitIntoDenominations(amount, euroDenominations);
foreach ((var amount, var denomination) in returned)
    Console.WriteLine($"{amount} coins of €{denomination}.");

You may find it useful to create a CurrencyInfo class that contains a denominations array as well as the name and symbol of the currency, and perhaps additional information, depending on your needs:
var euro = new CurrencyInfo("Euro", "€", new decimal[] { 500m, ..., 0.01m });
var dollar = new CurrencyInfo("Dollar", "$", new decimal[] { 100m, ..., 0.01m });

The same can be done for the return value of this method, if you find an array of named tuples to be insufficient. Again, this depends on your needs, but keep in mind that you only need a single class, regardless of currency.


Q:

What is this kind of toggle switch nut called?

Toggle switches are frequently attached to a mounting surface with a nut that has two indentations on opposite sides.

What is this kind of nut called?
What kind of tool is good for tightening and loosening this fastener?

I usually use needle nose pliers.  They work, but sometimes mar the fastener.

A:

I've always known them as slot or slotted nuts (a type of castellated nut) although I did come across a reference to switch nuts, which makes sense if they are used to fasten switches.

A:

There are probably a few names but I've often heard them referred to as dress nuts. A search on Digikey using that term shows plenty of fairly similar nuts although they don't appear to have any with the slot at the top:
http://www.digikey.com/product-search/en?x=0&y=0&lang=en&site=us&KeyWords=dress+nut
I'm not sure if specialised tools are available but a pair of circlip pliers from your local hardware store might do the job, they are available in a wide variety of styles and sizes so take the switch along with you to find one that suits. Most have round prongs which you could remove to make things easier.


Q:

When removing item from slice will the item remain in underlying array and consume memory

I am making a slice of a structure (user session)
I wat to manage only the current user session in this
So i add a session when user login
And remove when user logout
I was wondering if this can consume memory, if all the removed sessions are present in the underlying array.

A:

Yes the underlying array will remain so the removed item from the slice will still be there in the memory.
best way to handle it is set the item to be removed to 'Zero value' before removing it from the slice.


Q:

try to make path in Google maps from JSON array

I try to make a path in Google Maps ,
firts execute a query and take the result as jeson the query is
SELECT  ST_AsGeoJSON(ST_Transform(geom,4326)) As geom, cost FROM table;

first i take the coordinates as a json array from php the code of json array is
while ($row = pg_fetch_array($result,null, PGSQL_ASSOC)) {

        $row_array['gid'] = $row['gid'];
        $row_array['cost'] = $row['cost'];
        $row_array['coords'] = json_decode($row['geom'], true);

        array_push($json_response,$row_array);

    }

the results from this array is like this
[{"gid":null,"cost":"66.1287777511195","coords":{"type":"LineString","coordinates":[[22.941692442967,40.586863079715],[22.941123079604,40.586455128992]]}},.......,{"gid":null,"cost":"66.0742074916243","coords":{"type":"LineString","coordinates":[[22.942269084347,40.587264319141],[22.941692442967,40.586863079715]]}}]

i try to push in a new array in javascript to plot in map but i can't make it
the code from the java script is
first take the array from php to javascript with
     var jsonAr = <?php echo json_encode($json_response); ?>;

And after with this loop i tray to make the LatLng
var pathAr = new Array();
 for(var i = 0; i < jsonAr.length; i++) {
                  var coords = jsonAr[i].coords.coordinates[0];
            for(var j = 0 ; j < coords.length; j++){
                pathAr.push( new google.maps.LatLng(coords[j][1], coords[j][0]));
            }}

If some one can help. thanks.

A:

This line:
var coords = jsonAr[i].coords.coordinates[0];

should be
var coords = jsonAr[i].coords.coordinates;

A different approach, because your data seems to be perfect for use with the data-layer.
Convert it to geoJSON:
(Not tested):
<?php
   $json_response=array('type'    =>'FeatureCollection',
                        'features'=>array());

   while ($row = pg_fetch_array($result,null, PGSQL_ASSOC)) {

        $json_response['features'][]
          = array('type'=>'Feature',
                  'properties'=>array('gid' => $row['gid'],
                                      'cost'=> $row['cost']
                                     ),
                  'geometry'=>json_decode($row['geom'], true)
                );
    }
?>

var jsonAr = <?php echo json_encode($json_response); ?>;

To draw the lines simply call:
//map ist the google.maps.Map-instance
map.data.addGeoJson(jsonAr);

...done, no need to parse jsonAr.
The difference: Your approach will draw a single line with all points defined in each item of jsonAr, while my approach will draw a separate line for each item.


Q:

How to enable bottom menu button in android 4.0 ICS

I want to enable bottom menu button and Which theme will be use for this menu button.I try many theme but did not work for me by the any theme.How can I achieve this?. Thanks in Advance.

A:

set android:targetSdkVersion="8"  in manifest.xml ,
Image is taken from Samsung galaxy nexus
Example
<uses-sdk
    android:minSdkVersion="8"
    android:maxSdkVersion="17"
    android:targetSdkVersion="8" />


Q:

Switching between modes / Accessing parts of data structure

Given the following data:
    {
        id:         "",
        title:      "",
        // modes
        one: {
            stage:  1,
            order:  3,
            more:   "",
        }
        two: {
            stage:  14,
            order:  5,
            more:   "",
        }
        // ...
    },
    // ...

how can I combine the following two pieces of code into one that uses a variable as a switching mechanism for the mode?
// If selected mode was "one"

    {{ item.title }},
    {{ item.one.stage }}
    // ...

// If selected mode was "two"

    {{ item.title }},
    {{ item.two.stage }}
    // ...

Since the two pieces of code are completely identical - apart from the mode - I would like to avoid code duplication. (Note also that there will eventually be more than just two modes.)

A:

I agree with Michael that you should probably reorganize your code, but if you must have it all at once you can do this depending on what version of angular you are using:
// variable mode is either 'one' or 'two'

    {{ item.title }},
    {{ item[mode].stage }}
    // ...


Q:

Node refactor if/else mess

I'd love some pointers on how to refactor this
async function validate_request_args(req, request_type) {
    let problem_id;
    const errors = [];
    switch (request_type) {
        case "post":
            if (req.body.id == null) {
                errors.push({
                    msg: "Missing id of the problem",
                    param: "id"
                });
            } else {
                problem_id = req.body.id;
            }
            break;

        case "get":
            if (req.query.id == null) {
                errors.push({
                    msg: "Missing id of the problem",
                    param: "id"
                })
            } else {
                problem_id = req.query.id;
            }
            break;
    }
    if (errors.length === 0) {
        const problem = await models.Problem.findByPk(problem_id);
        if (problem == null) {
            errors.push({
                msg: `Problem with id ${problem_id} does not exist `,
                param: "id"
            });
        }
        return monet.Validation.success(problem)
    }
    return monet.Validation.fail(errors);
}

A:

To start with, I see what's likely to be a logic error. At the bottom, you do:
if (problem == null) {
    errors.push({
        msg: `Problem with id ${problem_id} does not exist `,
        param: "id"
    });
}
return monet.Validation.success(problem)

If the problem isn't found, you push an error object to the errors array, but then you return .success anyway and don't use the errors array again. In such a case, I think you want to call monet.Validation.fail with the error object instead, and not call .success.
Once that's done, note that you only ever have at most one element in the errors array, which .fail gets called with. It would be less repetitive to immediately call .fail and return when an error is encountered. Also, since the fail calls are all similar (monet.Validation.fail([{ msg: SOME_MESSAGE, param: 'id' }])), you can make the code DRY by putting that into a helper function:
const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);

Also, switch is almost never the right tool for the job IMO - it's quite verbose and can be error-prone when one forgets to break (which is surprisingly common). If the request type will be either post or get, use the conditional operator to figure out the property to look up on req instead:
const { id } = req[requestType === 'post' ? 'body' : 'query'];

I'd highly recommend against using loose equality ==. It requires an expectation that any reader of the code understands its strange rules. Better to use strict equality. Or, if the id or problem, if it exists, will be truthy (which sounds likely), it would look even nicer to use a truthy test:
if (!id) {
    return fail('Missing id of the problem');
}

If you actually need the logic you're implementing with == to check that the expressions aren't null and aren't undefined (but could be anything else, including other falsey values), then best to test both of those explicitly:
if (id === null || id === undefined) {
    return fail('Missing id of the problem');
}

I think it would also be useful to follow the standard Javascript naming conventions and use camelCase for variable names in most cases.
All together:
const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);
async function validateRequestArgs(req, requestType) {
    const { id } = req[requestType === 'post' ? 'body' : 'query'];
    if (!id) {
        return fail('Missing id of the problem');
    }
    const problem = await models.Problem.findByPk(id);
    if (!problem) {
        return fail(`Problem with id ${id} does not exist`);
    }
    return monet.Validation.success(problem);
}


Q:

How can I save output image from camera directly to file without compression?

After compressing the file and then texting it, it recompresses again and is very choppy
I use Intent to bring up the camera.  I get the result and bring up Intent to send as text.
private void takePic() {
    Intent cameraIntent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(cameraIntent, 2);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 2) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        File file = writebitmaptofilefirst("route_image",photo);
        Uri uri = Uri.fromFile(file);
        fileToDelete = file;
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.putExtra("address", "8001111222");
        sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        sendIntent.setType("image/jpg");
        startActivityForResult(sendIntent,3);
    }
    else if (requestCode == 3){
        if (fileToDelete.exists()) fileToDelete.delete();
    }
}

public static File writebitmaptofilefirst(String filename, Bitmap source) {
    String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    File mFolder = new File(extStorageDirectory + "/temp_images");
    if (!mFolder.exists()) {
        mFolder.mkdir();
    }
    OutputStream outStream = null;
    File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
    if (file.exists()) {
        file.delete();
        file = new File(extStorageDirectory, filename + ".jpg");
        Log.e("file exist", "" + file + ",Bitmap= " + filename);
    }
    try {
        outStream = new FileOutputStream(file);
        source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.e("file", "" + file);
    return file;

}

This works great except the resulting image texted is choppy.  If I send the same pic that ends up in the Gallery it converts that down and the result is 100 times better at the receiving end.  Can I save the Bitmap I get from the camera call directly without compression, the file will be deleted after the sending of the picture.  The user actually takes the pic and then hits the send button on the default sms app.

A:

To save an image directly without compressing use AndroidBmpUtil:
new AndroidBmpUtil().save(source, file);


Q:

TF51005 Query columns other than workitem properties listed?

I'm trying to run this query and it keeps throwing a TF51005 The query references a field that does not exist. Caused by the [Microsoft.VSTS.Common.Severity], I don't know how i'm suppose to pull the severity
select [System.Id], [System.WorkItemType],[Microsoft.VSTS.Common.Severity]
from WorkItems

I'm using a console application with this code
 foreach (WorkItem workItem in queryResults)
            {
                Console.WriteLine("ID: {0}", workItem.Id);
                Console.WriteLine("Title: {0}", workItem.Title);
                Console.WriteLine("State: {0}", workItem.State);
                Console.WriteLine("Reason: {0}", workItem.Reason);

            }

And I realized even if i can pull the column Severity isn't listed as a workitem property. Is it not possible to pull this data?

A:

The query is probably failing because that field is only present some work item types. Specifically, it's present on the Bug, Issue, and Risk work items, depending on your process template selection.
Restrict your query accordingly and it should be fine.
Work items can contain any number of fields, as defined by the process template. The work item object in the TFS API has properties that correspond to the fields that absolutely exist on every work item.
You can access the actual fields by inspecting the Fields property on the work item object.


Q:

Rails app to check the status of a server

I want to achieve a problem, where we manually go and check a webapp/server if it is up/down. I want to build a rails app which can automate this task.
Consider my app url is: HostName:PORT/Route?Params (may or may not have port in url)
I checked 'net/http'
def check_status()
      @url='host'
      uri = URI(@url)
      http = Net::HTTP.new(@url,port)
      response = http.request_get('/<route>?<params>')
      if response == Net::HTTPSuccess
        @result='Running'
      else
        @result='Not Running'
      end
    end

I am facing error at ,
response = http.request_get('/<route>?<params>')

when the app is down throwing 'Failed to open TCP connection to URL' which is correct.
Can you guys help me find some new solution or how can I improve the above implementation?

A:

Since it's working as intended and you just need to handle the error that's returned when the app is down, wrap it in a rescue block.
    def check_status()
      @url='host'
      uri = URI(@url)
      http = Net::HTTP.new(@url,port)
      begin
        response = http.request_get('/<route>?<params>')
        rescue TheClassNameOfThisErrorWhenSiteIsDown
          @result = 'Not Running'
        end
        if response == Net::HTTPSuccess
          @result='Running'
        else
          @result='Not Running'
        end
      end
    end


Q:

Algebra problem in integration by parts

The integral to solve:
$$
\int{5^{sin(x)}cos(x)dx}
$$
I used long computations using integration by parts, but I don't could finalize:
$$
\int{5^{sin(x)}cos(x)dx} = cos(x)\frac{5^{sin(x)}}{ln(5)}+\frac{1}{ln(5)}\Bigg[ \frac{5^{sin(x)}}{ln(5)}-\frac{1}{ln(5)}\int{5^{sin(x)}cos(x)dx} \Bigg]
$$

A:

If you do $\sin x=u$ and $\cos x\,\mathrm dx=\mathrm du$, your integral becomes$$\int 5^u\,\mathrm du.$$


Q:

unable to understand how to loop in loop

I'm writing a java code to loop the data and inside it there is another loop. Below is my code.
String names[] = { "user1", "User2", "User3", "User4", "User5" };
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < names.length; j++) {
        System.out.println(i + " " + names[j]);
    }
}

Thre output that i get is as below, i.e. for each i the user names are getting printed, but i want them to be printed in a series if i values. please see the expected output for better understanding.
Current output:
0 user1
0 User2
0 User3
0 User4
0 User5
1 user1
1 User2
1 User3
1 User4
1 User5
2 user1
2 User2
2 User3
2 User4
2 User5
3 user1
3 User2
3 User3
3 User4
3 User5
4 user1
4 User2
4 User3
4 User4
4 User5
5 user1
5 User2
5 User3
5 User4
5 User5
6 user1
6 User2
6 User3
6 User4
6 User5
7 user1
7 User2
7 User3
7 User4
7 User5
8 user1
8 User2
8 User3
8 User4
8 User5
9 user1
9 User2
9 User3
9 User4
9 User5

Expected output:
0 user1
1 User2
2 User3
3 User4
4 User5
5 user1
6 User2
7 User3
8 User4
9 User5

please let me know how can i achieve this.

A:

You can do it with a single for loop :
for (int i = 0; i < 10 * names.length; i++) {
    System.out.println(i + " " + names[i % names.length]);
}

With this statement i % names.length you would be using the array as ring-buffer. So when you increment i just beyond the length of the array the result of modulo would be 0 and it would continue from there. Which seems to be what you want.
This will print 50 lines as a result, up to 49 User5. If you want 10 lines for example just put this limit as terminating condition in the for loop.
for (int i = 0; i < 10; i++)

A:

This is a good opportunity to learn about the mod operator %:
for (int i = 0; j < 10 ; i++) {
    System.out.println(i + " " + names[i % names.length]);
}

The operator produces the remainder of the division of its left operand (in this case, it's i) by its right operand, names.length, i.e. by 5. As i increases from zero to ten, the series of remainders of division by 5 proceeds as follows:
0 1 2 3 4 0 1 2 3 4

This is a common way to cycle your index back to the beginning of an array without making a separate counter for it.


Q:

How to display the all available commands in oracle database?

I would like to check whether some commands available in database, Is there any command dictionary like that in db apart from Oracle documention?

A:

Check view SELECT * FROM V$RESERVED_WORDS


Q:

Getting wrong annotation from MapView Delegate method

I have declared the following in my .h file:
Annotation *annoForMoreDetails.
However when I try to set it to the current annotation in the method
- (MKAnnotationView *)mapView:(MKMapView *)mapViews viewForAnnotation:(id <MKAnnotation> )annotation

It gets set to the wrong object.
Here is my code:
 - (MKAnnotationView *)mapView:(MKMapView *)mapViews viewForAnnotation:(id <MKAnnotation> )annotation
{
    NSLog(@"welcome into the map view annotation");
    // if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    for (annotation in [mapView annotations]) {
        if ([[mapView annotations] containsObject:annotation]) {
            annoForMoreDetails = annotation;
        }
    }
    if (annoForMoreDetails.coordinate.latitude != mapViews.userLocation.coordinate.latitude && annoForMoreDetails.coordinate.longitude != mapViews.userLocation.coordinate.longitude) {
    // try to dequeue an existing pin view first
    static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
    MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
                                     initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
    pinView.animatesDrop=YES;
    pinView.canShowCallout=YES;
    pinView.pinColor = MKPinAnnotationColorGreen;

    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    [rightButton setTitle:annotation.title forState:UIControlStateNormal];
    [rightButton addTarget:self
                    action:@selector(moreDetails)
          forControlEvents:UIControlEventTouchUpInside];
    pinView.rightCalloutAccessoryView = rightButton;
    return pinView;
    }
    else if (annoForMoreDetails.coordinate.latitude == mapViews.userLocation.coordinate.latitude && annoForMoreDetails.coordinate.longitude == mapViews.userLocation.coordinate.longitude) {
        return nil;
    }
    return nil;
}

- (void)moreDetails {
    annotationCalloutView.frame = CGRectMake(70, 120, 188, 218);
    annotationCalloutView.alpha = 0.0;
    mapView.userInteractionEnabled = NO;
    annotationCalloutView.userInteractionEnabled = YES;
    titleLabel.text = annoForMoreDetails.title;
    titleLabel.numberOfLines = 0;
    titleLabel.userInteractionEnabled = NO;
    addressLabel.text = annoForMoreDetails.subtitle;
    [self.view addSubview:annotationCalloutView];
    [UIView beginAnimations:@"callout" context:NULL];
    [UIView setAnimationDuration:0.6];
    annotationCalloutView.alpha = 1.0;
    [UIView commitAnimations];
}

If you see anything wrong please point it out!

A:

Are you trying to use annoForMoreDetails to know which annotation the user tapped on so you can show more details?  If that's the case, there's an easier way.  Use the map view's calloutAccessoryControlTapped delegate method.  It will be called when the user taps on the accessory button and it will pass the annotation view which includes the annotation as a property.
Remove the annoForMoreDetails instance variable and in viewForAnnotation, remove the for-loop that sets annoForMoreDetails (I think it ends up setting it to the last annotation every time).  Remove all other references to annoForMoreDetails.
Also in viewForAnnotation, remove the addTarget line on the rightButton since you'll replace your custom moreDetails method with an implementation of calloutAccessoryControlTapped:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view
    calloutAccessoryControlTapped:(UIControl *)control
{
    Annotation *annoForMoreDetails = (Annotation *)view.annotation;

    //the code currently in moreDetails method goes here...
}


Q:

OSGI - missing imported package=org.apache.commons.collections

I'm trying to create very simple OSGI bundle with Circular FIFO Buffer. This is the complete source code:  http://www.2shared.com/file/TkLeBBO2/test.html
I created this simple java class:
package com.sh_2.test;

import org.apache.commons.collections.BufferUtils;
import org.apache.commons.collections.buffer.CircularFifoBuffer;

public class Buffer {

      Buffer fifo = (Buffer) BufferUtils.synchronizedBuffer(new CircularFifoBuffer(200));

}

I imported dependency package org.apache.commons.collections. I successfully compiled the code with Netbeans. When I tried to deploy the bundle on Glassfish application server I get this error:
Feb 17, 2012 5:40:22 PM com.sun.enterprise.admin.launcher.GFLauncherLogger info
INFO: JVM invocation command line:
/opt/jdk1.7.0_01/bin/java
-cp
/opt/glassfish3/glassfish/modules/glassfish.jar
-XX:+UnlockDiagnosticVMOptions
-XX:MaxPermSize=192m
-XX:NewRatio=2
-Xmx512m
-client
-javaagent:/opt/glassfish3/glassfish/lib/monitor/flashlight-agent.jar
-Dfelix.fileinstall.disableConfigSave=false
-Djavax.net.ssl.keyStore=/opt/glassfish3/glassfish/domains/domain1/config/keystore.jks
-Djava.awt.headless=true
-Dfelix.fileinstall.poll=5000
-Djava.endorsed.dirs=/opt/glassfish3/glassfish/modules/endorsed:/opt/glassfish3/glassfish/lib/endorsed
-Dfelix.fileinstall.bundles.startTransient=true
-Djavax.net.ssl.trustStore=/opt/glassfish3/glassfish/domains/domain1/config/cacerts.jks
-Dcom.sun.enterprise.security.httpsOutboundKeyAlias=s1as
-DANTLR_USE_DIRECT_CLASS_LOADING=true
-Djava.security.auth.login.config=/opt/glassfish3/glassfish/domains/domain1/config/login.conf
-Dgosh.args=--nointeractive
-Dosgi.shell.telnet.maxconn=1
-Djdbc.drivers=org.apache.derby.jdbc.ClientDriver
-Dfelix.fileinstall.dir=/opt/glassfish3/glassfish/modules/autostart/
-Dosgi.shell.telnet.port=6666
-Djava.security.policy=/opt/glassfish3/glassfish/domains/domain1/config/server.policy
-Dfelix.fileinstall.log.level=2
-Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory
-Dosgi.shell.telnet.ip=127.0.0.1
-Dcom.sun.aas.instanceRoot=/opt/glassfish3/glassfish/domains/domain1
-Dcom.sun.aas.installRoot=/opt/glassfish3/glassfish
-Djava.ext.dirs=/opt/jdk1.7.0_01/lib/ext:/opt/jdk1.7.0_01/jre/lib/ext:/opt/glassfish3/glassfish/domains/domain1/lib/ext
-Dfelix.fileinstall.bundles.new.start=true
-Dorg.glassfish.additionalOSGiBundlesToStart=org.apache.felix.shell,org.apache.felix.gogo.runtime,org.apache.felix.gogo.shell,org.apache.felix.gogo.command,org.apache.felix.fileinstall
-Djava.library.path=/opt/glassfish3/glassfish/lib:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/jre/lib/amd64/server:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/jre/lib/amd64:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
com.sun.enterprise.glassfish.bootstrap.ASMain
-domainname
domain1
-asadmin-args
--host,,,localhost,,,--port,,,4848,,,--secure=false,,,--terse=false,,,--echo=false,,,--interactive=true,,,start-domain,,,--verbose=false,,,--debug=false,,,--domaindir,,,/opt/glassfish3/glassfish/domains,,,domain1
-instancename
server
-verbose
false
-debug
false
-asadmin-classpath
/opt/glassfish3/glassfish/modules/admin-cli.jar
-asadmin-classname
com.sun.enterprise.admin.cli.AsadminMain
-upgrade
false
-type
DAS
-domaindir
/opt/glassfish3/glassfish/domains/domain1
-read-stdin
true
Feb 17, 2012 5:40:22 PM com.sun.enterprise.admin.launcher.GFLauncherLogger info
INFO: Successfully launched in 35 msec.
[#|2012-02-17T17:40:32.867+0200|INFO|null|null|_ThreadID=1;_ThreadName=Thread-2;|Running GlassFish Version: GlassFish Server Open Source Edition 3.1.1 (build 12)|#]

[#|2012-02-17T17:40:32.868+0200|WARNING|null|null|_ThreadID=1;_ThreadName=Thread-2;|Record begin marker is not a proper value so using default.|#]

[#|2012-02-17T17:40:32.868+0200|WARNING|null|null|_ThreadID=1;_ThreadName=Thread-2;|Record end marker is not a proper value so using default.|#]

[#|2012-02-17T17:40:32.868+0200|WARNING|null|null|_ThreadID=1;_ThreadName=Thread-2;|Log Format field separator is not a character so using default.|#]

[#|2012-02-17T17:40:33.237+0200|INFO|glassfish3.1.1|org.glassfish.ha.store.spi.BackingStoreFactoryRegistry|_ThreadID=1;_ThreadName=Thread-2;|Registered org.glassfish.ha.store.adapter.cache.ShoalBackingStoreProxy for persistence-type = replicated in BackingStoreFactoryRegistry|#]

[#|2012-02-17T17:40:33.759+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.services.impl|_ThreadID=30;_ThreadName=Thread-2;|Grizzly Framework 1.9.36 started in: 205ms - bound to [0.0.0.0:8181]|#]

[#|2012-02-17T17:40:33.763+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.services.impl|_ThreadID=29;_ThreadName=Thread-2;|Grizzly Framework 1.9.36 started in: 158ms - bound to [0.0.0.0:3700]|#]

[#|2012-02-17T17:40:33.765+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.services.impl|_ThreadID=33;_ThreadName=Thread-2;|Grizzly Framework 1.9.36 started in: 194ms - bound to [0.0.0.0:4848]|#]

[#|2012-02-17T17:40:33.766+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.services.impl|_ThreadID=32;_ThreadName=Thread-2;|Grizzly Framework 1.9.36 started in: 86ms - bound to [0.0.0.0:7676]|#]

[#|2012-02-17T17:40:33.770+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.admin.adapter|_ThreadID=1;_ThreadName=Thread-2;|The Admin Console is already installed, but not yet loaded.|#]

[#|2012-02-17T17:40:33.763+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.services.impl|_ThreadID=31;_ThreadName=Thread-2;|Grizzly Framework 1.9.36 started in: 253ms - bound to [0.0.0.0:8080]|#]

[#|2012-02-17T17:40:36.063+0200|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=1;_ThreadName=Thread-2;|Started NB_27-api [379]|#]

[#|2012-02-17T17:40:36.067+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=1;_ThreadName=Thread-2;|CORE10010: Loading application NB_27-api-1.0-SNAPSHOT done in 2,094 ms|#]

[#|2012-02-17T17:40:36.072+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=1;_ThreadName=Thread-2;|GlassFish Server Open Source Edition 3.1.1 (12) startup time : Felix (8,046ms), startup services(4,094ms), total(12,140ms)|#]

[#|2012-02-17T17:40:37.610+0200|INFO|glassfish3.1.1|javax.enterprise.system.tools.admin.org.glassfish.server|_ThreadID=47;_ThreadName=Thread-2;|JMXStartupService: Started JMXConnector, JMXService URL = service:jmx:rmi://Testserver:8686/jndi/rmi://Testserver:8686/jmxrmi|#]

[#|2012-02-17T17:41:16.978+0200|INFO|glassfish3.1.1|org.hibernate.validator.util.Version|_ThreadID=68;_ThreadName=Thread-2;|Hibernate Validator 4.1.0.Final|#]

[#|2012-02-17T17:41:16.987+0200|INFO|glassfish3.1.1|org.hibernate.validator.engine.resolver.DefaultTraversableResolver|_ThreadID=68;_ThreadName=Thread-2;|Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.|#]

[#|2012-02-17T17:41:18.023+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.services.impl|_ThreadID=83;_ThreadName=Thread-2;|Grizzly Framework 1.9.36 started in: 68ms - bound to [0.0.0.0:8080]|#]

[#|2012-02-17T17:41:18.787+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.services.impl|_ThreadID=87;_ThreadName=Thread-2;|Grizzly Framework 1.9.36 started in: 3ms - bound to [0.0.0.0:8181]|#]

[#|2012-02-17T17:41:18.934+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.admin.adapter|_ThreadID=90;_ThreadName=Thread-2;|The Admin Console is already installed, but not yet loaded.|#]

[#|2012-02-17T17:41:18.936+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.admin.adapter|_ThreadID=90;_ThreadName=Thread-2;|The Admin Console is starting. Please wait.|#]

[#|2012-02-17T17:41:22.622+0200|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=90;_ThreadName=Thread-2;|WEB0169: Created HTTP listener [http-listener-1] on host/port [0.0.0.0:8080]|#]

[#|2012-02-17T17:41:22.629+0200|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=90;_ThreadName=Thread-2;|WEB0169: Created HTTP listener [http-listener-2] on host/port [0.0.0.0:8181]|#]

[#|2012-02-17T17:41:22.691+0200|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=90;_ThreadName=Thread-2;|WEB0169: Created HTTP listener [admin-listener] on host/port [0.0.0.0:4848]|#]

[#|2012-02-17T17:41:22.833+0200|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=90;_ThreadName=Thread-2;|WEB0171: Created virtual server [server]|#]

[#|2012-02-17T17:41:22.843+0200|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=90;_ThreadName=Thread-2;|WEB0171: Created virtual server [__asadmin]|#]

[#|2012-02-17T17:41:23.440+0200|INFO|glassfish3.1.1|com.sun.jersey.server.impl.application.WebApplicationImpl|_ThreadID=94;_ThreadName=Thread-2;|Initiating Jersey application, version 'Jersey: 1.8 06/24/2011 12:17 PM'|#]

[#|2012-02-17T17:41:23.576+0200|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=90;_ThreadName=Thread-2;|WEB0172: Virtual server [server] loaded default web module []|#]

[#|2012-02-17T17:41:24.659+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.security.com.sun.enterprise.security|_ThreadID=90;_ThreadName=Thread-2;|SEC1002: Security Manager is OFF.|#]

[#|2012-02-17T17:41:24.769+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.security.com.sun.enterprise.security|_ThreadID=90;_ThreadName=Thread-2;|SEC1010: Entering Security Startup Service|#]

[#|2012-02-17T17:41:24.785+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.security.com.sun.enterprise.security|_ThreadID=90;_ThreadName=Thread-2;|SEC1143: Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.|#]

[#|2012-02-17T17:41:24.978+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.security.com.sun.enterprise.security.auth.realm|_ThreadID=90;_ThreadName=Thread-2;|SEC1115: Realm [admin-realm] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.|#]

[#|2012-02-17T17:41:24.983+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.security.com.sun.enterprise.security.auth.realm|_ThreadID=90;_ThreadName=Thread-2;|SEC1115: Realm [file] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.|#]

[#|2012-02-17T17:41:25.029+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.security.com.sun.enterprise.security.auth.realm|_ThreadID=90;_ThreadName=Thread-2;|SEC1115: Realm [certificate] of classtype [com.sun.enterprise.security.auth.realm.certificate.CertificateRealm] successfully created.|#]

[#|2012-02-17T17:41:25.077+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.security.com.sun.enterprise.security|_ThreadID=90;_ThreadName=Thread-2;|SEC1011: Security Service(s) Started Successfully|#]

[#|2012-02-17T17:41:32.985+0200|INFO|glassfish3.1.1|javax.enterprise.resource.webcontainer.jsf.config|_ThreadID=90;_ThreadName=Thread-2;|Initializing Mojarra 2.1.3 (FCS b02) for context ''|#]

[#|2012-02-17T17:41:35.059+0200|INFO|glassfish3.1.1|javax.enterprise.system.tools.admin.org.glassfish.admin.rest.adapter|_ThreadID=94;_ThreadName=Thread-2;|REST00001: Listening to REST requests at context: /management/domain|#]

[#|2012-02-17T17:41:36.492+0200|INFO|glassfish3.1.1|org.hibernate.validator.engine.resolver.DefaultTraversableResolver|_ThreadID=90;_ThreadName=Thread-2;|Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.|#]

[#|2012-02-17T17:41:37.565+0200|INFO|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=90;_ThreadName=Thread-2;|WEB0671: Loading application [__admingui] at [/]|#]

[#|2012-02-17T17:41:37.569+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=90;_ThreadName=Thread-2;|CORE10010: Loading application __admingui done in 18,631 ms|#]

[#|2012-02-17T17:41:37.569+0200|INFO|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.admin.adapter|_ThreadID=90;_ThreadName=Thread-2;|The Admin Console application is loaded.|#]

[#|2012-02-17T17:41:41.756+0200|WARNING|glassfish3.1.1|org.apache.catalina.connector.Request|_ThreadID=93;_ThreadName=Thread-2;|PWC4011: Unable to set request character encoding to UTF-8 from context , because request parameters have already been read, or ServletRequest.getReader() has already been called|#]

[#|2012-02-17T17:41:42.543+0200|INFO|glassfish3.1.1|org.glassfish.admingui|_ThreadID=104;_ThreadName=Thread-2;|Redirecting to /|#]

[#|2012-02-17T17:41:42.797+0200|INFO|glassfish3.1.1|org.glassfish.admingui|_ThreadID=95;_ThreadName=Thread-2;|Admin Console: Initializing Session Attributes...|#]

[#|2012-02-17T17:42:08.433+0200|WARNING|glassfish3.1.1|org.apache.catalina.connector.Request|_ThreadID=68;_ThreadName=Thread-2;|PWC4011: Unable to set request character encoding to UTF-8 from context , because request parameters have already been read, or ServletRequest.getReader() has already been called|#]

[#|2012-02-17T17:42:08.576+0200|INFO|glassfish3.1.1|org.glassfish.admingui|_ThreadID=68;_ThreadName=Thread-2;|GUI deployment: uploadToTempfile|#]

[#|2012-02-17T17:42:08.617+0200|INFO|glassfish3.1.1|org.glassfish.admingui|_ThreadID=68;_ThreadName=Thread-2;|uploadFileName=test-1.0-SNAPSHOT.jar|#]

[#|2012-02-17T17:42:08.849+0200|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=93;_ThreadName=Thread-2;|Installed com.SH_2.test [406] from reference:file:/opt/glassfish3/glassfish/domains/domain1/applications/test-1.0-SNAPSHOT/|#]

[#|2012-02-17T17:42:08.852+0200|SEVERE|glassfish3.1.1|javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=93;_ThreadName=Thread-2;|Exception while invoking class org.glassfish.extras.osgicontainer.OSGiDeployedBundle start method
java.lang.RuntimeException: org.osgi.framework.BundleException: Unresolved constraint in bundle com.SH_2.test [406]: Unable to resolve 406.0: missing requirement [406.0] package; (&(package=org.apache.commons.collections)(version>=3.2.0)(!(version>=4.0.0)))
    at org.glassfish.extras.osgicontainer.OSGiDeployedBundle.startBundle(OSGiDeployedBundle.java:110)
    at org.glassfish.extras.osgicontainer.OSGiDeployedBundle.resume(OSGiDeployedBundle.java:83)
    at org.glassfish.extras.osgicontainer.OSGiDeployedBundle.start(OSGiDeployedBundle.java:67)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:294)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:462)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:384)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1064)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1244)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1232)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:202)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:195)
    at org.glassfish.admin.rest.resources.TemplateListOfResource.createResource(TemplateListOfResource.java:148)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer._service(GrizzlyContainer.java:182)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer.service(GrizzlyContainer.java:147)
    at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:184)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:238)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.osgi.framework.BundleException: Unresolved constraint in bundle com.SH_2.test [406]: Unable to resolve 406.0: missing requirement [406.0] package; (&(package=org.apache.commons.collections)(version>=3.2.0)(!(version>=4.0.0)))
    at org.apache.felix.framework.Felix.resolveBundle(Felix.java:3443)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:1727)
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:922)
    at org.glassfish.extras.osgicontainer.OSGiDeployedBundle.startBundle(OSGiDeployedBundle.java:107)
    ... 55 more
|#]

[#|2012-02-17T17:42:08.882+0200|SEVERE|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=93;_ThreadName=Thread-2;|Exception while loading the app|#]

[#|2012-02-17T17:42:08.890+0200|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=93;_ThreadName=Thread-2;|Uninstalled com.SH_2.test [406]|#]

[#|2012-02-17T17:42:08.894+0200|SEVERE|glassfish3.1.1|javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=93;_ThreadName=Thread-2;|Exception while loading the app : org.osgi.framework.BundleException: Unresolved constraint in bundle com.SH_2.test [406]: Unable to resolve 406.0: missing requirement [406.0] package; (&(package=org.apache.commons.collections)(version>=3.2.0)(!(version>=4.0.0)))
org.osgi.framework.BundleException: Unresolved constraint in bundle com.SH_2.test [406]: Unable to resolve 406.0: missing requirement [406.0] package; (&(package=org.apache.commons.collections)(version>=3.2.0)(!(version>=4.0.0)))
    at org.apache.felix.framework.Felix.resolveBundle(Felix.java:3443)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:1727)
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:922)
    at org.glassfish.extras.osgicontainer.OSGiDeployedBundle.startBundle(OSGiDeployedBundle.java:107)
    at org.glassfish.extras.osgicontainer.OSGiDeployedBundle.resume(OSGiDeployedBundle.java:83)
    at org.glassfish.extras.osgicontainer.OSGiDeployedBundle.start(OSGiDeployedBundle.java:67)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:294)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:462)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:384)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1064)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1244)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1232)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:202)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:195)
    at org.glassfish.admin.rest.resources.TemplateListOfResource.createResource(TemplateListOfResource.java:148)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer._service(GrizzlyContainer.java:182)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer.service(GrizzlyContainer.java:147)
    at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:184)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:238)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
|#]

[#|2012-02-17T17:42:08.921+0200|INFO|glassfish3.1.1|org.glassfish.admingui|_ThreadID=68;_ThreadName=Thread-2;|Exception Occurred :Error occurred during deployment: Exception while loading the app : org.osgi.framework.BundleException: Unresolved constraint in bundle com.SH_2.test [406]: Unable to resolve 406.0: missing requirement [406.0] package; (&(package=org.apache.commons.collections)(version>=3.2.0)(!(version>=4.0.0))). Please see server.log for more details.|#]

I seems that there is dependency problem, maybe a bug into apache commons collections package. I tried with older versions of the package but there is no change. Is this OSGI problem or a bug in apache commons package? How I can repair the code?
Best wishes

A:

It's not a bug. The error message (did you read it?) says that there is a missing dependency on the package org.apache.commons.collections. You need to install the Commons Collections bundle.


Q:

jQuery: Wildcard class selector in removeClass

This code snippet works to remove an existing class, before adding a new one, when I specify it directly (ie, 'ratingBlock', 'ratingBlock1', 'ratingBlock2', etc.). But when I use a wildcard selector in the removeClass ('[class^="ratingBlock"]'), it doesn't work. Am I doing something wrong? Thanks.

Broken

1+

2+

3+

A:

$.removeClass() doesn't take a selector as a parameter, only a class name (or class names).
See: Removing multiple classes (jQuery)
So you basiacally need to call:
$.removeClass('ratingBlock1 ratingBlock2 ratingBlock3 ratingBlock4 ratingBlock5');


Q:

In 1 Corinthians 11:4 why does Paul consider it a dishonor for a man to cover his head when praying or prophesying?

Why does the apostle Paul consider it a dishonour if a man prays with his head covered in 1 Corinthians 11:4?

NIV-UK Every man who prays or prophesies with his head covered dishonours his head.

A:

This is a bewildering passage indeed. Some context from ancient Greek medical literature can help illuminate it, however.

Hippocratic authors hold that hair is hollow and grows primarily from either male or female reproductive fluid or semen flowing into it and congealing (Hippocrates, Nat. puer. 20). Since hollow body parts create a vacuum and attract fluid, hair attracts semen.... Hair grows most prolifically from the head because the brain is the place where the semen is produced or at least stored (Hippocrates, Genit. 1). Hair grows only on the head of prepubescent humans because semen is stored in the brain and the channels of the body have not yet become large enough for reproductive fluid to travel throughout the body (Hippocrates, Nat. puer. 20; Genit. 2). At puberty, secondary hair growth in the pubic area marks the movement of reproductive fluid from the brain to the rest of the body (Hippocrates, Nat. puer. 20; Genit. 1). Women have less body hair not only because they have less semen but also because their colder bodies do not froth the semen throughout their bodies but reduce semen evaporation at the ends of their hair (Hippocrates, Nat. puer. 20).
According to these medical authors, men have more hair because they have more semen and their hotter bodies froth this semen more readily throughout their whole bodies (Hippocrates, Nat. puer. 20). The nature (φύσις) of men is to release or eject the semen. During intercourse, semen has to fill all the hollow hairs on its way from the male brain to the genital area (Aristotle, Probl. 893b.10-17). Thus, men have hair growth on their face, chest, and stomach. A man with hair on his back reverses the usual position of intercourse. A man with long hair retains much or all of his semen, and his long hollow hair draws the semen toward his head area but away from his genital area, where it should be ejected. Therefore, 1 Cor 11:4 correctly states that it is a shame for a man to have long hair since the male nature (φύσις) is to eject rather than retain semen."1

Conversely, the nature of women was to "draw up" semen, and as such should have long hair to increase this "vacuum" effect, increasing the odds of fertility.
While science has clearly made some advancements in the understanding of human physiology, one can sympathize with this worldview given the instruments available in their day and age for conducting medical research. This worldview explains the passage in 1 Corinthians 11:4 and why long hair was disgraceful to a man in the ancient Greek world.
As such, Paul clearly taught that men should not have long hair, in line with Greco-Roman thought on the function of hair and reproductive science.

Footnotes
1 Troy W. Martin, "Paul’s argument from nature for the veil in 1 Corinthians 11:13-15: A testicle instead of a head covering," Journal of Biblical Literature (JBL) 123, no. 1 (2004), 77-78. doi: 10.2307/3268550.
 (read it for free here).

A:

In context, in 1Cor 11, Paul is talking about authority. Jesus is under the father's authority, man is under God's authority, and the woman is under the man (her husband's) authority. The head is the place where decisions are made.
Both men and women are equal, just like Jesus and the father are equal but they have different roles- Jesus himself is subject to the Father.
And when all things shall be subdued unto him, then shall the Son also himself be subject unto him that put all things under him, that God may be all in all.
1 Corinthians 15:28 KJV
To explain this, Paul uses a physical example like he so often does in his epistles. In culture at that time, and even in several cultures today, women cover their head as a symbol of subjection to authority.
So he uses two examples. One -how in culture women cover their head, and two - how even naturally women have longer hair, a natural symbol that they are subject to their husbands.
A woman without a head covering was considered a wanton woman, someone who refused to be subject to her husband's (her head's) authority, who was disrespectful towards him. Similarly for a woman's head to be shaved was considered a disgrace. Paul mentions that here:
But every woman that prayeth or prophesieth with her head uncovered dishonoureth her head: for that is even all one as if she were shaven.  For if the woman be not covered, let her also be shorn: but if it be a shame for a woman to be shorn or shaven, let her be covered.
1 Corinthians 11:5-6 KJV
Jewish men while praying cover their head, a symbol that they are subject to God. However since Paul is writing to gentiles, he is referencing their culture. Men don't cover their head because they aren't subject to someone else's authority, as women are to their husbands.
The line of authority goes thus- Jesus begotten of the Father, Man created by Jesus, woman taken out from the man.
But in case anyone misunderstands,he explains that in Christ both men and women are equal. Just like Jesus and the Father are equal but have different roles.
Nevertheless neither is the man without the woman, neither the woman without the man, in the Lord.
1 Corinthians 11:11 KJV
He summarizes by saying :
But if any man seem to be contentious, we have no such custom, neither the churches of God.
1 Corinthians 11:16 KJV
The example of head coverings is just a physical example to explain to them, there is no such custom or ordinance in the churches.
So no, neither men nor women have to cover their head in church.


Q:

Is it possible to create an Android application directly on the HTC Evo phone?

As a means of simplifying development, I'd like to be able to create and test an application right on my handset.
Is it possible to build an application directly on the HTC Evo phone?

A:

No, sorry. With the Android Scripting Environment, you can write small scripts that run on the device. But the build tools require a fair bit more memory and computing power than an Android phone offers.


Q:

External drive performance for iMovie

I love iMovie and used it to create several projects on my wife's iMac.  I'd like to move all my iMovie resources (from an HD camcorder and my iPhone) to my Macbook Air but I don't feel there is enough hard drive space for me to do so.
Has anyone here used iMovie sourcing documents from an external hard drive?  Could you comment on the performance?  I am not sure if I should be looking at an external thunderbolt hard drive, a usb3 drive, or if even a usb2 drive would suffice as I am not a heavy user.

A:

I haven't used iMovie specifically but I have used Final Cut Pro X. And AFAIK they source media the same way.
Generally, it works excellently if you keep the following things in mind:

The external drive needs to be "fast enough" (Basically: USB 3 or Thunderbolt)*
To save power most external HDDs will enter sleep mode after a certain amount of inactivity. When that happens, it'll generally take a couple of seconds for OS X to wake the drives when you start poking around in iMove again.

(Optionally, HDD sleep can be disabled in System Preferences > Energy Saver but unchecking Put hard disks to sleep when possible)
Short answer
USB 3 should be totally fine for you.
Long answer
"In the old days" (or on older Macs), when using USB 2 drives, you'd run the risk of not being able to read/write fast enough. But with your use-case and a modern Mac, that shouldn't be a problem.
The main rule: In general, the faster the drive, the better. This means Thunderbolt over USB 3 and USB 3 over USB 2 and so on. Opting for 7200 RPM instead of 5200 RPM is also a great choice. In the end it comes down to how much you're willing to spend.
I can't point to an official source but Apple-Certified trainer Larry Jordan has a great article that explains the above points in detail. Also, I work at media company so I have a bit of experience on this.
*I could throw numbers at you but since you mention "camcorder" and "iPhone" as sources, I'm guessing that telling you the number of ProRes 422 streams each connection type can handle, would be immense overkill :)


Q:

php array_diff with sql query and $REQUEST

I want to use array_diff with the result of an mysql query and the result of an $REQUEST here is what I tried:
while($resultarray3 = mysql_fetch_array($result3))
{
$Bestand = $resultarray3['Bestand']
}
$Ergebnis = array_diff($_REQUEST['Menge'], $Bestand);

I got this error by using it: Warning: array_diff(): Argument #2 is not an array in /var/www/html/lager_management/warenkorb.php on line 143
Example for the array $Bestand:
Array ( [0] => 20 [1] => 250 [2] => 90 )

Example for the array $Menge:
Array ([0] => 10 [1] => 45 [3] => 80 )

A:

You are replacing the varible each time in loop.
Try this
$Bestand =array();
while($resultarray3 = mysql_fetch_array($result3))
{
$Bestand[] = $resultarray3['Bestand']
}
$Ergebnis = array_diff($_REQUEST['Menge'], $Bestand);
Need to change/Modify
$Bestand=array()

and
$Bestand[] = $resultarray3['Bestand']


Q:

Does mixing decks in Agricola reduce the chance of synergies?

This is in some ways a followup to Is the Complex deck in Agricola strictly better?.
In Agricola, are there many synergies between cards across decks, or do cards which work towards a certain theme tend to be grouped into the same deck?
I kind of like the idea of mixing the E, I, K (and, when FedEx arrives, G) decks, but does doing so reduce the chance of getting strong combos? If so, would it be better to increase the cards drawn (but still discard or draft down to 7) when combining decks?

In response to the first answer received: I can see that a larger deck reduces the risk of "negative synergy", where some cards are specifically meant to balance other powerful ones by the possibility that an opponent has that card. (Chief and Chief's Daughter, for example.) In fact, that's obviously the case with any card which mentions a specific other card, so, what if we set those cards aside and just consider the rest? Is there a greater or worse chance of getting a set of cards which happens to work together nicely without explicitly saying so?

A:

I'm going to go with my gut response here (again) and say that mixing the decks does dilute the game, but not so much by "reducing the chance of getting strong combos"... more by increasing the chance of being dealt a powerful hand!
The key deck to examine here is the I-deck.  The other two (core set) decks are ostensibly just two piles of assorted cards, one of which contains some allegedly more difficult concepts than the other.  The Interactive Deck though is specifically designed for, well, interactivity.  If you play with just the I-deck the cards in your hand are more likely to interact with the cards in your opponents' hands than if you just mix everything together.
Let's consider the Wood, Clay and Stone Paths in the I-deck.  The Wood Path is a superb card in isolation, giving you 2 Victory Points for the low, low cost of 1 Wood.  And if you've mixed all the decks together into one mega-deck, chances are you can consider it in isolation.  The chance that someone has the Clay Path, or the difficult-to-play Stone Path, is probably small enough to discount.
Whereas if you're playing just the I-deck, chances are high that someone else does have the Clay Path, which makes the Wood Path a much less attractive proposition.  If you use it early as part of a starting player grab, you run the serious risk that someone will take it upon themselves to out-Path you later in the game.  Which forces you to think very hard about the best time to use your Wood Path - as late in the game as possible is probably good.  Which makes the Wood Path a much more interesting card, but obviously a less powerful one...


Q:

What is the name on the bottle of Scotch in the final episode of Star Trek Enterprise?

In the final episode of Star Trek Enterprise, "These are the Voyages", Archer and Trip are drinking a toast from a bottle of Scotch (timestamp 27:23) All I can make out is "20 Year", Malt, "Scotch Whiskey". The name looks like two words or names each beginning with "D". Can anyone make out the name, and is it a real Scotch or something they made up for the show?

A:

With contrast enhanced, you can clearly see the label reads "Brannon & Braga".

This is obviously an in-joke relating to the show's producer, Brannon Braga

A:

While I do not feel that this is a certain answer, not having a copy of the episode in question nor even having watched it, some participants on the talk page of Memory Alpha's article on the episode believe the label is "Berman & Braga", an in-joke referencing Rick Berman and Brannon Braga, the co-creators of the series.


Q:

JSON processing in Android

[{"ip":"127.31.25.145"},{"ip":"196.32.25.256"},{"ip":"10.32.25.256"}]

This a JSON response I get from a php webpage I developed. Now I want to add all values under ip field to a ListActivity. I tried a lot but could do, there are many references out there but even then I couldn't do. This JSON response may contain many more ip values. Its kind of a variable response, gets changed from time to time. Please Help!!!

A:

JSONArray mJsonArray = new JSONArray("Response");
for(int i=0;i< mJsonArray.length();i++)
{
    JSONObject obj =(JSONObject) mJsonArray.get(i);
    String strIp = obj.getString("ip");
    arraylist.add(strIP);
}


Q:

Iterate over test files synchronously with Mocha

I have a set of mocha test scripts (= files), located in /test together with mocha.opts. It seems mocha is running all test files in parallel, is this correct? This could be a problem if test data are used in different test scripts.
How can I ensure, that each file is executed separately?

A:

It seems mocha is running all test files in parallel, is this correct?

No.
By default, Mocha loads the test files sequentially, and records all tests that must be run, then it runs the test one by one, again sequentially. Mocha will not run two tests at the same time, no matter whether the tests are in the same file or in different files. Note that whether your tests are asynchronous or synchronous makes no difference: when Mocha starts an asynchronous test, it waits for it to complete before moving on to the next test.
There are tools that patch Mocha to run tests in parallel. So you may see demonstrations showing Mocha tests running in parallel, but this requires additional tools, and is not part of Mocha properly speaking.
If you are seeing behavior that suggest tests running in parallel, that's a bug in your code, or perhaps you are misinterpreting the results you are getting. Regarding bugs, it is possible to make mistakes and write code that will indicate to Mocha that your test is over, when in fact there are still asynchronous operations running. However, this is a bug in the test code, not a feature whereby Mocha is running tests in parallel.


Q:

Como crear objetos y guardarlos en un arraylist en c#?

Necesito hacer un programa que cree x cantidad de usuarios y pida su nombre y apellido. Cada usuario seria un objeto de la clase Empleado. Lo que no entiendo es como hacer para que el que usa el programa genere esos usuarios y los guarde en un arreglo. Como se crean esos objetos si yo no se cuantos usuarios van a meter en el arreglo? Espero ser claro. Muchas gracias. C#.

A:

A parte de los arrays, en C# existen distintas estructuras de datos que podrían ayudarte. En tu caso particular yo me decantaría por las listas. Con ellas no necesitas, por ejemplo, saber cuantos datos quieres guardar.
Son bastante sencillas de utilizar. Puedes agregar datos:
List<Empleado> empleados = new List<Empleado>();
Empleado e = new Empleado(idEmpleado);

empleados.Add(e);

Puedes hacer búsquedas. Para ello, es buena idea que eches un vistazo a Linq:
empleados.Where(x => x.idEmpleado == 123)

Y eliminar:
empleados.RemoveAll(x => x.idEmpleado == 123)


Q:

Is there any way of changing the font size of the tabs in Chromium?

Is the a way of changing the font size of the tabs in Chromium?
Chromium 8.0.552.237 (70801)

A:

Unfortunately, no. The font size is  hardcoded in the Chromium source code. This issue has been reported here, you can "star" it to be notified of any changes.


Q:

how works or operator in if statements and print

I have two questions
1) how can i make php to check getnext() function,if it exists or what value it has ???
$a = 1;
if($a == 1 or getnext()== 1){
    echo "yeap";                 //this works
}

2)i want to write condition -- if $a or $b is equal to 1 , print the variable name that has the value of 1.
Is it possible to do in php ??can i do it this way???
if($a ==1 or $b==1){
    print($a or $b);
}

thanks in advance:)

A:

You could for example do as follows :
if($a ==1 || $b==1){
   print (($a == 1)? $a : $b);
}


Q:

css and combating text align

the links below the copy that i have on this tab look poor, how can i combat this
http://www.facebook.com/pages/Testing-page-for-pets/142212209151821?v=app_7146470109
its a css issue, best way round this?

A:

The text-align there is set to justify, it is fine for the paragraph, but not for the links.
add a css rule to the links, and set it to left, right or center.
use firebug with firefox to debug such problems.


Q:

How to start developing with microcontrollers?

I want to be able to build my own small electronic device that just has a few buttons, and stores each keypress inside a memory.
I am a pretty experienced programmer but I have no idea where to start regarding hardware, or what to search for on google.
Please give me any info that can help me out.

A:

Arduino boards are inexpensive and the platform is wildly popular.  I buy stuff like that from sparkfun.com in the developer area down the left side of the page.  At sparkfun you will also find many other similar eval boards from various vendors.  I like the lillypad over the arduino pro mini only because it has the programming pins already soldered.   You will want the ftdi usb serial board thing for power and programming.  I am a fan of the armmite pro, which is arm based.  the mbed2 is real easy when you plug it in it shows up like a thumb drive, you copy your .bin file to it and press the button and it loads the program and runs it.  The blue leds give me migraines but that was solved by replacing with green leds.  I have a number of the header style olimex boards, good stuff, have never used the ones with displays and buttons though.  Going to other sites the ez430 msp430 is a good starting platform but no buttons which you are interested in using, the stellaris cortex-m3 based family is good I would skip the 811 board and go for maybe the 1978 or something in that range, the 811 is too easy to brick.
Most of the ones mentioned above (not the olimex boards) have sandboxes for you to play in safely (turn key development environments), but at the same time you are not locked into those environments, you can do your own thing if you like, use different toolchains, flash programmers, etc.  I personally would avoid the lpcxpresso for that reason, painfully tied to both windows and their sandbox.
the sam7-h256 for example, an olimex board, is powered by the usb, and a program called sam-ba is used to load your programs into the chip.  That particular board does not have buttons but boards in that family are also programmed the same way.  basically one usb cable for power and programming.  And like the AVR (arduino and avr butterfly are based on the avr micro) the at91sam7s is an atmel part.  Atmel seems to have that edge over competitors for better documentation and support.  At least my belief is that contributes to the popularity of the avr (the avrfreaks website existed before the avr butterfly and the arduino), and it certainly makes me like their arm based products.
short answer, start with http://www.sparkfun.com along the left side click on Development Tools, and there are many solutions.  You want to find something like the arduino, armmite pro, mbed, that either standalone or with a ftdi based usb thing you both power the board, and have an interface for programming.  There should be links on the page to websites with development tools, compilers, etc, and tools for actually doing the loading of the program on the board.  I recommend trying the arm, avr, and msp430 micros, as well as different vendors (many different arm based solutions with their own pros and cons for example).


Q:

Parsing nested JSON using body-parser and express

I have an iOS app which is sending a JSON packet to a webserver.  The webserver code looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log("MongoDB connection is open.");
});

// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
    X: Number,
    Y: Number,
    Orientation: Number,
    UserID: String,
    Time: String
});

// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);

// create application/json parser
var jsonParser = bodyParser.json();

// URL management
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.post('/update', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    else {
        console.log(req.body);
    }
});

// Start the server
var server = app.listen(3000, function () {
  var host = server.address().address
  var port = server.address().port
  console.log('App listening at %s:%s',host, port)
});

The key part is the app.post method which processes the incoming http request being sent from my iOS app.  At the moment, the method which prints the req.body to the console looks like this:
{
  datapoint_1:
   { timestamp: '2015-02-06T13:02:40:361Z',
     x: 0.6164286615466197,
     y: -0.6234909703424794,
     id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
     orientation: 271.3345946652066 },
  datapoint_2:
   { timestamp: '2015-02-06T13:02:40:961Z',
     x: 0.6164286615466197,
     y: -0.6234909703424794,
     id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
     orientation: 273.6719055175781 }
}

So, you can see the request is a nested JSON object.  Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose).  However, I can't seem to figure out how to do much of anything with the req.body.  I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema.  Can anyone provide some guidance on how to insert these datapoints into the mongoose database?

A:

Set body-parser's extended property to true to allow parsing nested objects.
var express = require('express');
var app = express()
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
    extended: true
}));

A:

Answering my own question.  But, after figuring out how to access the key/value pairs inside the nested JSON object... it became relatively easy to figure out the rest.  The updated app.post function now looks like this:
app.post('/update', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    else {
        for(var datapoint in req.body){
            //create new instance of LocationCollection document
            var point = new LocationsCollection({
                X:Number(req.body[datapoint]["x"]),
                Y:Number(req.body[datapoint]["y"]),
                Orientation:Number(req.body[datapoint]["orientation"]),
                Time:req.body[datapoint]["timestamp"],
                UserID:req.body[datapoint]["id"]
            });
            //insert the newly constructed document into the database
            point.save(function(err, point){
                if(err) return console.error(err);
                else console.dir(point);
            });
        }
    }
});

I can test if this worked by putting the following method inside the callback function once the mongodb connection is first established:
//Find all location points and print to the console.
console.log("Searching for all documents in Location Points Collection");
LocationsCollection.find(function(err,data){
    if(err) console.error(err);
    else console.dir(data);
});

This will print any documents that have been previously added to the database.  Hopefully this helps.


Q:

In QFT, are forces made out of multiple fields?

I’ve been reading about 1,5 books about quantum physics and I’ve also watched a few YouTube videos. In one book, I learnt that there are fields, such as the electromagnetic field, which carries forces between particles (vibrations in the field) via virtual particles. But in another book and on YouTube, they instead say that every elementary particle (quarks, photons, electrons etc.) have their own fields. But what I can’t understand is what the relation of the fields I read about that carries forces to the ones with the particles? Are these forces made up of interactions between multiple fields?

A:

There is no clear notion of what exactly a "force" is in quantum field theory (obligatory xkcd).
Every field has particles associated with it, and we tend to associate those particles/fields with "forces" whose interactions with the rest are such that they have a major influence on their behaviour even when they are not directly involved (e.g. there are no real photons involved in the process that gives the Coulomb force in its classical limit, and no real W/Z-bosons involved in the process that turns protons into neutrons in $\beta^+$-decay).
Massless particles that couple to others in the same way the photon does always produce a classical force like electromagnetism (see this question for the technical background), while massive particles with such a coupling produce a classical force that decays exponentially (cf. Yukawa potential, and see this answer of mine for the residual nuclear force mediated by pions as an example). But even this is oversimplified, since e.g. gluons are massless yet produce no classical force at all since no free color charges can occur due to confinement.


Q:

reduce page weight of google plus button

I am currently developing a website and am wanting to include the google plus button. My problem however is that the google plus button adds an extra 300kb to the page weight. A lot of this comes from one single file that the http://apis.google.com/js/plusone.js file calls.
I've managed to keep the page load time down to a minimum by loading it asynchronously but I would like to know if there's any way to adapt the code to minimise the page weight?
Here is the code I am using...
<script>
    window.___gcfg = {lang: 'en-GB'};

    (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();
</script>

<div id="google-plusone">
    <g:plusone annotation="none" size="medium"></g:plusone>
</div>

Thanks in advance for any help.

A:

You shouldn't really worry about it as it doesn't affect your code startup time. Most users will most likely just have it in cache already and load it from there. Trying to provide your own somehow "minimized" copy is actually counter-productive, because it won't profit from being cached from visiting other sites.