text:
Q: Get total count of in array embedded documents for a MongoDB collection Here is an example MongoDB collection of articles with embedded comments:
{
  _id: 1,
  name: "article_1",
  comments: [
    { title: 'title_1_1', ... },
    { title: 'title_1_2', ... }
  ]
}
{
  _id: 2,
  name: "article_2",
  comments: [
    { title: 'title_2_1', ... },
    { title: 'title_2_2', ... },
    { title: 'title_2_3', ... }
  ]
}

How can I efficiently query for the total count of comments? The result should be 5 for the example above.


text:
Q: Finding elements on Xamarin Test Recorder I am new using on Xamarin Test Recorder and I am not able to find a proper documentation to help me identify specific elements in the app.
By, example, I am trying to automate the use of a date selector, however, even if I specify the exact point where I want to click using the coordinates, the recorder tends to not find the element I want and stops the test.
I know that this is not web automation, but I am not sure if I could be able to find another way to automate those controls.
Any suggestions? Any place where I can be able to read something that could help?

A: In general to click on an element using the ID you defined in the application layout. You need the following code:
app.Tap(x => x.Id("elementId"));

Maybe the element is not the UI yet while executing the code, in that case you need to add a wait for element:
app.WaitForElement(x => x.Id("elementId"), timeout: TimeSpan.FromSeconds(5));

redpajama_set_name: RedPajamaStackExchange


text:
Q: git commit --amend hanging on hint: Waiting for your editor to close the file in vscode Related post: Git hangs with "hint: Waiting for your editor to close the file..." when closing a commit message file in VSCode
I do not like the solution in the above link because it makes an entirely new vscode instance. I used to be able to git commit --amend and then a new tab in my current vscode instance pops up where I then edit the commit message, save, and then close, and the  hint: Waiting for your editor to close the file then disappears. As of this morning, this no longer happens, and I don't think I made any changes in my ~/.gitconfig.
These are my current settings in .gitconfig
[submodule]
    recurse = true
[user]
    name = my_email
    email = my_email
[credential]
    helper = cache --timeout=31536000
[url "https://github.com/"]
  insteadOf = git://github.com/
[alias]
  tree = log --oneline --graph --all --decorate
[core]
    editor = code --wait
[diff]
  tool = vscode
[difftool "vscode"]
  cmd = code -n --wait --diff $LOCAL $REMOTE
[merge]
  tool = vscode
[mergetool "vscode"]
  cmd = code --wait $MERGED

Does anyone know of a solution for this?
P.S. I just tried the solution in the linked post where the amend is routed to a different instance, and that didn't work either. When i closed the new instance, it's still hanging on hint: Waiting for....

A: I don't like that this bug is not fixed.
My solution: I go to my VM and commit via Git GUI, for example.
It clears it on Mac side (that's where my project runs) without re-opening or new instances.


text:
Q: CSS Printing: Avoiding cut-in-half DIVs between pages? I'm writing a plug-in for a piece of software that takes a big collection of items and pops them into HTML in a WebView in Cocoa (which uses WebKit as its renderer, so basically you can assume this HTML file is being opened in Safari).
The DIVs it makes are of dynamic height, but they don't vary too much. They're usually around 200px. Anyway, with around six-hundred of these items per document, I'm having a really rough time getting it to print. Unless I get lucky, there's an entry chopped in half at the bottom and top of every page, and that makes actually using printouts very difficult.
I've tried page-break-before, page-break-after, page-break-inside, and combinations of the three to no avail. I think it might be WebKit not properly rendering the instructions, or maybe it's my lack of understanding of how to use them. At any rate, I need help. How can I prevent the cutting-in-half of my DIVs when printing?

A: page-break-inside: avoid;  definitely does not work in webkit, in fact has been a known issue for 5+ years now https://bugs.webkit.org/show_bug.cgi?id=5097
As far as my research has gone, there is no known method to accomplish this (I am working on figuring out my own hack)
The advice I can give you is, to accomplish this functionality in FF, wrap the content that you don;t want to break ever inside a DIV (or any container) with overflow: auto  (just be careful not to cause weird scroll bars to show up by sizing the container too small).
Sadly, FF is the only browser I managed to accomplish this in, and webkit is the one I am more worried about.

A: In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:
@media print{
* {
    display:inline;
}
script, style {
    display:none;
}
div {
    page-break-inside:avoid;
}

}

It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.
Maybe someone could expand on this.

A: The possible values for page-break-after are: auto, always, avoid, left, right
I believe that you can't use thie page-break-after property on absolutely positioned elements.

A: I have the same problem bu no solution yet. page-break-inside does not work on browsers but Opera. An alternative might be to use page-break-after: avoid; on all child elements of the div to keep togehter ... but in my tests, the avoid-Attribute does not work eg. in Firefox ...
What works in all ppular browsers are forced page breaks using eg. page-break-after: always

A: I had to deal with wkhtmltopdf too.
I'm using Bootstrap 3.3.7 as Framework and need to avoid page break on .row element.
I did the job using those settings:
.myContainer {
    display: grid;
    page-break-inside: avoid;
}

No need to wrap in @media print

A: Using break-inside should work:
@media print {
  div {
    break-inside: avoid;
  }
}

It works on all major browsers:

*

*Chrome 50+

*Edge 12+

*Firefox 65+

*Opera 37+

*Safari 10+

Using page-break-inside: avoid; instead should work too, but has been exactly deprecated by break-inside: avoid.

A: One pitfall I ran into was a parent element having the 'overflow' attribute set to 'auto'. This negates child div elements with the page-break-inside attribute in the print version. Otherwise, page-break-inside: avoid works fine on Chrome for me.

A: page-break-inside: avoid; gave me trouble using wkhtmltopdf.
To avoid breaks in the text add display: table; to the CSS of the text-containing div.
I hope this works for you too. Thanks JohnS.
Edit: Suggest to add this within media block to not break existing styles. ie
@media print {
  div.my-div {
    display: table
  }
}

A: Only a partial solution: The only way I could get this to work for IE was to wrap each div in it's own table and set the page-break-inside on the table to avoid.

A: page-break-inside: avoid; does not seem to always work. It seems to take into account the height and positioning of container elements.
For example, inline-block elements that are taller than the page will get clipped.
I was able to restore working page-break-inside: avoid; functionality by identifying a container element with display: inline-block and adding:
@media print {
    .container { display: block; } /* this is key */

    div, p, ..etc { page-break-inside: avoid; }
}

Hope this helps folks who complain that "page-break-inside does not work".

A: @media print{
    /* use your css selector */
    div{
        page-break-inside: avoid;
    }
}

For all new browser this solution works. See caniuse.com/#search=page-break-inside

A: I got this problem while using Bootstrap and I had multiple columns in each rows.
I was trying to give page-break-inside: avoid; or break-inside: avoid; to the col-md-6 div elements. That was not working.
I took a hint from the answers given above by DOK that floating elements do not work well with page-break-inside: avoid;.
Instead, I had to give page-break-inside: avoid; or break-inside: avoid; to the <div class="row"> element. And I had multiple rows in my print page.
That is, each row only had 2 columns in it. And they always fit horizontally and do not wrap on a new line.
In another example case, if you want 4 columns in each row, then use col-md-3.


text:
Q: Test if value is Long or Integer (no decimal places) I need to test if the value in textbox1 and textbox2 is integer or long (with no decimal places).
I tried something like this:
    Dim x As Integer
    Dim y As Integer

    x = TextBox1.Value
    y = TextBox2.Value

    If x = Int(x) Then
        'my code
    Else
        MsgBox("value is not an integer")

If I put x=2.3 it does not display MsgBox but it rounds the value to 2.

A: Since you've specified the type of x to be an Integer, the conversion from the text box string to the Integer has already taken place. Hence Int(x) is a no-op.
One fix would be to use something like
If IsNumber(TextBox1.Value) Then
    If Fix(TextBox1.Value) = TextBox1.Value Then
        'I am an integeral type.
    End If
End If

Here, Fix truncates a numeric type, and I'm relying on VBA to make the correct comparison. Note that VBA doesn't implement a short-circutted And so you need to use a nested If or similar.

A: You can't Dim var as Decimal in VBA but you can Dim var as Variant and use var = CDec(...) to store a decimal data type in a variant.  Even then, I've found that decimals with 14 or 15 zeroes after the decimal followed by a number (or the equivalent decimal subtracted from a whole number) are rounded to a whole number.  I haven't found a solution yet that differentiates tiny decimals from whole numbers.

A: Here is another approach (pseudo-code, so check syntax!)
Dim l_Temp_D1 as Decimal
Dim l_Temp_D2 as Decimal
Dim l_Temp_I  as Integer

l_Temp_I  = TextBox1.Value
l_Temp_D1 = TextBox1.Value
l_Temp_D2 = l_Temp_I

if (not IsNumber(TextBox1.Value)) then
    ' Error!!!
End If

if (l_Temp_D1 = l_Temp_D2) then
  ' Integer
  ...
else
  ' Float
  ...
End If


text:
Q: ReactNative textcontenttype iOS 13 Issue We are not able to get Email, Name, phone number suggestions (autocomplete) to work on our React Native. Can someone help on troubleshooting to see what we may be doing wrong here?
https://facebook.github.io/react-native/docs/textinput#textcontenttype
<Input
               placeholder="First Name"
               textContentType="givenName"
               onChangeText={firstname => (onChange('first_name', firstname))}
               value={state.form.first_name}
               autoCapitalize="words"
               placeholderTextColor={'#262626'}
               style={styles.textInput}
             />

A: It does work in iOS 13. Just use the settings described here, and translate them from Swift to React Native:
After updating to iOS 13 suggestion(email, phone number, first name...) for UITextField don't appear above keyboard
For phone number:
autoCorrect={true}
textContentType="telephoneNumber"
keyboardType="numbers-and-punctuation"

For email:
autoCorrect={true}
textContentType="emailAddress"
keyboardType="email-address"

You'll need to use a different keyboard type for Android, so probably something like:
keyboardType={(Platform.OS === 'ios') ? "numbers-and-punctuation" : 'phone-pad"}

A: *

*In Android we can use autoCompleteType prop and the supported types
with it are:

So if I talk about telephone number suggestion in android we can use
<TextInput
    autoCorrect={true}
    keyboardType={'phone-pad'}
    autoCompleteType={"tel"}
/>

*

*In iOS we can use textContentType prop and the supported types with
it are:

and telephone number suggestion in iOS we can use
<TextInput
    autoCorrect={true}
    keyboardType={'phone-pad'}
    textContentType={"telephoneNumber"}
/>

No need to create two different TextInput , just use below example to support suggestions to telephone field in react native.
<TextInput
    autoCorrect={true}
    keyboardType={'phone-pad'}
    autoCompleteType={"tel"}
    textContentType={"telephoneNumber"}
/>

A: in react native you can accomplish this like this
 <TextInput
  ...
  textContentType='emailAddress'
  keyboardType='email-address' // a bit of extra love for your users
  autoCapitalize='none' // React Native default is to capitalise
/>


text:
Q: How to change input shape in keras I had downloaded a .h5 file from GitHub and wanted to make predictions from it. I executed the following code:
from keras.models import load_model
from PIL import Image
import numpy as np

im = Image.open('img.jpg')
img = np.array(im)

model = load_model('model_weight.h5')

a = model.predict(img)
print(a)

and got the following error:
ValueError: Input 0 of layer dense_1 is incompatible with the layer: expected axis -1 of input shape to have value 4096 but received input with shape [None, 300, 3]

Here is the model summary:
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            [(None, 4096)]       0
__________________________________________________________________________________________________
input_2 (InputLayer)            [(None, 34)]         0
__________________________________________________________________________________________________
dropout_1 (Dropout)             (None, 4096)         0           input_1[0][0]
__________________________________________________________________________________________________
embedding_1 (Embedding)         (None, 34, 256)      1940224     input_2[0][0]
__________________________________________________________________________________________________
dense_1 (Dense)                 (None, 128)          524416      dropout_1[0][0]
__________________________________________________________________________________________________
lstm_1 (LSTM)                   (None, 34, 256)      525312      embedding_1[0][0]
__________________________________________________________________________________________________
repeat_vector_1 (RepeatVector)  (None, 34, 128)      0           dense_1[0][0]
__________________________________________________________________________________________________
time_distributed_1 (TimeDistrib (None, 34, 128)      32896       lstm_1[0][0]
__________________________________________________________________________________________________
concatenate_1 (Concatenate)     (None, 34, 256)      0           repeat_vector_1[0][0]
                                                                 time_distributed_1[0][0]
__________________________________________________________________________________________________
lstm_2 (LSTM)                   (None, 1000)         5028000     concatenate_1[0][0]
__________________________________________________________________________________________________
dense_3 (Dense)                 (None, 7579)         7586579     lstm_2[0][0]
==================================================================================================
Total params: 15,637,427
Trainable params: 15,637,427
Non-trainable params: 0
__________________________________________________________________________________________________
WARNING:tensorflow:Model was constructed with shape (None, 4096) for input Tensor("input_1:0", shape=(None, 4096), dtype=float32), but it was called on an input with incompatible shape (None, 300, 3).

I know that I have to reshape it but don't know how to do it. Any help would be appreciated.
Thanks

A: Assuming the model accepts square image(where the width and height is equal), the image inputs should be of size (64, 64) and with 1 channel. You can use the following steps to use the model for prediction with images

*

*convert the image from RGB to grayscale

*Resize the image to (64, 64)

*Reshape the image to (1, 4096)

*Feed it to the network.

from keras.models import load_model
from PIL import Image
import numpy as np

im = Image.open('img.jpg').convert('L') # Grayscale conversion
im = im.resize((64, 64)) # Resizing to neccessary size.
img = np.array(im).reshape(1, 4096)

model = load_model('model_weight.h5')

sentence = np.zeros((1, 34));
sentence = model.predict([img, sentence])
print(sentence)

Generation of sentence

stop_token_index = 0;

i = 0;

sentence = np.zeros((1, 34));
while i < sentence.shape[-1]:
    next_word = np.argmax(model.predict([img, sentence]).squeeze())
    if next_word == stop_token_index:
        break
    sentence[0][i] = next_word
    i += 1
print(sentence)


text:
Q: Background task or updating location in iphone I want to make an application that updates users location to my remote server in every xx minute, even the application is in background
I have tried the following code
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    i=0;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    bgTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundTask:) userInfo:nil repeats:YES];

}

-(void)backgroundTask:(NSTimer*)timer{

    i++;
    NSLog(@"%s  %d",__func__,i);
}

But the timer callback stops after around 10 minutes
How can I make an application that continuously updates current location to my server

A: You're probably missing the Background Modes key in your app's Info.plist file:
<key>UIBackgroundModes</key>
    <array>
            <string>location</string>
    </array>

This lets your app access location services while in the background.
But, this type of thing has been asked many times, so also do a little browsing of other stack overflow questions for more information.
Here's another one to read.

A: You can update in background only for 3 minutes.Set Capabilities-> BackgroundFetch on for more or equal than 3 fields
using following code
Call this didenterbackground or foreground
var time = 120
func applicationDidEnterBackground(_ application: UIApplication)
    {
        time = 180
        self.doBackgroundTask()
    }

 var timerBack  = Timer()
    func doBackgroundTask() {

        DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
            self.beginBackgroundUpdateTask()

            self.timerBack = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.displayAlert), userInfo: nil, repeats: true)
            RunLoop.current.add(self.timerBack, forMode: RunLoopMode.defaultRunLoopMode)
            RunLoop.current.run()

            self.endBackgroundUpdateTask()
        }
    }
    var backgroundUpdateTask: UIBackgroundTaskIdentifier!

    func beginBackgroundUpdateTask() {
        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            self.endBackgroundUpdateTask()
        })
    }

    func endBackgroundUpdateTask() {
        UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
        self.backgroundUpdateTask = UIBackgroundTaskInvalid
    }

//Do whatever you want
func displayAlert{

}


text:
Q: PHP __get and __set magic methods Unless I'm completely mistaken, the __get and __set methods are supposed to allow overloading of the → get and set.
For example, the following statements should invoke the __get method:
echo $foo->bar;
$var = $foo->bar;

And the following should use the __set method:
$foo->bar = 'test';

This was not working in my code, and is reproducible with this simple example:
class foo {

    public $bar;
    public function __get($name) {

        echo "Get:$name";
        return $this->$name;
    }

    public function __set($name, $value) {

        echo "Set:$name to $value";
        $this->$name = $value;
    }
}

$foo = new foo();

echo $foo->bar;
$foo->bar = 'test';

echo "[$foo->bar]";

This only results in:
[test]

Putting some die() calls in there shows that it is not hitting it at all.
For now, I just said screw it, and am manually using __get where it's needed for now, but that's not very dynamic and requires knowledge that the 'overloaded' code is in fact not being called unless specifically called. I'd like to know if this is either not supposed to function the way I've understood that it should or why this is not working.
This is running on php 5.3.3.

A: To expand on Berry's answer, that setting the access level to protected allows __get and __set to be used with explicitly declared properties (when accessed outside the class, at least) and the speed being considerably slower, I'll quote a comment from another question on this topic and make a case for using it anyway:
I agree that __get is more slow to a custom get function (doing the same things), this is 0.0124455 the time for __get() and this 0.0024445 is for custom get() after 10000 loops. –  Melsi Nov 23 '12 at 22:32 Best practice: PHP Magic Methods __set and __get
According to Melsi's tests, considerably slower is about 5 times slower. That is definitely considerably slower, but also note that the tests show that you can still access a property with this method 10,000 times, counting time for loop iteration, in roughly 1/100 of a second. It is considerably slower in comparison with actual get and set methods defined, and that is an understatement, but in the grand scheme of things, even 5 times slower is never actually slow.
The computing time of the operation is still negligible and not worth considering in 99% of real world applications. The only time it should really be avoided is when you're actually going to be accessing the properties over 10,000 times in a single request. High traffic sites are doing something really wrong if they can't afford throwing a few more servers up to keep their applications running. A single line text ad on the footer of a high traffic site where the access rate becomes an issue could probably pay for a farm of 1,000 servers with that line of text. The end user is never going to be tapping their fingers wondering what is taking the page so long to load because your application's property access takes a millionth of a second.
I say this speaking as a developer coming from a background in .NET, but invisible get and set methods to the consumer is not .NET's invention. They simply aren't properties without them, and these magic methods are PHP's developer's saving grace for even calling their version of properties "properties" at all. Also, the Visual Studio extension for PHP does support intellisense with protected properties, with that trick in mind, I'd think. I would think with enough developers using the magic __get and __set methods in this way, the PHP developers would tune up the execution time to cater to the developer community.
Edit: In theory, protected properties seemed like it'd work in most situation. In practice, it turns out that there's a lot of times you're going to want to use your getters and setters when accessing properties within the class definition and extended classes. A better solution is a base class and interface for when extending other classes, so you can just copy the few lines of code from the base class into the implementing class. I'm doing a bit more with my project's base class, so I don't have an interface to provide right now, but here is the untested stripped down class definition with magic property getting and setting using reflection to remove and move the properties to a protected array:
/** Base class with magic property __get() and __set() support for defined properties. */
class Component {
    /** Gets the properties of the class stored after removing the original
     * definitions to trigger magic __get() and __set() methods when accessed. */
    protected $properties = array();

    /** Provides property get support. Add a case for the property name to
     * expand (no break;) or replace (break;) the default get method. When
     * overriding, call parent::__get($name) first and return if not null,
     * then be sure to check that the property is in the overriding class
     * before doing anything, and to implement the default get routine. */
    public function __get($name) {
        $caller = array_shift(debug_backtrace());
        $max_access = ReflectionProperty::IS_PUBLIC;
        if (is_subclass_of($caller['class'], get_class($this)))
            $max_access = ReflectionProperty::IS_PROTECTED;
        if ($caller['class'] == get_class($this))
            $max_access = ReflectionProperty::IS_PRIVATE;
        if (!empty($this->properties[$name])
            && $this->properties[$name]->class == get_class()
            && $this->properties[$name]->access <= $max_access)
            switch ($name) {
                default:
                    return $this->properties[$name]->value;
            }
    }

    /** Provides property set support. Add a case for the property name to
     * expand (no break;) or replace (break;) the default set method. When
     * overriding, call parent::__set($name, $value) first, then be sure to
     * check that the property is in the overriding class before doing anything,
     * and to implement the default set routine. */
    public function __set($name, $value) {
        $caller = array_shift(debug_backtrace());
        $max_access = ReflectionProperty::IS_PUBLIC;
        if (is_subclass_of($caller['class'], get_class($this)))
            $max_access = ReflectionProperty::IS_PROTECTED;
        if ($caller['class'] == get_class($this))
            $max_access = ReflectionProperty::IS_PRIVATE;
        if (!empty($this->properties[$name])
            && $this->properties[$name]->class == get_class()
            && $this->properties[$name]->access <= $max_access)
            switch ($name) {
                default:
                    $this->properties[$name]->value = $value;
            }
    }

    /** Constructor for the Component. Call first when overriding. */
    function __construct() {
        // Removing and moving properties to $properties property for magic
        // __get() and __set() support.
        $reflected_class = new ReflectionClass($this);
        $properties = array();
        foreach ($reflected_class->getProperties() as $property) {
            if ($property->isStatic()) { continue; }
            $properties[$property->name] = (object)array(
                'name' => $property->name, 'value' => $property->value
                , 'access' => $property->getModifier(), 'class' => get_class($this));
            unset($this->{$property->name}); }
        $this->properties = $properties;
    }
}

My apologies if there are any bugs in the code.

A: It's because $bar is a public property.
$foo->bar = 'test';

There is no need to call the magic method when running the above.
Deleting public $bar; from your class should correct this.

A: I'd recommend to use an array for storing all values via __set().
class foo {

    protected $values = array();

    public function __get( $key )
    {
        return $this->values[ $key ];
    }

    public function __set( $key, $value )
    {
        $this->values[ $key ] = $value;
    }

}

This way you make sure, that you can't access the variables in another way (note that $values is protected), to avoid collisions.

A: From the PHP manual:

*

*__set() is run when writing data to inaccessible properties.

*__get() is utilized for reading data from inaccessible properties.

This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.

A: Best use magic set/get methods with predefined custom  set/get Methods as in example below. This way you can combine best of two worlds. In terms of speed I agree that they are a bit slower but can you even feel the difference. Example below also validate the data array against predefined setters.

"The magic methods are not substitutes for getters and setters. They
  just allow you to handle method calls or property access that would
  otherwise result in an error."

This is why we should use both.
CLASS ITEM EXAMPLE

    /*
    * Item class
    */
class Item{
    private $data = array();

    function __construct($options=""){ //set default to none
        $this->setNewDataClass($options); //calling function
    }

    private function setNewDataClass($options){
        foreach ($options as $key => $value) {
            $method = 'set'.ucfirst($key); //capitalize first letter of the key to preserve camel case convention naming
            if(is_callable(array($this, $method))){  //use seters setMethod() to set value for this data[key];
                $this->$method($value); //execute the setters function
            }else{
                $this->data[$key] = $value; //create new set data[key] = value without seeters;
            }
        }
    }

    private function setNameOfTheItem($value){ // no filter
        $this->data['name'] = strtoupper($value); //assign the value
        return $this->data['name']; // return the value - optional
    }

    private function setWeight($value){ //use some kind of filter
        if($value >= "100"){
            $value = "this item is too heavy - sorry - exceeded weight of maximum 99 kg [setters filter]";
        }
        $this->data['weight'] = strtoupper($value); //asign the value
        return $this->data['weight']; // return the value - optional
    }

    function __set($key, $value){
        $method = 'set'.ucfirst($key); //capitalize first letter of the key to preserv camell case convention naming
        if(is_callable(array($this, $method))){  //use seters setMethod() to set value for this data[key];
            $this->$method($value); //execute the seeter function
        }else{
            $this->data[$key] = $value; //create new set data[key] = value without seeters;
        }
    }

    function __get($key){
        return $this->data[$key];
    }

    function dump(){
        var_dump($this);
    }
}

INDEX.PHP
$data = array(
    'nameOfTheItem' => 'tv',
    'weight' => '1000',
    'size' => '10x20x30'
);

$item = new Item($data);
$item->dump();

$item->somethingThatDoNotExists = 0; // this key (key, value) will trigger magic function __set() without any control or check of the input,
$item->weight = 99; // this key will trigger predefined setter function of a class - setWeight($value) - value is valid,
$item->dump();

$item->weight = 111; // this key will trigger predefined setter function of a class - setWeight($value) - value invalid - will generate warning.
$item->dump(); // display object info

OUTPUT
object(Item)[1]
  private 'data' =>
    array (size=3)
      'name' => string 'TV' (length=2)
      'weight' => string 'THIS ITEM IS TOO HEAVY - SORRY - EXIDED WEIGHT OF MAXIMUM 99 KG [SETTERS FILTER]' (length=80)
      'size' => string '10x20x30' (length=8)
object(Item)[1]
  private 'data' =>
    array (size=4)
      'name' => string 'TV' (length=2)
      'weight' => string '99' (length=2)
      'size' => string '10x20x30' (length=8)
      'somethingThatDoNotExists' => int 0
object(Item)[1]
  private 'data' =>
    array (size=4)
      'name' => string 'TV' (length=2)
      'weight' => string 'THIS ITEM IS TOO HEAVY - SORRY - EXIDED WEIGHT OF MAXIMUM 99 KG [SETTERS FILTER]' (length=80)
      'size' => string '10x20x30' (length=8)
      'somethingThatDoNotExists' => int 0

A: __get, __set, __call and __callStatic are invoked when the method or property is inaccessible. Your $bar is public and therefor not inaccessible.
See the section on Property Overloading in the manual:

*

*__set() is run when writing data to inaccessible properties.

*__get() is utilized for reading data from inaccessible properties.

The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error. As such, there are much more related to error handling. Also note that they are considerably slower than using proper getter and setter or direct method calls.

A: Drop the public $bar; declaration and it should work as expected.

A: Intenta con:
__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}


text:
Q: Refiner value is not populated in Refiners tab of Search Results Web Part I have created a site column called "mySiteCol1" and performed search such that this column must be populated in the Refiners tab on Search Results Web Part and I can filter the search results.But the column itself is not populated in this tab. What may be the issue that, this site column is not populated? I have already performed full crawl,checked the checkbox for Refineable and sortable and generated managed properties. Any extra configuration do I need to add in the search schema or search results web part.

A: In order for properties to show up in the Refiners you'll have to make sure that the Managed Property has at least Queriable checked and Refineable set to Yes - active.
Also make sure to update the Refiner webpart on the search page to include this Managed Property.

A: Do you check Searchable for managed property?
Is your managed property mapped to crawled property of mySiteCol1?
Are search results you get related to the value of the managed property? Refiner value only is shown up when having relation with search results.


text:
Q: How to access host port after running docker compose up I am dockerizing a React-Flask web application with separate containers for the frontend and the backend Flask API. Up to now I have only run this on my localhost using the default Flask development server. I then installed Gunicorn to prep the application for deployment with Docker later, and that also ran smoothly on my localhost.
After I ran  docker compose up the two images built successfully, are attached to the same network, and I got this in the logs:
Logs For backend:
Starting gunicorn 20.1.0
Listening at: http://0.0.0.0:5000 (1)
Using worker: gthread

Logs For frontend:
react-flask-app@0.1.0 start
react-scripts start
Project is running at http://172.21.0.2/
Starting the development server...

But when I try to access the site at http://172.21.0.2/, localhost:5000 or localhost:3000 it is not accessible. Do I maybe need to add the name of the frontend or backend service?
In Docker Desktop it's showing that the frontend is running at port 5000 but there is no port listed for the backend, it just says it's running.
This is what my files and setup look like:
I added a gunicorn_config.py file as I read it is a good practice, rather than adding all of the arguments to the CMD in the Dockerfile:
bind = "0.0.0.0:5000"
workers = 4
threads = 4
timeout = 120

Then in my Flask backend Dockerfile I have the following CMD for Gunicorn:
FROM python:3.8-alpine
EXPOSE 5000
WORKDIR /app
COPY requirements.txt requirements.txt
ADD requirements.txt /app
RUN pip install --upgrade pip
ADD . /app
COPY . .
RUN apk add build-base
RUN apk add libffi-dev
RUN pip install -r requirements.txt
CMD ["gunicorn", "--config", "gunicorn_config.py", "main:app"]

Here I do "main:app" where my Flask app file is called main.pyand then app is my Flask app object.
I'm generally confused about ports and how this will interact with Gunicorn and in general. I specified port 5000 in the EXPOSE of both of my Dockerfiles.
This is my frontend Dockerfile:
WORKDIR /app
COPY . /app
RUN npm install --legacy-peer-deps
COPY package*.json ./
EXPOSE 3000
ENTRYPOINT [ "npm" ]
CMD ["start"]

And used 5000 in the bind value of my Gunicorn config file. Also, I previously added port 5000 as a proxy in package.json.
I will initially want to run the application using Docker on my localhost but will deploy it to a public host service like Digital Ocean later.
This is my Docker compose file:
services:
  middleware:
   build: .
   ports:
      - "5000:5000"

  frontend:
    build:
      context: ./react-flask-app
      dockerfile: Dockerfile
    ports:
      - "3000:3000"

The other thing to mention is that I also created a wsgi.py file and I was wondering do I need to add this to the Gunicorn CMD in my Dockerfile:
from main import app

if __name__ == "__main__":
    app.run()


text:
Q: Calculating Probability Hi looking for advice on how to calculate the probability of the following.
If someone has a 4% chance of catching a disease (so 4 people out of 100)
Then if they caught the disease they have a 15% chance of it not showing up with tests, so 15 out of 100 who have caught the disease won't be diagnosed with the disease.
What is the overall probability of this happening combined?

A: We use one of the basic rules of probability
$P(AB) = P(A|B)P(B)$
where here $B$ is the event "caught the disease" and $A$ is the event "test comes back negative".
It's simply a matter of substitution from there.


text:
Q: Finding app config file from assembly I'm using Nini to read config throughout the app. I'm running into a problem in assemblies where I want to read the main applications config file (regardless of web.config or app.config).
This is standard way:
private static IConfigSource source = new DotNetConfigSource(DotNetConfigSource.GetFullConfigPath());
The problem in the case of assemblies is that DotNetConfigSource.GetFullConfigPath() returns "assembly.dll.config", not "app.exe.config" or "web.config".
What to do, what to do?

A: System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

string configPath = config.FilePath;

private static IConfigSource source = new DotNetConfigSource(configPath);

Try that.


text:
Q: Logging out using passport-saml: req.logout() or Strategy.logout(), or both? I have a question regarding the proper way to logout a user when using passport-saml for authentication.
The example script with passport-saml shows logging out as this:
app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

From what I can tell, this will end the local passport session, but it doesn't seem to send a logout request to the SAML IdP. When the user does another login, it redirects to the IdP but immediately redirects back with the authenticated user. Is there a way to logout with the IdP so that the user has to enter their password again when signing in to my site? I've seen other sites that use our IdP do this, so I think it's possible.
I did notice in the passport-saml code that there is a logout() method on the passport-saml Strategy object, which doesn't seem to be called by req.logout(). So I tried switching the code to this:
app.get('/logout', function(req, res) {
    //strategy is a ref to passport-saml Strategy instance
    strategy.logout(req, function(){
        req.logout();
        res.redirect('/');
    });
});

But I got this error deep in XMLNode.js
Error: Could not create any elements with: [object Object]
   at XMLElement.module.exports.XMLNode.element (/.../node_modules/passport-saml/node_modules/xmlbuilder/lib/XMLNode.js:74:15)
   at XMLElement.module.exports.XMLNode.element (/.../node_modules/passport-saml/node_modules/xmlbuilder/lib/XMLNode.js:54:25)
   at XMLElement.module.exports.XMLNode.element (/.../node_modules/passport-saml/node_modules/xmlbuilder/lib/XMLNode.js:54:25)
   at new XMLBuilder (/.../node_modules/passport-saml/node_modules/xmlbuilder/lib/XMLBuilder.js:27:19)
   at Object.module.exports.create (/.../node_modules/passport-saml/node_modules/xmlbuilder/lib/index.js:11:12)
   at SAML.generateLogoutRequest (/.../node_modules/passport-saml/lib/passport-saml/saml.js:169:21)

Am I not calling this method correctly? Or should I not be calling this method directly and calling some other method instead?
I see that in generateLogoutRequest() it is referring to two properties on the req.user that I'm not sure are there:
  'saml:NameID' : {
    '@Format': req.user.nameIDFormat,
    '#text': req.user.nameID
  }

If these properties are not there, will that cause this error? If so, I assume that maybe I need to ensure that these properties are added to the user object that is returned from the verify callback function?
Thanks for any help anyone might be able to provide on this.

A: Yes adding the nameIDFormat and nameID to the user will solve the issue.

*

*To enable the logout you should configure the logoutURL option in your strategy

logoutUrl: 'http://example.org/simplesaml/saml2/idp/SingleLogoutService.php',
The logout method in the strategy does not actually send any request. the callback function is called with the request as parameter.
To launch the logout process :
passport.logoutSaml = function(req, res) {
    //Here add the nameID and nameIDFormat to the user if you stored it someplace.
    req.user.nameID = req.user.saml.nameID;
    req.user.nameIDFormat = req.user.saml.nameIDFormat;

    samlStrategy.logout(req, function(err, request){
        if(!err){
            //redirect to the IdP Logout URL
            res.redirect(request);
        }
    });
};

edit: the nameId and nameIdFormat has to be saved somewhere on successful login
var samlStrategy = new SamlStrategy(
  {
    callbackUrl: 'https://mydomain/auth/saml/callback',
    entryPoint: 'https://authprovider/endpoint',
    logoutUrl: 'https://authprovider/logoutEndPoint',
    issuer: 'passport-saml'
  },
  function(profile, done) {

      //Here save the nameId and nameIDFormat somewhere
      user.saml = {};
      user.saml.nameID = profile.nameID;
      user.saml.nameIDFormat = profile.nameIDFormat;

      //Do save

      });
  });

*You will also have to create an end point for the logout callback :

This URL should be configured in your SP metadata in your IdP configuration. The IdP will redirect to that URL once the logout is done.
in your routes :
app.post('/auth/saml/logout/callback', passport.logoutSamlCallback);

In your passport configuration :
passport.logoutSamlCallback = function(req, res){
    req.logout();
    res.redirect('/');
}


text:
Q: can't submit a form on express/angular app in my program there's a validation function on it, if there's an error it will prevent the form to submit and display error msg else it will console.log("Success") but my form cannot be submitted even without any error. is there anyway to enable status code 200 when there is no error ? because now the form prevent me to submit because of status code 400
express
function validateSignup(data,callback) {
        "use strict";
        var USER_RE = /^[a-zA-Z0-9_-]{2,25}$/;
        var PASS_RE = /^.{6,100}$/;
        var EMAIL_RE = /^[\S]+@[\S]+\.[\S]+$/;

        if (!USER_RE.test(data.publicUsername)) {
            callback(new Error('Invalid Public Username try just letters and numbers, e.g: Ed, 69, Kelvin and etc'), null);

        }
        if (!PASS_RE.test(data.password)) {
            callback(new Error('Password must be at least 6 characters long'), null);

        }
        if (data.password != data.confirmPassword) {
            callback(new Error('Password must match'), null);

        }
        if (!EMAIL_RE.test(data.email)) {
            callback(new Error('Invalid email address'), null);

            }
         if (data.email != data.confirmEmail) {
            callback(new Error('Email must match'), null);

        }
        return true;
    }

handlesignup
this.handleSignup = function(req, res, next) {
        "use strict";
    validateSignup(req.body, function(error, data) {
        if(error) {
            res.send(400, error.message);
        } else {
            console.log("success");
        }
    })
    }

Angular
function RegisterCtrl($scope, $http, $location) {
    $scope.form = {};
    $scope.errorMessage = '';
  $scope.submitPost = function() {
    $http.post('/register', $scope.form).
      success(function(data) {
        $location.path('/');
      }).error(function(err) {
        $scope.errorMessage = err;
      });
  };
}

A: You have multiple issues in your code.

*

*Your validateSignup function doesn't always call its callback. If the input passes the validation, it shouldn't return true but instead call its callback with no error and the data:
function validateSignup(data,callback) {
  // ...
  callback(null, data);
}

*You don't always answer the client's request:
validateSignup(req.body, function(error, data) {
   if(error) {
       res.send(400, error.message);
   } else {
       console.log("success");
       res.send(200);
   }
})

Edit: As a side note, a callback should aways be called asynchronously (ie. using process.setImmediate, process.nextTick or setTimeout), but that isn't an issue in your specific case as the callback will always be called synchronously. As noted in Effective JS, item 67:

Never call an asynchronous callback synchronously, even if the data is immediately available.

That's why my advice is to always call callbacks asynchronously, which will free you from weird bugs later on. There are a number of reasons as why you shouldn't do it, but the most obvious is that you can easily blow the stack.
Here's how you you can defer the callback execution:
function validateSignup(data,callback) {
  // ...
  process.setImmediate(function() {
    callback(null, data);
  });
}


text:
Q: Static variable cannot be resolved In my VC++ 2008 project, I create two files, Globals.h and Globals.cpp, as follows:
Glboals.h:
#pragma once

extern ULONG g_ulMAPIUnicodeFlag;

Globals.cpp:
#include "StdAfx.h"
#include "Globals.h"
#include <mapidefs.h>

#ifdef _UNICODE

static ULONG g_ulMAPIUnicodeFlag = MAPI_UNICODE;

#else

static ULONG g_ulMAPIUnicodeFlag = 0;

#endif

Then I use the global variable in another file, TestGlboalDlg.cpp, as follows:
#include "Globals.h"

...

void CTestGlobalDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    ULONG a;

    a = g_ulMAPIUnicodeFlag;
}

But get the following link error:
TestGlobalDlg.obj : error LNK2001: unresolved external symbol "unsigned long g_ulMAPIUnicodeFlag" (?g_ulMAPIUnicodeFlag@@3KA)

Why? If I remove the static modifier in GLobals.cpp, then everything is OK. However, static modifier is required since I need to set the value of the flag at the beginning of the program.
Thanks

A: static is the exact opposite of extern. Do not mix the two.
#ifdef _UNICODE

ULONG g_ulMAPIUnicodeFlag = MAPI_UNICODE;

#else

ULONG g_ulMAPIUnicodeFlag = 0;

#endif


text:
Q: NumPy array to Raster file (GeoTIFF) I converted a raster file (one band grey scale) to an numpy array and set a range to it. I Did like that:
import gdal
import numpy
ds = gdal.Open('H:/GDAL_docs/a.tif')
myarray = numpy.array(ds.GetRasterBand(1).ReadAsArray())
selection = numpy.logical_or(myarray >= 0.3557, myarray <= 0.0753)

That works fine. Now I have the problem to convert the numpy array varriable back to a raster file (my favorite format would be GeoTIFF) is that possible? I also struggle to install rasterio to my osgeo4w64 instalation.

A: By using a raster with integer values (1, 100) and one equivalent condition (myarray >= 35, myarray <= 7), following code would work as expected:
from osgeo import gdal, osr
import numpy

ds = gdal.Open('/home/zeito/pyqgis_data/aleatorio.tif')
band = ds.GetRasterBand(1)
myarray = numpy.array(band.ReadAsArray())
selection = numpy.logical_or(myarray >= 35, myarray <= 7)

new_array = [ [0 for i in range(band.XSize)] for j in range(band.YSize)]

for i, item in enumerate(myarray):
    for j, element in enumerate(item):
        if selection[i][j] == True:
            new_array[i][j] = myarray[i][j]
        else:
            new_array[i][j] = -999

geotransform = ds.GetGeoTransform()
wkt = ds.GetProjection()

# Create gtif file
driver = gdal.GetDriverByName("GTiff")
output_file = "/home/zeito/pyqgis_data/raster_geotiff.tif"

dst_ds = driver.Create(output_file,
                       band.XSize,
                       band.YSize,
                       1,
                       gdal.GDT_Int16)

new_array = numpy.array(new_array)

#writting output raster
dst_ds.GetRasterBand(1).WriteArray( new_array )
#setting nodata value
dst_ds.GetRasterBand(1).SetNoDataValue(-999)
#setting extension of output raster
# top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
dst_ds.SetGeoTransform(geotransform)
# setting spatial reference of output raster
srs = osr.SpatialReference()
srs.ImportFromWkt(wkt)
dst_ds.SetProjection( srs.ExportToWkt() )
#Close output raster dataset

ds = None
dst_ds = None

After running above code, I corroborated in several pixels of raster of following image that myarray >= 35, myarray <= 7 condition worked as expected.


text:
Q: run python with crontab with string dates as arguments I have a python script, which works when I run:
python my_script.py --start_time 2020-09-18-09-00 --end_time 2020-09-18-19-00 >> log_file.log 2>&1

I am trying to run in crontab:
14 16 * * * python my_script.py --start_time 2020-09-18-09-00 --end_time 2020-09-18-19-00 >> log_file.log 2>&1

but it fails - It says that I have a SyntaxError in the python script (which didn`t happen while I ran the python script without crontab).
I guess that I have a mistake in the syntax of the crontab command.
I would appreciate any help.

A: The solution was:
my python version was different from the python in system default path.
for example, if the relevant python version for this script is /usr/bin/python, you have to modify the command to be:
14 16 * * * /usr/bin/python /path/to_my_script/my_script.py --start_time 2020-09-18-09-00 --end_time 2020-09-18-19-00 >> log_file.log 2>&1


text:
Q: Normal looking text file, detected by file as ASCII Pascal program text I have a "normal" looking text file (contains english sentences) which is getting detected by file command as ASCII Pascal program text.
How does Pascal program text differentiate itself from normal ASCII English text?
I did head -10 file > tmp
file tmp still shows Pascal.
tmp when opened in VI and :set list
HELEN'S BABIES$
$
With some account of their ways, innocent, crafty, angelic, impish,$
witching and impulsive; also a partial record of their actions during$
ten days of their existence$
$
By JOHN HABBERTON$
$
$
$

Output of head file | od -c
0000000   H   E   L   E   N   '   S       B   A   B   I   E   S  \n  \n
0000020   W   i   t   h       s   o   m   e       a   c   c   o   u   n
0000040   t       o   f       t   h   e   i   r       w   a   y   s   ,
0000060       i   n   n   o   c   e   n   t   ,       c   r   a   f   t
0000100   y   ,       a   n   g   e   l   i   c   ,       i   m   p   i
0000120   s   h   ,  \n   w   i   t   c   h   i   n   g       a   n   d
0000140       i   m   p   u   l   s   i   v   e   ;       a   l   s   o
0000160       a       p   a   r   t   i   a   l       r   e   c   o   r
0000200   d       o   f       t   h   e   i   r       a   c   t   i   o
0000220   n   s       d   u   r   i   n   g  \n   t   e   n       d   a
0000240   y   s       o   f       t   h   e   i   r       e   x   i   s
0000260   t   e   n   c   e  \n  \n   B   y       J   O   H   N       H
0000300   A   B   B   E   R   T   O   N  \n  \n  \n  \n
0000314

File uploaded here: http://www.fileswap.com/dl/L0eCWJTvy/
I'm on CentOS release 6.5, file version 5.04
There is something in the 4th line. Removing from 4th line onwards detects it as only text file

A: I was able reproduce this both on OS X 10.6.8 and OpenBSD 5.5-current.
Printing out debug information using file -D tmp, it turns out that your text file fails roughly 2000 tests before file(1) recognizes the Pascal keyword record and decides that it must be a Pascal program text.
A minimal working example can be obtained as follows:
$ echo record > test
$ file test
test: ASCII Pascal program text

After numerous heuristics, only the "third & last set of tests, based on hardwired assumptions" in ascmagic.c applies. These tests recognize "file types that we know based on keywords that can appear anywhere in the file". Therefore, minimal changes to your file result in the correct identification as ASCII English text, for example changing their to the in the third line.


text:
Q: wp_get_nav_menu_items how to exclude sub level menu items? I have the following function to output a custom menu in select format for a responsive design I'm working on.
It's working exactly how I want it to apart from I would need to exclude sub menu items. At the moment it includes all levels.
Does anyone know how I can tell wp_get_nav_menu_itemsto only display top level menu items please?
function jeMobileMenu( $args ) {

        // Set up defaults arguments
        $defaults = array (
            'menuSlug'      =>  '',
            'placeholder'   =>  'Menu',
            'prefix'        =>  ' » ',
            'navID'         =>  'mobileNav',
            'navClass'      =>  ''
        );

        // Parse incomming $args into an array and merge it with $defaults
        $args = wp_parse_args( $args, $defaults );

        //Declare each item in $args as its own variable i.e. $menuSlug, $placeholder
        extract( $args, EXTR_SKIP );

        // If no menu slug has been passed then lets bail
        if ( empty($menuSlug) )
            return;

        // If the menu slug that has been passed doesn't correspond to an exisiting menu then lets bail
        if ( !has_nav_menu( $menuSlug ) )
            return;

        $locations = get_nav_menu_locations();
        $menu = wp_get_nav_menu_object( $locations[ $menuSlug ] );

        $menu_items = wp_get_nav_menu_items($menu->term_id);

        // Wrap the select in a nav element with passed id and classes
        $menu_output = '<nav id="' . $navID . '" class="' . $navClass . '">';

        $menu_output .= '<select id="menu-' . $menuSlug . '" onchange="window.open(this.options[this.selectedIndex].value,\'_top\')">';

        // Add placeholder and home link
        $menu_output .= '<option value="">' . $placeholder . '</option>';
        $menu_output .= '<option value="' . home_url( '/' ) . '">' . $prefix . 'Home</option>';

        // Now loop through all the menu items and create them as options in the select list
        foreach ( (array) $menu_items as $key => $menu_item ) {
            $title = $menu_item->title;
            $url = $menu_item->url;
            $menu_output .= '<option value="' . $url . '">' . $prefix . $title . '</option>';
        }
        $menu_output .= '</select>';

        $menu_output .= '</nav>';

        echo $menu_output;
    }

A: Think I worked it out!!
I did a print_r on each $menu_item and saw there's an array key called menu_item_parent in there.
So I changed this:
foreach ( (array) $menu_items as $key => $menu_item ) {
    $title = $menu_item->title;
    $url = $menu_item->url;
    $menu_output .= '<option value="' . $url . '">' . $prefix . $title . '</option>';
}

to this:
foreach ( (array) $menu_items as $key => $menu_item ) {
    if ( $menu_item->menu_item_parent == 0 ) :
        $title = $menu_item->title;
        $url = $menu_item->url;
        $menu_output .= '<option value="' . $url . '">' . $prefix . $title . '</option>';
    endif;
}

Now it will only pull menu items without a menu item parent.


text:
Q: Doctrine QueryBuilder - add PARTITION selection in clause FROM I have a table "actions" with partitions
PARTITION BY RANGE (MONTH(`created_at`)) (
        PARTITION `m1` VALUES LESS THAN (2),
        PARTITION `m2` VALUES LESS THAN (3),
        PARTITION `m3` VALUES LESS THAN (4),
        PARTITION `m4` VALUES LESS THAN (5),
        PARTITION `m5` VALUES LESS THAN (6),
        PARTITION `m6` VALUES LESS THAN (7),
        PARTITION `m7` VALUES LESS THAN (8),
        PARTITION `m8` VALUES LESS THAN (9),
        PARTITION `m9` VALUES LESS THAN (10),
        PARTITION `m10` VALUES LESS THAN (11),
        PARTITION `m11` VALUES LESS THAN (12),
        PARTITION `m12` VALUES LESS THAN (13)
        );

I want to select partitions in clause FROM:
SELECT t1.*
FROM actions PARTITION (m6, m7) as t1
WHERE t1.created_at >= NOW() - INTERVAL 14 DAY

(It is the MySql)
but I don't now how that add to Doctrine QueryBuilder

A: Doctrine does not support that in query builder. You either have to write native SQL or create custom DQL function.


text:
Q: Array value duplicated I'm creating a webshop cart, in my cart there is an array of products.
let cars = ["Saab", "Volvo", "BMW", "Volvo"];

for (var i = 0; i < cars.length; i++) {
  document.body.innerHTML += '
' + cars[i] + '
';
}

I'm getting the following:

Saab
  Volvo
  BMW
  Volvo

What I need is:

Saab
  Volvo x2
  BMW

What is the best way to do this?

A: This is a fairly basic programming question. I won't hand you the answer, but I can give you the general structure of how your solution could look like.
Your input is an array with several unordered items, and the first thing you want is
to create a new structure that groups items with the same name.
To do this, I would create a separate object that contains items and how often they appear. You should use a Map.
Loop through the cars array and add an entry to the Map for every car. You can use the car type as a key and the value should be how often you've seen the car.
So for every loop you:

*

*check if the car exists in the Map

*If yes, increment by 1

*If no, create a new entry and set its value to 1.

At the end you have a key->value map with items and their counts.
Now you can loop through your Map and simply output car types one by one and append 2x if there were more than 1.

A: You could take a Map for counting and iterate this map for getting the rendering.

let cars = ["Saab", "Volvo", "BMW", "Volvo"],
    count = cars.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map);

count.forEach((v, k) => document.body.innerHTML += '
' + k + (v > 1 ? ' x' + v : '') + '
');

A: Convert the initial array into a map. The key of each element in the map is the name of the car and the value is the number of occurrences of the car in the initial list.
Iterate the car map and generate your HTML string.
It is kind of strange that you are setting the HTML for the whole document, but the below snippet should get you what you are looking for.

// initial car array
let carArr = ["Saab", "Volvo", "BMW", "Volvo"];
console.log(carArr);

// convert to a map with counts
let carObj = {};
for (let car of carArr) {
  carObj[car] = 1 + (carObj[car] || 0);
}
console.log(carObj);

// concatenate the HTML string
var s = "";
for (let car in carObj) {
  s += '
' + car + (carObj[car] > 1 ? ' x' + carObj[car] : '') + '
';
}
// set the body HTML
document.body.innerHTML += s;

A: You will need to pre-process the list, like this:

let cars = ["Saab", "Volvo", "BMW", "Volvo"];

const map = new Map();
for (const car of cars) {
  const count = map.get(car) || 0;
  map.set(car, count + 1);
}

for (const [name, count] of map) {
   const suffix = count > 1 ? ' x' + count : '';
   document.body.innerHTML += '
' + name + suffix + '
';
}


text:
Q: llenado de formulario PHP y envió de correo automático Realizo un modulo en php donde se levanta un ticket de trabajo, lo que quiero que haga es que al llenar y enviar el formulario envié automáticamente un correo con los datos que lleno el usuario de confirmación espero en verdad me puedan orientar. Anexo mi código.
Saludos

<?php
    $priorities =mysqli_query($con, "select * from priority");
    $turns =mysqli_query($con, "select * from turn");
    $areas =mysqli_query($con, "select * from area");
    $statuses =mysqli_query($con, "select * from status");
    $kinds =mysqli_query($con, "select * from kind");
    $categories =mysqli_query($con, "select * from category");

?>

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg-add"> Agregar Ticket</button>

                    <button type="button" class="close" data-dismiss="modal">×
                    </button>

Agregar Tickets

                    <form class="form-horizontal form-label-left input_mask" method="post" id="add" name="add">

                            Tipo

                                <select class="form-control" name="kind_id" >
                                      <?php foreach($kinds as $p):?>
                                        <option value="<?php echo $p['id']; ?>"><?php echo $p['name']; ?></option>
                                      <?php endforeach; ?>
                                </select>

                            Titulo*

                              <input type="text" name="title" class="form-control" placeholder="Titulo" >

                            Descripción *

                              <textarea name="description" class="form-control col-md-7 col-xs-12"  placeholder="Descripción"></textarea>

                            Seguimiento de Proceso

                              <textarea name="process_1" class="form-control col-md-7 col-xs-12"  placeholder="Seguimiento de Proceso"></textarea>

                            Fin de Proceso

                              <textarea name="process_2" class="form-control col-md-7 col-xs-12"  placeholder="Fin de Proceso"></textarea>

                            Area

                                <select class="form-control" name="area_id" >
                                    <option selected="" value="">-- Selecciona --</option>
                                      <?php foreach($areas as $p):?>
                                        <option value="<?php echo $p['id']; ?>"><?php echo $p['name']; ?></option>
                                      <?php endforeach; ?>
                                </select>

                            Categoria

                                <select class="form-control" name="category_id" >
                                    <option selected="" value="">-- Selecciona --</option>
                                      <?php foreach($categories as $p):?>
                                        <option value="<?php echo $p['id']; ?>"><?php echo $p['name']; ?></option>
                                      <?php endforeach; ?>
                                </select>

                            Prioridad

                                <select class="form-control" name="priority_id" >
                                    <option selected="" value="">-- Selecciona --</option>
                                  <?php foreach($priorities as $p):?>
                                    <option value="<?php echo $p['id']; ?>"><?php echo $p['name']; ?></option>
                                  <?php endforeach; ?>
                                </select>

                            Turno*

                                <select class="form-control" name="turn_id" >
                                    <option selected="" value="">-- Selecciona --</option>
                                  <?php foreach($turns as $p):?>
                                    <option value="<?php echo $p['id']; ?>"><?php echo $p['name']; ?></option>
                                  <?php endforeach; ?>
                                </select>

                            Estado

                                <select class="form-control" name="status_id" >
                                    <option selected="" value="">-- Selecciona --</option>
                                  <?php foreach($statuses as $p):?>
                                    <option value="<?php echo $p['id']; ?>"><?php echo $p['name']; ?></option>
                                  <?php endforeach; ?>
                                </select>

                              <button id="save_data" type="submit" class="btn btn-success">Guardar</button>

                    </form>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>

A: Para enviar un correo automático puedes hacer uso de la función "mail()" de php
Puedes consultar la documentación de la función aquí:
https://www.w3schools.com/php/func_mail_mail.asp
Para hacer uso de la función te dejo un código de muestra que puedes utilizar para enviar correos desde PHP, lo único que tendrías que definir es si enviar los datos capturados a otro PHP donde puedas procesarlos, es decir, a donde envias el formulario para guardarlo ahi podrías usar el siguiente código.
$to = "mimail@mimail.com";

$subject = "Este es el ASUNTO del correo.";

$htmlContent = ''; //Aquí puedes crear el template que se usará para enviar el correo concatenando las variables de los datos. Recomiendo usar TABLE para esquematizar más fácil el contenido.

            // Aquí estableces los headers del correo, por lo general estos son iguales siempre para cualquier correo.
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

            // Este header es importante, ya que es el 'nombre' que se muestra al lado del correo cuando llega.
            $headers .= 'From: NOMBRE DEL SISTEMA<hello@sistema.com>' . "\r\n";

            // Enviar el correo, agregando las variables anteriormente definidas.
            if(mail($to,$subject,$htmlContent,$headers)):
                $successMsg = 'Email has sent successfully.';
            else:
                $errorMsg = 'Email sending fail.';
            endif;

Espero te sirva al menos para darte una idea, quedo pendiente :)


text:
Q: What does "safely escaped with Go syntax" mean? Go's fmt package defines %q (for strings) as:

 %q      a double-quoted string safely escaped with Go syntax

What does safely escaped with Go syntax mean?
Some experimentation shows it preserves escape sequences used in the original string:
s := "This has \"quotes\" in it"
fmt.Printf("%q\n", s)             // output: "This has \"quotes\" in it"

Is there anything else it does? In what situations might you want to use this? I'm guessing perhaps in templates that generate Go code?

A: It means that the formatted output would be escaped properly that it can be copied and used in the go source code
Example formattings
 "abc"          => `"abc"`
 []byte("abc")  => `"abc"`
 ""             => `""`
 "\""           => `"\""`
 `\n`           => `"\\n"`
 renamedBytes([]byte("hello")) => `"hello"`
 []renamedUint8{'h', 'e', 'l', 'l', 'o'} => `"hello"`
 reflect.ValueOf("hello") => `"hello"`

Code explaining the above
package main

import (
    "fmt"
    "reflect"
)

func main() {
    type renamedBytes []byte
    type renamedUint8 uint8

    fmt.Printf("%q\n", "abc")
    fmt.Printf("%q\n", []byte("abc"))
    fmt.Printf("%q\n", "\n")
    fmt.Printf("%q\n", []renamedUint8{'h', 'e', 'l', 'l', 'o'})
    fmt.Printf("%q\n", renamedBytes([]byte("hello")))
    fmt.Printf("%q\n", reflect.ValueOf("hello"))
}

A: it transforms a strange / malformed input into something that is safe to use
it would change the string representation of this byte array
[]byte{56 ,21 ,114 ,215 ,252 ,199 ,62 ,146 ,143 ,167 ,197 ,162 ,172 ,158 ,112 ,4 ,76 ,17 ,222 ,32 ,34 ,215 ,199 ,97 ,187 ,143 ,61 ,161 ,211, 96 ,198 ,218 ,134 ,106 ,85 ,107 ,162 ,194 ,36 ,153, 255}  from "o<�i���H���O��Ia)eb�?G(V���H" into "\x9d\xd8ջ\x90\xf13\x89\xd6\xd0\v2\xc0\xbe.m\xaa!B\xbf\xbe\xe7s\x0e\xff\xac\xf4Ӕ\xe6Dx\x88\xd3c\xa2P\x16n\x97\xc8"
but "hello world" would remain "hello world"
if the byte array is printer straight into your terminal it might make your terminal look weird, for example my terminal returned this " "D␊␌⎼≤⎻├␊␍ ⎽├⎼␋┼± "H␊┌┌⎺, ┬⎺⎼┌␍!", when i used string() instead of "%q"


text:
Q: Cheapest way of doing max() on absolute values, but have max() preserve sign? I have a 3-vector, let's say
v = vec3(-4, 2, 3)

I would like to do a max on the absolute values of the components, so the equivalent of:
max(abs(v[0]), max(abs(v[1]), abs(v[2]))) == 4

However, I have a requirement that I need to preserve the sign.  So for example:
magic_max(v[0], magic_max(v[1], v[2])) == -4.

It's a trivial problem if I use conditional branching, but I'm trying to do this in as few operations as possible, and avoid branching.  Any ideas on where to look?  Maybe there's some bit-shifting magic that can be done?

A: I would determ the max AND the min of all values, and then decide what is abs larger
ma = max(v[0], max(v[1], v[2]));
mi = min(v[0], min(v[1], v[2]));

res = abs(mi) > ma ? mi : ma;

If you want to get the sign, replace the last line with an if
if (abs(mi) > ma) {
  sign = -1;
  res = mi;
} else {
  sign = +1;
  res = ma;
}

However, what should happen on (0, 0, 0)? no sign?


text:
Q: Threads in Java | wait(), notify() and notifyAll() I have an interface as below(assume it's a Java Interface and methods with void return types)
interface FileAccessOperations{
    fun requestReadAccess()
    fun releaseReadAccess()
    fun requestWriteAccess()
    fun releaseWriteAccess()
}

Now I have to implement these methods where I need to manage single file's read/write permission between large number of threads.
I have implemented as below.
public class FileOperationsImpl implements FileAccessOperations {

    /* When count is
     * (equals 0) -> File is free, no thread is accessing it (Write and read request is possible)
     * (greater than 0) -> File is being read by #count of threads.(Reads are still possible. No write)
     * (lesser than 0) -> File is in write mode.(Write/Read is not possible)
     *
     * So basically, the file can read by multiple threads at a time.
     * But only one thread can write at a given time.
     */
    private int count = 0;

    @Override
    synchronized public void requestReadAccess() {
        while(count < 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count++;
    }

    @Override
    synchronized public void releaseReadAccess() {
        if(count > 0){
            count--;
        }
        if(count == 0){
            notifyAll();
        }
    }

    @Override
    synchronized public void requestWriteAccess() {
        while(count != 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
    }

    @Override
    synchronized public void releaseWriteAccess() {
        count = 0;
        notifyAll();
    }
}

Did I do it right?

A: I see several issues with your implementation:

*

*releaseReadAccess does not check if any read access is actually held, and thus can acquire write access (make count go negative).

*releaseWriteAccess has a similar problem, it can increase count beyond 0, creating false read lock.

*If requestWriteAccess is called while any lock exists, it will block until lock is released, but then do nothing.
Since this function does not return any value, the calling thread will never know it didn't actually get the lock.

*Similar issue with requestReadAccess - it will wait until it can grant the lock, but won't increment count, so no lock will be granted.
Generally speaking, it is a better design practice to have request functions return true or false to indicate weather lock was successfully obtained, even if they block, just in case there are some error conditions.


text:
Q: Can Hive recursively descend into subdirectories without partitions or editing hive-site.xml? I have some web server logs that I'd like to query with Hive. The directory structure, in HDFS, looks like this:
/data/access/web1/2014/09
/data/access/web1/2014/09/access-20140901.log
[... etc ...]
/data/access/web1/2014/10
/data/access/web1/2014/10/access-20141001.log
[... etc ...]
/data/access/web2/2014/09
/data/access/web2/2014/09/access-20140901.log
[... etc ...]
/data/access/web2/2014/10
/data/access/web2/2014/10/access-20141001.log
[... etc ...]

I'm able to create an external table:
CREATE EXTERNAL TABLE access(
  host STRING,
  identity STRING,
  user STRING,
  time STRING,
  request STRING,
  status STRING,
  size STRING,
  referer STRING,
  agent STRING)
ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.RegexSerDe'
WITH SERDEPROPERTIES (
  "input.regex" = "([^ ]*) ([^ ]*) ([^ ]*) (-|\\[[^\\]]*\\]) ([^ \"]*|\"[^\"]*\") (-|[0-9]*) (-|[0-9]*)(?: ([^ \"]*|\"[^\"]*\") ([^ \"]*|\"[^\"]*\"))?",
  "output.format.string" = "%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s")
LOCATION '/data/access/'

... though Hive doesn't descend into the subfolders unless I run the following commands before running the Hive query:
set hive.input.dir.recursive=true;
set hive.mapred.supports.subdirectories=true;
set hive.supports.subdirectories=true;
set mapred.input.dir.recursive=true;

I've seen other posts set these properties at the table-level (e.g. Issue creating Hive External table using tblproperties):
TBLPROPERTIES ("hive.input.dir.recursive" = "TRUE",
    "hive.mapred.supports.subdirectories" = "TRUE",
    "hive.supports.subdirectories" = "TRUE",
    "mapred.input.dir.recursive" = "TRUE");

Unfortunately, this didn't work for me: the table doesn't return any records when I query it. I understand it's possible to set these properties in hive-site.xml, but I'd rather not make any changes that might impact other users if I don't need to.
Q) is there a way to create a table that descends into the subdirectories without using partitions, making site-wide changes, or running those 4 commands every time?

A: These are not tables properties.
TBLPROPERTIES ("hive.input.dir.recursive" = "TRUE",
    "hive.mapred.supports.subdirectories" = "TRUE",
    "hive.supports.subdirectories" = "TRUE",
    "mapred.input.dir.recursive" = "TRUE");

A) add
  <property>
    <name>mapred.input.dir.recursive</name>
    <value>true</value>
  </property>

  <property>
    <name>hive.mapred.supports.subdirectories</name>
    <value>true</value>
  </property>

in hive-site.xml

A: Using Hive in HDInsight, I set the following properties before I create my external table in the Hive query and it works for me.
SET hive.mapred.supports.subdirectories=TRUE;
SET mapred.input.dir.recursive=TRUE;

A: If you are using ambari the set the following properties to hive advanced config inside custom hive-site.xml.
**- SET hive.input.dir.recursive=TRUE
SET hive.mapred.supports.subdirectories=TRUE
SET hive.supports.subdirectories=TRUE
SET mapred.input.dir.recursive=TRUE**
And then restart the affected services. This will read all the data recursively.

A: settings from ozw1z5rd's post worked on Hortonworks
alter table .... set tblproperties (
    "hive.input.dir.recursive" = "TRUE",
    "hive.mapred.supports.subdirectories" = "TRUE",
    "hive.supports.subdirectories" = "TRUE",
    "mapred.input.dir.recursive" = "TRUE");


text:
Q: What does a backslash hyphen (\-) do? What does \- do in the middle of a word? The context in which I saw it was
\textsc{Some\-Word}

I tried searching for this syntax with google but it's very difficult to get a search engine to do anything with such oddball characters.


text:
Q: Create JavaScript array of function pointer, without calling it I have the code below. I would like to have an array (buttons) with a single element pointing to the a function (closeFlag).
<script type="text/javascript">
    var closeFlag = new function() {
        alert('Clicked');
    }
    var buttons = {
        'OK': closeFlag
    }
</script>

However, when loading the page the alert immediately pops up. When the array is constructed, instead of using it as a pointer, JavaScript calls my function.
Why? What mistake, misconception do I have?

A: The new keyword, you will not need it.
<script type="text/javascript">
  var closeFlag = function() {
    alert('Clicked');
  }
  var buttons = {
    'OK': closeFlag
  }
</script>

What's happening in your code is that it's constructing the anonymous function then assigning the result of it (this) to closeFlag.


text:
Q: The excel file was converted to a Numbers file by AppleScript First, I ran the script code in the script editor, and found that there was an error. The Numbers did not understand the save command, The script command was as follows:
tell application "Numbers"
    set thisDocument to open alias "Macintosh HD:Users:admin:numbers-FATP.xls"
    tell thisDocument
        save thisDocument in file "Macintosh HD:Users:admin:NumbersTest.numbers"
    end tell
    close thisDocument
end tell

And the specific error information was as follows:
error ""Numbers" encountered an error:"remove id \"C76B3CB0-D007-46C4-BEB0-9C65D0E65767\"" do not understand "save" information." number -1708 from remove id "C76B3CB0-D007-46C4-BEB0-9C65D0E65767"

The point is, sometimes can execute the script code, sometimes can't perform, and it is puzzling, I try to change the computer version and version Numbers, but did not solve the problem, this is why, look forward to your reply, best regards!
I refer to this website: https://iworkautomation.com/numbers/document-save.html


text:
Q: Python - how can i read numbers in a file as integers but with headings? I have a file that has a bunch of numbers, but there are headings that are keeping me from doing much. The file looks like this:
x:
1 2 3 4

f:
5 6 7 8

h:
9 10 11 12 13

so I have this program which i believe will help me access the numbers but I get an error message about it.
filename = input('file: ')
f = open(filename, 'r')
output=[]
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
    if i == h:
        break
    x.append(map(int,line.split()[:w]))
output.append(x)

So i tried striping the headers, but I get an error message about it being a string and such.
filename = input('file: ')
f = open(filename, 'r')
output=[]
func = f.readline()
lines = func.strip('x').strip('f').strip('h').split()
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
    if i == h:
         break
    x.append(map(int,line.split()[:w]))
output.append(x)

any advice?

A: If the heading are distinct, parse as follows?
x -> [1,2,3,4]
f -> [5,6,7,8]
h -> [9,10,11,12,13]

Is this what you are after?

A: Just read file normally and strip all characters? Quick code, haven't tested but you should be able to easily adapt.
import re

 with open (filename, "r") as myfile:
    for line in myfile.readlines():
       data =re.sub(r"\D", "", line)

A: parsefile.py:
import re

with open('file.txt', 'rU') as data:
    mydict = {}
    for line in data:
        varname = re.search('(\w+):', line)
        if varname:
            mydict[varname.group(1)] = [int(num) for num in data.next().split()]
    print 'x = ', mydict['x']
    print 'f = ', mydict['f']
    print 'h = ', mydict['h']

file.txt:
x:
1 2 3 4

f:
5 6 7 8

h:
9 10 11 12 13

output:
(parsedigitsheaders)macbook:parsedigitsheaders joeyoung$ python parsefile.py
x =  [1, 2, 3, 4]
f =  [5, 6, 7, 8]
h =  [9, 10, 11, 12, 13]


text:
Q: Breaking up the SDL code I am doing first examples from the "SDL Game Development Black and White" book.
The point where I have problems is in example where I should break "HelloSDL" code in one header( .h) and two cpp( .cpp) files.
Here they are:
main.cpp
#include "Game.h"
#include <stdio.h>
#include <SDL2/SDL.h>

Game* g_game = 0;

int main(int argc, char* args[])
{

    g_game = new Game();

    g_game->init("Chapter 1", 100, 100, 640, 480, 0);

    while(g_game->running())
    {
        g_game->handleEvents();
        g_game->update();
        g_game->render();
    }
    g_game->clean();

    void Game::handleEvents()
    {
        SDL_Event event;
        if(SDL_PollEvent(&event))
        {
           switch (event.type)
           {
               case SDL_QUIT:
                   m_bRunning = false;
               break;

              default;
              break;
           }
       }
    }
    return 0;
}

Game.h
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#include <SDL2/SDL.h>

class Game
{
public:

    Game();
    ~Game();

    void init();

    void render();
    void update();
    void handleEvents();
    void clean();

    bool running() { return m_bRunning; }

private:

    SDL_Window* m_pWindow;
    SDL_Renderer* m_pRenderer;

    bool m_bRunning;
};

#endif // GAME_H_INCLUDED

Game.cpp
#include <iostream>
#include "Game.h"
//#include <stdio.h>
#include <SDL2/SDL.h>

bool Game::init(const char* title, int xpos, int ypos, int width, int height, int flags)
{
    if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        std::cout << "SDL init success\n";
        m_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);

        if(m_pWindow != 0)
        {
            std::cout << "window creation success\n";
            m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);

            if(m_pRenderer != 0)
            {
                std::cout << "renderer creation success\n";
                SDL_SetRenderDrawColor(m_pRenderer, 255 255, 255, 255);
            }
            else
            {
                std::cout << "renderer init fail\n";
                return false;
            }
        }
        else
        {
            std::cout << "window init fail\n";
            return false;
        }
    }
        else
        {
            std::cout << "SDL init fail\n";
            return false;
        }

        std::cout << "init success\n";
        m_bRunning = true;

        return true;
}

void Game::render()
{
    SDL_RenderClear(m_pRenderer);

    SDL_RenderPresent(m_pRenderer);
}

SDL_Quit()
    +{
        std::cout << "cleaning game\n";
        SDL_DestroyWindow(m_pWindow);
        SDL_DestroyRenderer(m_pRenderer);
        SDL_Quit();
    }

void Game::clean()
{
    std::cout << "cleaning game\n";
    SDL_DestroyWindow(m_pWindow);
    SDL_DestroyRenderer(m_pRenderer);
    SDL_Quit();
}

After compiling it in CodeBlocks(16.11) I get next error messages:
Game.cpp|6|error: prototype for 'bool Game::init(const char*, int, int, int, int, int)' does not match any in class 'Game'

Game.h|12|error: candidate is: void Game::init()

Firstly, I got much more errors but I managed to solve it.
There is still two more errors to solve.
I suppose that is something wromg in Game.h file, but I cannot find it.
Thank you in advance!

A: It seems that you may be coming from C background. In C++ omitting function signature at function declaration is not permitted. Basically by declaring void init(); you declare void Game::init(void) function, not bool Game::init(const char* title, int xpos, int ypos, int width, int height, int flags). So one must carefully check that function declaration does exactly match function definition. Another thing is that in C++ one should perform object initialization at constructor and cleanup at destructor.

A: The init() declared in the game.h returns void, but the definition you provide returns bool.


text:
Q: Mega Menu TYPO3 Fluid Typoscript TYPO3 9.5.3 Fluid Bootstrap Package
How to make a mega menu in TypoScript with the placeholder I provide for example toplevel1 is the first then a dropdown toplevel2 and then a dropdown top-level 3? If you need the css I will upload it also and the JavaScript.
Thank you for you help. OR should I build the menu only with TypoScript?
Thank you

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="content-language" content="de-DE">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>HTL Villach</title>
        <link rel="icon" type="image/png" href="images/logo_schwarz.png">
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
        <link rel="stylesheet" href="css/style.css">
        <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.css" />

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" >

                </button>

                         {menuPrimary f:format.raw()}

                                                    {toplevel2 f:format.raw()}

                                                    {toplevel3 f:format.raw()}

                                {toplevel1 f:format.raw()}

{toplevel2 f:format.raw()}

{toplevel3 f:format.raw()}

                                {toplevel1 f:format.raw()}

                                                    {toplevel2 f:format.raw()}

                                                    {toplevel3 f:format.raw()}

                                {toplevel1 f:format.raw()}

{toplevel2 f:format.raw()}

{toplevel3 f:format.raw()}

                                {toplevel1 f:format.raw()}

                                                    {toplevel2 f:format.raw()}

                                                    {toplevel3 f:format.raw()}

                                 {toplevel1 f:format.raw()}

{toplevel2 f:format.raw()}

{toplevel3 f:format.raw()}

                    <form class="form-inline my-2 my-lg-0">
                        <input class="form-control" type="search" placeholder="Suche" aria-label="Search">

                    </form>

            ©
            Höhere technische Bundeslehr- und Versuchsanstalt Villach, Tschinowitscher Weg 5, 9500 Villach
            |

            Tel: +43 4242 37061-0

            |

            Kontakt

            |

            Impressum

A: @Björn: Especially for megamenus, use of TS will offer you many possibilities of individual, partial caching. So it's a choice between performance and maintainability.


text:
Q: Where is the mistake in this replacing function in Haskell? I want to write a function which takes a string and replaces any number in the string with 7. For example "foo123" will be replaced to "foo777"
This is my function.
replace [] = []
replace (x:xs) =
    if x == ['0'..'9']
    then '7' : replace xs
    else x : replace xs

A: == does not test if x is an element of the list; it checks if x is equal to the list. Use the elem function instead.
replace [] = []
replace (x:xs) =
    if x `elem` ['0'..'9']
    then '7' : replace xs
    else x : replace xs

if is a pure expression that can be used anywhere another expression can be used, so you don't need to repeat the recursive call to xs:
replace [] = []
replace (x:xs) = (if x `elem` ['0'..'9'] then '7' else x) : replace xs

Finally, you can just use map instead of using explicit recursion.
replace xs = map (\x -> if x `elem` ['0'..'9'] then '7' else x) xs

or just
replace = map (\x -> if x `elem` ['0'..'9'] then '7' else x)

You may want to use Data.Char.isDigit instead:
import Data.Char
replace = map (\x -> if isDigit x then '7' else x)

A: ==  only tests if x is equal to the list, which it is not. You have to use the function elem which takes as its parameter one element and a list of element, and returns true if the element is in the list. So your code will be:
replace [] = []
replace (x:xs) =
    if elem x ['0'..'9']
    then '7' : replace xs
    else x : replace xs


text:
Q: Not able to identify elements of the DOM on the map (mapbox api) using chrome developer tools I have created a web interface which renders a map using mapbox api. The map renders fine. It contains few elements, on click of which a pop up appears. When I try to inspect the elements using chrome developer tool, I am not able to see this in the DOM except for a canvas tag! The link is https://plnkr.co/edit/wpIYHXATxhCMVIYeSqlD?p=preview
<canvas class="mapboxgl-canvas" tabindex="0" width="2880" height="742" style="position: absolute; width: 1440px; height: 371px;"></canvas>

If anybody knows anything about it, please help me.
Thanks

A: Popups will be wrapped inside a div element with class mapboxgl-popup, They can be styled as per your wish and you can also add some html elements into it and also test it.


text:
Q: Using OpenLayers, how can I display different icons for different features on a single layer? firstly I'm new to Openlayers/JS as a whole and fairly inexperienced with programming in general so there might be other problems with my code that I'm not aware of.
I am using the latest version of Openlayers (5.3.0).
My program currently passes GeoJson formatted data via Ajax to be displayed on an Openlayers map. It creates the map, view and a layer for the features to be displayed on. When I press a "Go" button on the page, the features are loaded onto the map successfully. In my case the features are just simple points with latitude/longitude using a png marker to visualise. The GeoJson looks like this in C# before being serialised and sent to JS on my page for deserialisation:
{{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -1.549077,
          53.800755
        ]
      },
      "properties": {
        "GPSKey": 1,
        "Latitude": 53.800755,
        "Longitude": -1.549077,
        "TimeAdded": "2019-01-15T12:10:16",
        "IconPath": "pinred.png"
      },
      "ID": 1,
      "IconPath": null
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -1.545077,
          53.800755
        ]
      },
      "properties": {
        "GPSKey": 2,
        "Latitude": 53.800755,
        "Longitude": -1.545077,
        "TimeAdded": "2019-01-15T12:10:16",
        "IconPath": "pinred.png"
      },
      "ID": 2,
      "IconPath": null
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -1.524043,
          53.773222
        ]
      },
      "properties": {
        "GPSKey": 3,
        "Latitude": 53.773222,
        "Longitude": -1.524043,
        "TimeAdded": "2019-01-15T12:10:16",
        "IconPath": ""
      },
      "ID": 3,
      "IconPath": null
    }
  ]
}}

The JS receives the above serialised and uses this code to add it to the layer for viewing:
var geojsonFormat = new ol.format.GeoJSON({
        dataProjection: "EPSG:4326",
        featureProjection: "EPSG:3857"
    });//creates a format definition

    jsonDecoded = JSON.parse(result); /

    if (jsonDecoded.features.length > 0) {
        for (var i = 0; i < jsonDecoded.features.length; i++) {
            vectorSource.addFeature(geojsonFormat.readFeature(jsonDecoded.features[i], { featureProjection: "EPSG:3857" }));

        }

    }/

The vector layer it gets added to looks like this:
var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: iconStyleFunc()
});

And the iconStyleFunc() looks like this:
function iconStyleFunc() {

    var zIndex = 1;

    var iconName = null;

    if (iconName == null) {
        iconName = "pinother.png"
    };

    iconStyle = [new ol.style.Style({
        image: new ol.style.Icon(({
            anchor: [0.5, 36],
            anchorXUnits: "fraction",
            anchorYUnits: "pixels",
            opacity: 1,
            src: "images/" + iconName,
            zIndex: zIndex
        })),
        zIndex: zIndex
    })];
return iconStyle;

This works fine for styling all the features with the icon "pinother.png". I have no problem displaying the points on the map when I press the button.
What I'd like to do is apply styling based on the icon path in the properties of each feature's GeoJson "iconpath", so that any feature having a "pinred.png" would use that instead of the default "pinother.png", and so on with various icons I might need to add in the future.
I'm not sure how to read this property of each feature and how I would best implement it in the styling function. The way I envisaged it was iterating through features using the iconStyleFunc(), reading the IconPath property for each feature, appending that value to the "src/images/" path in the iconStyleFunc() and styling the feature appropriately.

A: Using the feature argument of the style function you can get properties of the feature
function iconStyleFunc(feature) {

    var zIndex = 1;

    var iconName = feature.get("IconPath") || "pinother.png";

    iconStyle = [new ol.style.Style({
        image: new ol.style.Icon(({
            anchor: [0.5, 36],
            anchorXUnits: "fraction",
            anchorYUnits: "pixels",
            opacity: 1,
            src: "images/" + iconName,
            zIndex: zIndex
        })),
        zIndex: zIndex
    })];
return iconStyle;


text:
Q: Color coded calendar 2007 versus 2013 I have a calendar color coded in SP 2007. Its working good. I used the same code in SP 2013, but it doesn't work there. Any Suggestions?
<script language="javascript" type="text/javascript">
 var SEPARATOR = "|||";
 var nodes, Group;
 nodes = document.getElementsByTagName("a");
 function getObjInnerText (obj)
 {
   return (obj.innerText) ? obj.innerText : (obj.textContent) ? obj.textContent : "";
 }
 for(var i = 0; i < nodes.length; i++)
 {
   if(getObjInnerText(nodes[i]).indexOf(SEPARATOR) != -1)
   {
     UpdatecalendarEntryText(nodes[i]);
     var foundNode = nodes[i];
     var trap = 0;
     while(foundNode.nodeName.toLowerCase() != "td")
     {
       foundNode = foundNode.parentNode;
       trap++;
       if(trap > 10)
       {
         break; // don't want to end up in a loop
       }
     }
     var colourinfo = GetcalendarColourInfo(Group);
     if(colourinfo.bg != "")
     {
       foundNode.style.background = colourinfo.bg;
     }
     // try and update the text colour if we can TD/A/NOBR/B/#text
     if(colourinfo.fg != "")
     {
       try
       {
         // there should only be one anchor tag
         childNodes = foundNode.all;
         for(var j = 0; j < childNodes.length; j++)
         {
           if(childNodes[j].nodeName.toLowerCase() == "a")
           {
             // found anchor tag
             childNodes[j].style.color = colourinfo.fg;
             // set the NOBR tag as well to set the time if it is shown, but set it on the B tag for month view
             if(childNodes[j].children[0].nodeName.toLowerCase() == "nobr")
             {  // month view has an extra b tag surrounding the text
               childNodes[j].children[0].style.color = colourinfo.fg;
               if(childNodes[j].children[0].children[0].nodeName.toLowerCase() == "b")
               {
                 childNodes[j].children[0].children[0].style.color = colourinfo.fg;
               }
             }
             break;
           }
         }
       }
       catch(e) {}
     }
   }
 }
 function ColourInfo(bg, fg)
 {
   this.bg = bg;
   this.fg = fg;
 }
 function UpdateCalendarEntryText(anchorNode)
 {
   var children = anchorNode.childNodes;
   for(var i = 0; i < children.length; i++)
   {
     if(children[i].nodeType == 3 && children[i].nodeValue.indexOf(SEPARATOR) != -1)
     {
       var parts = children[i].nodeValue.split(SEPARATOR);
       category = parts[0];
       children[i].nodeValue = parts[1];
     }
     else
       UpdateCalendarEntryText(children[i]);
   }
 }
 function GetCalendarColourInfo(desc)
 {
   var colour = new ColourInfo("", "");
   var trimmed = desc.replace(/^\s+|\s+$/g, '') ;
   switch(trimmed.toLowerCase())
   {
     case "Business Visit":
           colour.bg = "#f0e109";
           colour.fg = "";
           break;
     case "Flex":
           colour.bg = "#19f009";
           colour.fg = "";
           break;
     case "Out Of Office":
           colour.bg = "#25add6";
           colour.fg = "";
           break;
     case "Holiday":
           colour.bg = "#d67d25";
           colour.fg = "";
           break;
     case "Other":
           colour.bg = "#8467d7";
           colour.fg = "";
           break;
     default:
     {
       colour.bg = "";
       colour.fg = "";
     }
   }
   return colour;
 }
 </script>

A: I have used this site's documentation to color code 2013 calendars: http://www.planetwilson.co.uk/sharepoint-2013-colour-calendar-v2/
It is a simple solution that utilizes some of the same coding concepts as your solution.
I even exported a color calendar template for others to use that cuts out most of the technical work.

A: I recommend using calendar overlays for colors, and then you can use some CSS to change those colors to what you want. Write up on http://davidlozzi.com/color-code-sharepoint-calendar/
For the CSS a sample looks like:
.ms-acal-color# {
 BACKGROUND-COLOR: #xxxxxx
}
.ms-acal-selcolor# {
 BACKGROUND-COLOR: #xxxxxx
}
.ms-acal-apanel-color# {
 BORDER-COLOR: #xxxxxx;
 BACKGROUND-COLOR: #xxxxxx;
}

Where # is the number of the color you're replacing.