text:
Q: XAML code to put button in bottom right corner I'm trying to get my floating action button in the bottom left corner of my application.
Currently it looks like this:

And I want it to look like this:

My XAML code:
<?xml version="1.0" encoding="utf-8" ?>
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:xxx;assembly=xxx"
         x:Class="xxx.xxx.xxx.xxxx">

 <AbsoluteLayout HorizontalOptions="FillAndExpand"  VerticalOptions="FillAndExpand">

    <StackLayout AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">

        <StackLayout Orientation="Vertical" VerticalOptions="StartAndExpand">
            <StackLayout HorizontalOptions="CenterAndExpand"  Margin="0,15,0,0" Orientation="Vertical">
                <!--<local:CustomImage Source="logo.png" HeightRequest="100" WidthRequest="100" HorizontalOptions="Center" />-->

                <local:CustomImageButton  WidthRequest="150" Image="Foto.png" ClassId="Eigendommen" x:Name="buttonFoto" HeightRequest="150"/>

            </StackLayout>

            <StackLayout Orientation="Vertical" VerticalOptions="CenterAndExpand" Margin="10,0,0,0" x:Name="MainStack" >
                <BoxView BackgroundColor="#F15A35" HeightRequest="1" WidthRequest="400" Margin="0,-2,0,5" />
                <Label Text="Toegevoegd:" FontSize="Medium" FontAttributes="Bold" />
                <StackLayout Orientation="Horizontal">
                    <StackLayout Orientation="Vertical"  IsVisible="False" Margin="10,0,10,0" x:Name="hideImage1">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="Verwijderen" FontSize="Small" VerticalTextAlignment="Center" />
                            <local:CustomImageButton Image="close_zwart.png" BackgroundColor="White" Clicked="Hide_Image_Click" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                    <StackLayout Orientation="Vertical" Margin="10,0,10,0" x:Name="hideImage2" IsVisible="False">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="Verwijderen" FontSize="Small" VerticalTextAlignment="Center" />
                            <local:CustomImageButton Image="close_zwart.png" Clicked="Hide_Image_Click" BackgroundColor="White" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                    <StackLayout Orientation="Vertical" Margin="10,0,10,0" x:Name="hideImage3" IsVisible="False">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="Verwijderen" FontSize="Small" VerticalTextAlignment="Center" />
                            <local:CustomImageButton Image="close_zwart.png" Clicked="Hide_Image_Click" BackgroundColor="White" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                </StackLayout>

            </StackLayout>

        </StackLayout>

    </StackLayout>

    <StackLayout
             AbsoluteLayout.LayoutFlags="All"
             AbsoluteLayout.LayoutBounds="1,1,0.25,0.25">

        <StackLayout HorizontalOptions="End" VerticalOptions="End" Margin="0,0,0,0">
            <local:FloatingActionButton Image="checktaak.png" x:Name="insertTaak"  HeightRequest="60" WidthRequest="60" />
        </StackLayout>

    </StackLayout>

</AbsoluteLayout>

</ContentPage>

You can find the my floating action button at the bottom of all the code ( the last stacklayout). if you need more code let me know in the comments.
Edit I want the button always there even if it overlaps a other stacklayout

A: Assuming FloatingActionButton inherits from Button and the AbsoluteLayout is the child of a ContentPage and the expected margin for the floating button as (15,15) from right and bottom borders,
<AbsoluteLayout>
    <!-- SOME OTHER ELEMENTS -->

    <local:FloatingActionButton Image="checktaak.png"
                                CornerRadius="30"
                                WidthRequest="60" HeightRequest="60"
                                AbsoluteLayout.LayoutFlags="PositionProportional" AbsoluteLayout.LayoutBounds="1,1,75,75"
                                HorizontalOptions="Center" VerticalOptions="Center" />
</AbsoluteLayout>

To NOTE,

*

*Use AbsoluteLayout.LayoutFlags="PositionProportional" to make
only the positioning proportional
Then for AbsoluteLayout.LayoutBounds set X and Y, 1 and 1 to
push it to the bottom right corner. The Width and Height is set
to 75 and 75 to position the element 75 points left from the layout's
right border and 75 points top from the layout's bottom border.

The 75 is calculated as,
60(element width/height request) + 15(right/bottom margin) = 75

*Since the WidthRequest and HeightRequest is 60, half of it 30
will be the CornerRadius of the element.

A: Found it!
Just had to tweak the layoutbounds a little, I didn't knew I could go over 1.
This is my new layoutbound for the stacklayout that includes the fab:
 AbsoluteLayout.LayoutBounds="0.94,1.18,0.5,0.25"


text:
Q: Retain few NA's and drop rest of NA's during Stack operation in Python I have a dataframe like shown below
df2 = pd.DataFrame({'person_id':[1],'H1_date' : ['2006-10-30 00:00:00'], 'H1':[2.3],'H2_date' : ['2016-10-30 00:00:00'], 'H2':[12.3],'H3_date' : ['2026-11-30 00:00:00'], 'H3':[22.3],'H4_date' : ['2106-10-30 00:00:00'], 'H4':[42.3],'H5_date' : [np.nan], 'H5':[np.nan],'H6_date' : ['2006-10-30 00:00:00'], 'H6':[2.3],'H7_date' : [np.nan], 'H7':[2.3],'H8_date' : ['2006-10-30 00:00:00'], 'H8':[np.nan]})

As shown in my screenshot above, my source datframe (df2) contains few NA's
When I do df2.stack(), I lose all the NA's from the data.
However I would like to retain NA for H7_date and H8 because they have got their corresponding value / date pair. For H7_date, I have a valid value H7 and for H8, I have got it's corresponding H8_date.
I would like to drop records only when both the values (H5_date,H5) are NA.
Please note I have got only few columns here and my real data has more than 150 columns and column names aren't known in advance.
I expect my output to be like as shown below which doesn't have H5_date,H5 though they are NA's

A: You can use :
col = [x for x in df.columns if "date" in x]
 for column in col:
    df.dropna(subset=[column,column[:-4]], how = 'all',inplace=True)
subset will select the lines where the NA is detected, how specifies the conditions on the line (here all the of the 2 lines must be NA) and inplace modifies the current DataFrame

A: try pd.DataFrame.melt
df = pd.melt(df2, id_vars='person_id', var_name='col', value_name='dates')
df['col2'] = df['col'].str.split("_").str[0]
df['count'] = df.groupby(['col2'])['dates'].transform(pd.Series.count)
df = df[df['count'] != 0]
df.drop(['col2', 'count'], axis=1, inplace=True)
print(df)

    person_id      col                dates
0           1  H1_date  2006-10-30 00:00:00
1           1       H1                  2.3
2           1  H2_date  2016-10-30 00:00:00
3           1       H2                 12.3
4           1  H3_date  2026-11-30 00:00:00
5           1       H3                 22.3
6           1  H4_date  2106-10-30 00:00:00
7           1       H4                 42.3
10          1  H6_date  2006-10-30 00:00:00
11          1       H6                  2.3
12          1  H7_date                  NaN
13          1       H7                  2.3
14          1  H8_date  2006-10-30 00:00:00
15          1       H8                  NaN

A: On approach is to melt the DF, apply a key that identifies columns in the same "group" (in this case H<some digits> but you can amend that as required), then group by person and that key, filter those groups to those containing at least one non-NA value), eg:
Starting with:
df = pd.DataFrame({'person_id':[1],'H1_date' : ['2006-10-30 00:00:00'], 'H1':[2.3],'H2_date' : ['2016-10-30 00:00:00'], 'H2':[12.3],'H3_date' : ['2026-11-30 00:00:00'], 'H3':[22.3],'H4_date' : ['2106-10-30 00:00:00'], 'H4':[42.3],'H5_date' : [np.nan], 'H5':[np.nan],'H6_date' : ['2006-10-30 00:00:00'], 'H6':[2.3],'H7_date' : [np.nan], 'H7':[2.3],'H8_date' : ['2006-10-30 00:00:00'], 'H8':[np.nan]})

Use:
df2 = (
    df.melt(id_vars='person_id')
    .assign(_gid=lambda v: v.variable.str.extract('H(\d+)'))
    .groupby(['person_id', '_gid'])
    .filter(lambda g: bool(g.value.any()))
    .drop('_gid', 1)
)

Which gives you:
    person_id variable                value
0           1  H1_date  2006-10-30 00:00:00
1           1       H1                  2.3
2           1  H2_date  2016-10-30 00:00:00
3           1       H2                 12.3
4           1  H3_date  2026-11-30 00:00:00
5           1       H3                 22.3
6           1  H4_date  2106-10-30 00:00:00
7           1       H4                 42.3
10          1  H6_date  2006-10-30 00:00:00
11          1       H6                  2.3
12          1  H7_date                  NaN
13          1       H7                  2.3
14          1  H8_date  2006-10-30 00:00:00
15          1       H8                  NaN

You can then use that as a starting point to tweak if necessary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invoking an elisp function and make it prompt for input In a function that I am writing myself, I would like to invoke the command compile but have it run interactively, just as if I had done Meta-x compile. Just invoking (compile) doesn't work as it expects arguments. So how do force emacs to run compile "interactively"?

A: The answer is:
(call-interactively 'compile)

This does exactly what I asked for in the question.


text:
Q: XAMPP PDO Sqlite directory The sqlite PHP PDO code below works when i run it through PHP command line from the htdocs directory in XAMPP.  However, when I run it as localhost, it cannot find S2.db.  There are the correct permissions on that directory...
What is the right way to access a different directory with ATTACH DATABASE when run through XAMPP?  Thank you!
$db = new PDO('sqlite:S1.db');
$db->exec("ATTACH DATABASE '../S2.db' as table1");


text:
Q: the accuracy formula of classification using lda what is the formula of accuracy linear discriminant system as classifier?
is the multi class and 2 class have same formula of accuracy?
i tried to find it in google but cant find one, help me please
thanks

A: If you are referring to the loss function, then there are several options, which don't depend on the method used (e.g. LDA), but rather on the objective (in your case classification/prediction). This article compares three loss functions and concludes the Hamming loss works best for multilabel classification.
The Hamming loss, as described here is defined as:
$$\frac{1}{|D|} \sum_{1}^{|D|} \frac{xor (y_i, \hat{y})}{|L|}$$
Where $y_i$ is the actual label, $\hat{y}$ the predicted label, $|D|$ the number of samples and $|L|$ the number of labels.
This is not the same as binary classification, where the loss function is  typically the 0/1 loss:
$$I(y_i \neq \hat{y})$$


text:
Q: Error uploading APK in Google Play Developer Console I recently create my 4th project on Google Play Developer Console. Since yesterday i am trying to upload the first project APK in Alpha but i am getting this error:

You uploaded an APK signed with a certificate that expires too soon.
  You need to sign your APK with a certificate that expires farther into
  the future.

I always generate the keys using keytool and developing, generating the APK and signing using Android Stuido.
I have created my keystore with my first project and everithing works ok for that project. Also no problem with the 2nd and the 3rd.
I already try using -validity 20000 like is described here or here but i got the same error message.
This is command that i am using to create the key:
keytool.exe -genkey -v -keystore "my_key_store" -alias "my_alias_key" -keyalg RSA -keysize 2048 -validity 20000

Thanks for any help.
EDIT:
Maybe the error message is wrong. I list the key information and the expires date is right, is valid until

Fri Jul 03 21:21:22 UYT 2071

A: I just tried the same command, signed the APK in the same way and uploaded using the same browser and it worked fine.
Seems to be a problem in Google Play Developer Console.
Very odd.


text:
Q: Getting the value of autofilled inputs - Jquery So, as some browsers auto-fill sign in forms, it causes an issue with my interactive placeholders. The placeholder is a <span> element with some text in, which moves above the input itself when focussed. Upon the browser inserting the data it has 'remembered', how would I be able to detect its presence, and it's value?
Please note, that it is the auto-completed value of the input which I wish to grab.

A: Using the following code, I have managed to achieve the result I wished for:
setTimeout(function() {
    console.log($('#input').val());
});

Using a timeout allowed the browser to load itself prior to the code requesting data from it.

A: Give the span an ID and run the text() method on it. Without any parameters it works as a getter.
var yourtext = $('#somespan').text();

If it was an actual textfield instead of a span, you would get the contents with the .val() method.
var yourtext = $( "#foo" ).val();


text:
Q: Using Propel in Symfony 1.4 I've gotta return the row by player Id, if there is no row, make one.
This cant be the best way to do it.
class PlayerRafPeer extends BasePlayerRafPeer {

  /**
   * Returns a PlayerRaf object by playerId.
   * @param int $player_id
   * @param PDO $con
   * @return PlayerRaf
   */
  public static function retrieveByPlayerId($player_id, $con = null)
  {
    if ($con === null) {
      $con = Propel::getConnection(self::DATABASE_NAME);
    }

    $criteria = new Criteria();
    $criteria->add(self::PLAYER_ID, $player_id);
    $v = self::doSelectOne($criteria, $con);

    if (!$v) {
        $player = new PlayerRaf();
        $player->setPlayerId($player_id)
             ->setEmailCount(0)
             ->setDate(date("Y-m-d"), time());
        self::doInsert($player, $con);
        return $player;
    }
    return $v;
  }

A: You should avoid to add logic in Peer classes, use the ActiveQuery API instead. You can read: http://www.propelorm.org/reference/model-criteria.html and http://propel.posterous.com/propel-query-by-example.
In your case, this section will help you: http://www.propelorm.org/reference/model-criteria.html#creating_an_object_based_on_a_query.
Then, you could write:
<?php

$player = PlayerRafQuery::create()
            ->filterById($id)
            ->findOneOrCreate();


text:
Q: How to create a Range Chart in Excel I have no idea how to create souch a range chart in Excel 2010:
rangechart http://i.msdn.microsoft.com/dynimg/IC267977.gif
My data looks like this:
1, 12, 22
2, 8, 48
3, 22, 42
...
The first column is the x-Value, the second column the lower y-value and the third the higher y-value. That's the yellow area in the graph.
And then the same for the blue one.
Thank you!
Source of the image: http://msdn.microsoft.com/en-us/library/dd456630.aspx

A: My recommendation would be as follows:
Paste the following into an Excel sheet
20% 20% 20% 20% 20%
10% 10% 10% 10% 10.0%
40% 10% -5% 10% 45.0%
20% 20% 20% 20% 20.0%
10% 40% 55% 40% 5%

Notice that the sum of each column is 100%
Now add a "stacked area" chart (under the area category of charts) based on this data, and colour the first and third and fifth colours to be white (or transparent)
You can then play with the percentages to get your chart. The top row which is 20% corresponds with a rectangle etc.

A: I would arrange my data in a Table as follows:
axis   y_1  h_1 y_2 h_2
1      12    10 30  10
2      8     40 2   4
3      10    12 43  4
4      17    12 18  5
5      30    6  31  5
6      4     7  5   6
7      5     8  6   7
8      2     9  34  8
9      1     4  2   9

Then, you can chart the columns y_1, h_1 in the first axis and y_2, h_2 in the second axis (y_i being the y value and h_i being the height of each strip). Make both chart as Stacked Area chart and change the series y_i transparent.

Finally make the second axis equal to the first one.

A: What worked best for me using MS office 2010 is to use area chart, but not stacked. For multiple data ranges graphs in a single chart, I needed to arrange data legends (column names) from higher to lower, by clicking on the chart and then under "Chart Tools"->"Design" tab click "Select Data". A new window titled "Select Data Source" will pop up. Select data legends in the left pane in the window and move up or down using arrow button on top of the left pane such that graphs will stack from high to low. Now, we need to select graphs corresponding to lower end of the range and fill solid "white" by formatting the graph. What will be left is range chart with shaded area between low and high ends of the data. It seems bit complex, but doing a hand-on tutorial, following the above instructions step-by-step on a chart in excel or power point (after selecting insert chart option), will make it easy.


text:
Q: Elasticsearch(C# nest): Map abstract property I have a class ProductDiscount in C#. Other classes inherit from it (FlatDiscount, PercentageDiscount etc).
Storing data in Elastic seems to work but I can't read data from Elastic.
I get this error:
Could not create an instance of type ProductDiscount. Type is an interface or abstract class and cannot be instantiated.  Path 'discount.amount', line 1, position 1098.
When I look at my index the discount is indeed storef in the collection but there's no indication of the type of the class.
Is it possible to map an abstract property in c# with the nest client?
I've tried with this mapping descriptor but with no succes:
mappingsDescriptor.Map<Product>(x => x
                .Properties(props => props

                    .Object<ProductDiscount>(o => o.Name(prop => prop.Discount))
                    .Object<FlatProductDiscount>(o => o.Name(prop => prop.Discount).AutoMap())
                    .Object<PercentageProductDiscount>(o => o.Name(prop => prop.Discount).AutoMap())
                    .Object<FreeProductProductDiscount>(o => o.Name(prop => prop.Discount).AutoMap())
                    .Object<QuantityProductDiscount>(o => o.Name(prop => prop.Discount).AutoMap())
                 )
            );

Reading is done with the ElasticClient:
    var result = await ElasticClient.SearchAsync<Product>(new SearchRequest(Indices.Index(index: CollectionName)));

A: I found a solution!!
I wrote a custom converter using the JsonSubTypes package.
    private static JsonConverter DiscountConverter()
    {
        var assembly = Assembly.GetAssembly(typeof(ProductDiscount));

        var builder = JsonSubtypesConverterBuilder
            .Of(typeof(ProductDiscount), "Type");

        assembly
            .GetTypes()
            .Where(type => type.IsSubclassOf(typeof(ProductDiscount)) && !type.IsAbstract)
            .ForEach(s =>
            {
                builder.RegisterSubtype(s, s.Name);
            });

        var converter = builder
            .SerializeDiscriminatorProperty()
            .Build();

        return converter;
    }

My connection is set up like this
            var pool = new SingleNodeConnectionPool(new Uri(uris.First()));
            connectionSettings = new ConnectionSettings(pool, connection, SourceSerializer());

    private static ConnectionSettings.SourceSerializerFactory SourceSerializer()
    {
        return (builtin, settings) => new JsonNetSerializer(builtin, settings,
            () => new JsonSerializerSettings
            {
                Converters = new List<JsonConverter>
                {
                    new StringEnumConverter(),
                    DiscountConverter()
                }
            });
    }


text:
Q: Removing Visual Studio 2010's upgrade of SP1 after removing Visual Studio 2010 I was removing my windows 7's updates from the Control Panel but after that when I tried opening Visual Studio 2010, it didn't opened, I wanted to reinstall it so I un-installed visual studio first but after that when I tried to remove it's SP1 update it was not allowing it, re installation is giving a error that a software with the same key exisits

A: Try Revo uninstaller. This software can do a deep analysis of installed software. IT first try to uninstall the product using the official uninstaller, then seek remaining files and registry keys.
Use with cautious, because it can remove more than necessary.


text:
Q: ngFor on keyValue with a mixture of string and number inputs causes focus to be lost when inputting a number I have an object with a few values of empty string and other values defaulted to 0.
Once I use *ngFor with the keyValue pipe and use trackBy to keep the dom from refreshing, I will still lose focus when inputting a new number value, but won't lose focus when inputting text.
Here is the stackblits https://stackblitz.com/edit/angular-ivy-ckzw9g?file=src/app/app.component.html where the issue can be reproduced.

A: I think I've implemented what you want at StackBlitz.

A: So I am answering it because you asked me, after debugging I figured out that will be beneficial for future reference:

*

*For this code:

<input matInput *ngIf="isNumber(conf.value)" placeholder="Number" name="input{{conf.key}}"
    id="input{{conf.key}}" [(ngModel)]="inputs[conf.key]">

On the very first run this code will create the input text box because you are
passing 0 as number and ngIf will be true so it will create an input box.

*When you input any value in the above text box "The inputted value will be a string" by default as no type is mentioned in the textbox, so the above text boxed will be removed and a new text box is created by angular the below one:

 <input matInput *ngIf="isString(conf.value)" placeholder="Text" name="input{{conf.key}}"
    id="input{{conf.key}}" [(ngModel)]="inputs[conf.key]">

This is because when the values of associated object changes, angular runs the change detection to update the view and find out the inputted value is string and creates a new textbox with that value as it is Ngmodeled and object work by reference(it is updating inputs object that is declared in the component) and when you enter the subsequent characters it allows you to keep it focused as long as it satisfy the if condition.
Note: if you add type="number"(that checks isNumber) in the input box, it will allow you to enter as many times you want and it will remained focus.


text:
Q: LinkedList - addLast() not always adding value at end of a list I have to add an element at the end of a list so now I am using addLast() function of LinkedList to add element at the end. It does add element in the list if and only if there is NO more add() statements after it.
Below works fine.
LinkedList<String> ls = new LinkedList<String>();

    ls.add("C");
    ls.add("E");
    ls.add("D");
    ls.add("B");

    ls.addLast("F");
    ls.addFirst("A");

    for( String l : ls )
          System.out.println( l  );

And in the below case, it will not add item at the end of the list.
LinkedList<String> ls = new LinkedList<String>();

    ls.add("C");
    ls.add("E");
    ls.add("D");

    ls.addLast("F");
    ls.add("B");

    ls.addFirst("A");

    for( String l : ls )
          System.out.println( l  );

However, addFirst() works fine regardless of place where you call it.
How I can achieve this? any suggestion please.

A: From java docs:
public boolean add(E e)
Appends the specified element to the end of this list.
This method is equivalent to addLast(E).

Specified by:
add in interface Collection<E>
Specified by:
add in interface Deque<E>
Specified by:
add in interface List<E>
Specified by:
add in interface Queue<E>
Overrides:
add in class AbstractList<E>
Parameters:
e - element to be appended to this list
Returns:
true (as specified by Collection.add(E))

In your case the you add 'B' for the end of the list after you added 'F' to the end of the list

A:
"it will not add item at the end of the list."

Yes it will, it adds the item at the end of the current list. What it won't do is keep it always last. Imagine what would happen if you did addLast() two times, which one would have priority? Same thing with addFirst(), it only works on the current list, and if you add more firsts the other ones won't be first anymore.

A: Specify the position of adding "B" for example ls.add(ls.size() - 1, "B"); Then "F" will be added in last.


text:
Q: Drop Down and File menu in TKinter I'm trying to read file and display it and get user input like in how many minutes he want that file to be displayed.
Currently I'm using .get() to input file path and minutes after which he want that file to be displayed but to make it more user readable I want to implement drop down menu showing minutes and file box (D:/ drive view of particular folder where file resides).
How can I code it using python Tkinter ?
I researched but no luck as of now.
----EDIT----
Snippet of how I'm doing it manually
def add_item():
 print(link_text.get(),small_break.get(),large_break.get(),maxrun_hours.get(),maxrun_minutes.get()
    ,exerun_hours.get(),exerun_minutes.get())

if link_text.get() == '' or small_break.get() == '' or large_break.get() == '' or maxrun_hours.get() == '' or maxrun_minutes.get() == '' or exerun_hours.get() == '' or exerun_minutes.get() == '':
messagebox.showerror('Required Fields', 'Please include all fields')
return

How I take input:
link_text = StringVar()
link_label = Label(app, text='TT-LINK', font=('bold', 14), pady=20, foreground="white",bg="black")
link_label.grid(row=0, column=0, sticky=W)
link_entry = Entry(app, textvariable=link_text, relief="solid")
link_entry.grid(row=0, column=1)

Any suggestions would be much appreciated !

A: TRY:
example = StringVar()
example_label = Label(app, text='example')
example_label.grid(add positional cords)
list = ttk.Combobox(app, textvariable=example)
# Adding combobox drop down list
list['values'] = ('Enter entries manually to populate')
list.grid(add positional cords)
list.current()

Hope that helps...!


text:
Q: How to encode list of 16 numbers in less than 2 bytes I need to convey information of availability of  16 items with their id(0-15) in a variable.
char item_availablity[16];

I can encode it with 2 bytes where every bit is mapped with one item id where 1 represents available and 0 represents unavailable
For ex 0000100010001000
This number has information that Items with id 4,8,12 are available
I need to encode this information by using less than 2 Bytes.
Is this possible? If so, how?

A: To put it simply:
No, you cannot. It's simply impossible to store 1 bit of information about 16 separate things in less than 16 bits. That is, in the general case.
An exception is if there are some restrictions. For instance, let's call the items i_1, i_2 ... i_16. If you know that i_1 is available if and only if i_2 also is available, then you can encode the availability about these two items in just one bit.
A more complicated example is that i_1 is available iff i_2 or i_3 is available. Then you could store the availability for these three items in two bits.
But for the general case, nope, it's completely impossible.

A: Trying to think out of the box here - If some items are more rare than others, you could use a variable length encoding so that, on average, it would take less than 16 bits to store the information. However, there will be combinations of availabilities where it would take more than 16 bits.


text:
Q: Json schema of interface - serialization missing some fields For this code, where I have an user defined interface and schema definition is guided.
type SchemaDefinition<T> = {
  [K in keyof T]: {
    type: { new(): unknown } //
    required?: boolean
  }
}

class Schema<T> {
  constructor(public schema: SchemaDefinition<T>) {}

  validate(obj: T): boolean {
    for (const prop of Object.keys(this.schema) as (keyof T)[]) {
      if (!(obj[prop] instanceof this.schema[prop].type)) return false
      if (this.schema[prop].required && obj[prop] == null) return false
    }

    return true
  }
}

interface IUser {
  name: string;
  email: string;
}

There are two schemas here. 1. for programming language specific container that is IUser interface 2. the one that I want to send it to backend that is composed by Schema object something like
new Schema<IUser>('users',
            {
                name: {type: Number, required: true},
                email: {type: String, required: true},
            });

now I am trying to serialize this Schema object to string using JSON.stringify() but type is skipped, how can I have it serialized or how can I translate this IUser into JSON schema in the best way in TS.
Edit:
I was able to retrieve the type name by doing something like this
const schemaRepresentation = {};
schemaRepresentation['title'] = this._name;
schemaRepresentation['additionalProperties'] = false;
schemaRepresentation['additionalProperties'] = false;

const properties = {};

for (const schemaKey in this.schema) {
  properties[schemaKey.toString()] = this.schema[schemaKey].datatype.name;
}

schemaRepresentation['properties'] = properties

if there is an array field in the interface - how do I get the type of the array?

A: You just need to use values that are serializable to JSON because String and Number are functions, and therefore are not serializable.
For example, maybe you want to test the typeof obj[prop] for particular string.
type AllowedTypeNames = 'string' | 'number' | 'boolean'

type SchemaDefinition<T> = {
  [K in keyof T]: {
    type: AllowedTypeNames
    required?: boolean
  }
}

And validate would now look like:
  validate(obj: T): boolean {
    for (const prop of Object.keys(this.schema) as (keyof T)[]) {
      if (typeof obj[prop] !== this.schema[prop].type) return false
      // ^ check if the typeof the obj[prop] matches the schema.

      if (this.schema[prop].required && obj[prop] == null) return false
      // ^ check if the typeof the obj[prop] is required and present.
    }

    return true
  }

Which serializes fine:
const userSchema = new Schema<IUser>({
  name: { type: 'string', required: true },
  email: { type: 'string', required: true },
});

console.log(JSON.stringify(userSchema.schema))
// {"name":{"type":"string","required":true},"email":{"type":"string","required":true}}

See playground


text:
Q: Positioning img with different size/ratio and filling it in in div I have a website that users upload images to, the image processing is made on the server and the size is 400px*400px. The images may come in vary of original sizes on which there is no control. when displaying them I cannot position them correctly in a 200px*200px div. its either squeezed/stretched or leaves a letterbox like space. The preference here is to crop the images at the cost of keeping the right ratio and centering them. any jquery/css known methods to do so?
Edit
.container{width:200px; height:200px;}
.container img{width:100%;}

That was the closest solution Ive found however its not satisfying at all (height/width obviously changes according to the pics)... currently we use a letterbox to 'scale' the images.
There's also Pixel Daily's photo stack plugin which is used PhotoStack

A: give image height and width 100%
try
.imgClass{  //your class name
height:100%;
width:100%;
}

A: For modern browsers (no IE8 or lower) you could achieve this with css only using the background-size property "cover" in conjunction with the background property inline.

http://jsfiddle.net/EXpb2/1/


text:
Q: Norm Inequality: Other I need help proving this inequality to understand a preliminary remark.
$$\Bigg |\Bigg| \dfrac{x}{\|x\|}-\dfrac{y}{\|y\|}\Bigg |\Bigg| \geq \|x-y\| $$
with $x$ and $y$ satisying $\|x\|,\|y\|\leq 1$ and $\|x-y\|\geq 1$

A: If $\ \| x\| \leqslant \| y \| \ $ , we  write:
$\left\|\dfrac{x}{\| x\|}-\dfrac{y}{\| y\|}\right\| = \left\|\dfrac{x}{\| x\|}-\dfrac{y}{\| x\|} + \dfrac{y}{\| x\| } - \dfrac{y}{\| y\|}\right\|$
We use the triangle inequality to obtain:
$\left\|\dfrac{x}{\| x\|}-\dfrac{y}{\| y\|}\right\| \geq \left\|\dfrac{x}{\| x\|}-\dfrac{y}{\| x\|}\right\| - \left\| \dfrac{y}{\| x\| } - \dfrac{y}{\| y\|}\right\|$
Then:
$\left\|\dfrac{x}{\| x\|}-\dfrac{y}{\| y\|}\right\| \geq \dfrac{1}{\| x\|} \|x-y\| - \left( \dfrac{1}{\| x\|} -\dfrac{1}{\| y\| }\right) \| y\|$
We know that    $\ \|y\| \leqslant 1 \leqslant \| x-y\| $
So:
$\left\|\dfrac{x}{\| x\|}-\dfrac{y}{\| y\|}\right\| \geq \dfrac{1}{\| x\|} \|x-y\| - \left( \dfrac{1}{\| x\|} -\dfrac{1}{\| y\| }\right) \| x-y\| = \dfrac{\|x-y\|}{\| y\|} \geqslant \|x-y\|$

A: Let $\|y\|\geq \|x\|$.
\begin{eqnarray*}
\|x\|\|x-y\|&=&\|y\|\|x-y\|-(\|y\|-\|x\|)\|x-y\|\qquad {\rm (trivially)}\\\\
&\leq&\|y\|\|x-y\|-(\|y\|-\|x\|)\|y\|\qquad {\rm (as}\,\,\|y\|\leq1 \leq\|x-y\|)\\\\
&=&{\large\|}\|y\|(x-y){\large\|}-{\large\|}(\|y\|-\|x\|)y{\large\|}\qquad {\rm (by\,\, scalability\,\, of\,\, norm)}\\\\
&\leq&{\large\|}\|y\|x-\|x\|y{\large\|}\qquad {\rm (by\,\, triangle\,\, inequality\,\, }\|A\|-\|B\|\leq\|A+B\|)
\end{eqnarray*}
Thus $$\|x-y\|\leq \frac{\|x\|\|x-y\|}{\|x\|\|y\|}\leq \left\| \frac{x}{\|x\|}-\frac{y}{\|y\|}\right\|$$


text:
Q: Processing a failed payment in square (should I use a new Idempotency key if the error is related to the customers bank) I am using square to take payments from customers.
When a payment request fails for a reason like insufficient funds etc I want to retry it a few hours later. We are using Card On File so we have the ability to do this.
Should I use the same idempotency key or a new one?
https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency

A: You'll want to generate a new idempotency_key for each new CreatePayment request with the card on file.


text:
Q: Programmatically import ES6 modules So instead of using
import A from './directory1/A'
import B from './directory1/B'
import C from './directory2/C'
import D from './directory3/D'

How can I programmatically write a function that reads from all the directories in my current module parent, and loads the modules inside each directory?


text:
Q: Verifying whether a quotient ring is indeed a ring. Take $$\frac{\Bbb{R[x]}}{\langle x^2+1\rangle}$$ This is a ring. In this quotient ring, the product of equivalence classes $[a+bx]$ and $[c+dx]$ is another equivalence class, as a ring is closed under multiplication.
$[a+bx]=\{a+bx,a+bx+(x^2+1),a+bx+2(x^2+1),\dots\}$, and $[c+dx]=\{c+dx,c+dx+(x^2+1),c+dx+2(x^2+1),\dots\}$.
Also, we should have $[a+bx][c+dx]=[(ac+bdx^2)+(ad+bc)x]$.
Which two elements in $[a+bx]$ and $[c+dx]$ multiply with each other to give $(ac+bdx^2)+(ad+bc)x+(x^2+1)$, which is a member of $[(ac+bdx^2)+(ad+bc)x]$?
Note: I know that $\{a+bx,a+bx+(x^2+1),a+bx+2(x^2+1),\dots\}\neq[a+bx]$; it is only the inverse of $[a+bx]$. I only write all this for a clear exposition: $[m][n]=[mn]$ only because the inverse images of $[m]$ and $[n]$, under the canonical mapping, multiply together to give the inverse image of $[mn]$.
Thanks!

A: To be honest, if you are trying to show this is indeed a ring, there are indirect methods that are far easier.  For example:
Consider the evaluation homomorphism $ev_i:\mathbb{R}[x] \rightarrow \mathbb{C}$ defined as follows:
$$f(x) \mapsto f(i)$$
This homomorphism is indeed surjective since, given any $(a + bi) \in \mathbb{C}$, simply take the polynomial $f(x) = a + bx$.  Further, $ker(\phi) = \langle x^2 + 1 \rangle$.  Now we apply the isomorphism theorem:
$$\mathbb{R}[x]/ \langle x^2 + 1 \rangle \cong \mathbb{C}$$
So it is certainly a ring, and even a field.


text:
Q: Can't Get Any LaTeX Editor To Run I just build a desktop and seem to be having issues getting LaTeX to run.
Important Information:

*

*Windows 7 (64-bit)

*Asus Radeon R9 290

*All LaTeX-related software is saved on the non-OS drive

*Several different editors have been installed and tested (MikTex, LyX, TeXstudio, and TeXworks), all of  seem to be unable to compile/build anything - several were re-installed as a test

*No log file seems to be created

As test code I've been using a basic example copied from the internet, in case it's a package issue, and a cover letter I wrote, as I can guarantee it works (though it does require some packages). Any ideas on what could be the issue here? Thanks for the help!
Screenshot:

Basic Test Code:
    \documentclass[12pt]{article}
%   options include 12pt or 11pt or 10pt
%   classes include article, report, book, letter, thesis

\title{This is the title}
\author{Author One \\ Author Two}
\date{29 February 2004}

\begin{document}
\maketitle

This is the content of this document.

This is the 2nd paragraph.
Here is an inline formula:
$   V = \frac{4 \pi r^3}{3}  $.
And appearing immediately below
is a displayed formula:
$$  V = \frac{4 \pi r^3}{3}  $$
\end{document}

Cover Letter Test (with personal information removed):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Short Stylish Cover Letter
% LaTeX Template
% Version 1.0 (28/5/13)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Original author:
% Stefano (http://stefano.italians.nl/archives/63)
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
% IMPORTANT: THIS TEMPLATE NEEDS TO BE COMPILED WITH XeLaTeX
%
% The two fonts used in this template: Adobe Garamond Pro and Gill Sans
% do not come with Windows by default. You will need to download them in
% order to get an output as in the preview PDF. Otherwise, change those
% fonts to fonts that do come with Windows or comment out the lines to use
% the default font.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%----------------------------------------------------------------------------------------
%   PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------

\documentclass{scrlttr2}

%\usepackage[left=2.5cm, right=2.5cm, bottom=1cm]{geometry}
\usepackage[left=2cm, right=2.5cm, bottom=1cm]{geometry}
\usepackage{fontspec} % Allows font customization
\usepackage{marvosym} % Allows the use of symbols
\usepackage[english]{babel} % Required to compile in Windows
\usepackage{graphicx}

\setlength\parindent{0pt} % Removes all indentation from paragraphs

\defaultfontfeatures{Mapping=tex-text}
%\setmainfont {Adobe Garamond Pro} % Main document font
\setsansfont {Cambria} % Used in the from address line above the to address

\renewcommand{\normalsize}{\fontsize{12}{12}\selectfont} % Sets the font size and leading
\def\second{{\raise.5ex\hbox{\small nd}}}
\makeatletter
\@setplength{refvpos}{8cm}
\makeatother

%----------------------------------------------------------------------------------------
%  PERSONAL INFORMATION
%----------------------------------------------------------------------------------------

%\setkomavar{fromname}{Name} % Your name
%\setkomavar{fromaddress}{Address} % Your address
%\setkomavar{fromphone}{(555) 555-5555} % Your phone number
%\setkomavar{fromemail}{myemail@gmail.com} % Your email address
%\setkomavar{place}{} % City written before the date, put your city here if you want this
\setkomavar{signature}{My Name} % Your name as you want it to appear in the signature
%\setkomavar{date}{\flushleft\vspace{-\baselineskip}\today\par}
\setkomavar{date}{\vspace*{-\baselineskip}}
\newkomavar{phone}
\newkomavar{email}
\setkomavar{phone}{(555) 555-5555}
\setkomavar{email}{myemail@gmail.com}

% These are not used in this document, uncomment if you would like to use them and refer to them as \usekomavar{name}
%\setkomavar{fromfax}{+1 (1)23 456789} % Your fax number
%\setkomavar{fromurl}{http://www.johnsmith.com} % Your personal website
%\setkomavar{frombank}{Postbank 9307157}

%----------------------------------------------------------------------------------------
%  HEADER SECTION
%----------------------------------------------------------------------------------------

\firsthead{
\centering
{\addfontfeature{LetterSpace=20.0}\fontsize{36}{36}\selectfont\scshape Name}\\[5mm]
\fontsize{21}{21}\selectfont\scshape My Title \\ My Institution } % Your current job title

%----------------------------------------------------------------------------------------
%  FOOTER SECTION
%----------------------------------------------------------------------------------------

%\firstfoot{
%\centering
%\addfontfeature{LetterSpace=20.0}\scshape
%{
%\renewcommand{\\}{\ {\large\textperiodcentered}\ }
%\usekomavar{fromaddress}
%}\\
%{\Large\Letter} \usekomavar{fromemail} \ {Large\Telefon} \usekomavar{fromphone} % If you want your fax number or website URL showing, add it here; you may need to play around with spacing
%}

%----------------------------------------------------------------------------------------

\begin{document}

%----------------------------------------------------------------------------------------
% COVER LETTER CONTENTS
%----------------------------------------------------------------------------------------

\begin{letter}{ % Address of the company you are applying to
\today \par \vspace*{2\baselineskip}
Biotech Company \\
123 Street Street \\
Washington, CA 12345
}

%\setkomavar{subject}{Cover Letter} % This is the bold text saying 'Cover Letter', remove it if you don't like it

\opening{Dear Mr. Thompson:\\}

\begin{sloppypar}
My name is...

Thank you for your time and consideration. I am looking forward to a further discussion of this job position. \\

\end{sloppypar}

Sincerely, \\
%\includegraphics[width=6cm]{Signature.png}

\usekomavar{signature}\\
\usekomavar{phone}\\
\usekomavar{email}

%----------------------------------------------------------------------------------------

\end{letter}
\end{document}

Confirmation of Hard Drive Recognition:

A: I figured out the issue. I had an old hard drive with a version of LaTeX installed on it, so when the compiler ran it was calling packages from the old copy- resulting in an endless loop of sorts. Deleting any and all LaTeX files from the hard drive, plus a clear install on the new one, resulted in all the problems being solved. In hindsight I should have just done that right away, but I didn't think LaTeX would do a global search for packages rather than just look in the associated local folder.


text:
Q: MPMoviePlayerController audio/video out of sync In my iPad App, I create an MPMoviePlayerController that plays an MP4 off of a website.  In the MP4 there are people talking.  In the App, I have noticed that the audio and video are out of sync by half a second or a quarter-second, perhaps.  (I can tell this because I view the video in a web browser and there is no lag.)
The only clue that I have to this is that when the MPMoviePlayerController first loads up, the audio starts playing, but the video doesn't--then the video starts playing and it seems to skip a couple of frames to "catch up" to the audio...but it doesn't quite sync.
Seeing as how this class is a "black box" per the Apple Documentation, and none of the existing methods or properties come across as helpful to this problem, I'm a bit stumped.  I may have to leave it how it is with the slight lag, rather than face weird workarounds.  I wanted to see if anyone has experienced this before or could suggest a solution.
I'm running on Mountain Lion, latest XCode, iPad 2 with iOS 6.
The code I use to generate the controller is:
-(void) startVideoPlaying {
if (!self.theMoviePlayer) {
    self.theMoviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: movieURL];
    [self.bgView addSubview: self.theMoviePlayer.view];
    [self.theMoviePlayer.view setFrame: movieContainer.frame]; // player's frame must match parent's
} else {
    [self.theMoviePlayer setContentURL:movieURL];
}
    self.theMoviePlayer.shouldAutoplay = YES;
    [self.theMoviePlayer play];
}

Thanks for any help.

A: After a variety of tests, I must conclude that there is something wrong with the encoding on the MP4s that I have been playing.  I am not a video codec guru, but I made the following tests, which tell me this:
1) Downloading the MP4, placing it into the app and loading it into the MPMoviePlayerController via a file URL.  Audio still out of sync, so not a connectivity issue.
2) Finding another MP4 on the web (something off Vimeo) and streaming it into the Player.  Audio synced properly, potentially something wrong with the MP4s I was attempting to play.
3) Downloading the MP4, and using Handbrake to convert it into M4V with a variety of different settings (including the iPad preset).  The Audio was synced fine.
Based on this, it seems to me like there's something wrong with the file I was attempting to play rather than the player (or the player can't handle it).  Unfortunately, the files I am attempting to play cannot simply be converted, they are part of a large website system and many hundreds of files would have to change, and so on.  So, while I have answered my own question, I haven't solved the problem.


text:
Q: NullInjectorError: No provider for Router Test case in Angular I am using below component.ts, getting below error
StaticInjectorError(DynamicTestModule)[UploadDocumentsLoginContainerComponent -> Router]:
  StaticInjectorError(Platform: core)[UploadDocumentsLoginContainerComponent -> Router]:
    NullInjectorError: No provider for Router!
export class UploadDocumentsLoginContainerComponent implements OnInit {
constructor(
    private fb: FormBuilder,
    private loanStore: Store<LoanState>,
    private router: Router,
    **private activateRoute: ActivatedRoute,**
    private urlProviderService: UrlProviderService
  ) {
    this.activateRoute.queryParams.subscribe(params => {
      this.isMyAccountRequest = params[IS_MY_ACCOUNT];
    });
  }

  ngOnInit() {}

  //on button click
   routeSignin() {
    if (this.isMyAccountRequest) {
      this.router.navigate(['/home']);
    }
  }
}

Test case:
import {
  async,
  ComponentFixture,
  fakeAsync,
  TestBed
  } from '@angular/core/testing';
  import { ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
describe('UploadDocumentsLoginContainerComponent', () => {
  let component: UploadDocumentsLoginContainerComponent;
  let fixture: ComponentFixture<UploadDocumentsLoginContainerComponent>;
  let router: Router;
  beforeEach(async(() => {
    return TestBed.configureTestingModule({
      declarations: [
        UploadDocumentsLoginContainerComponent
      ],
      imports: [
        NgbModule,
        ReactiveFormsModule,
        RouterTestingModule.withRoutes(routes)
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UploadDocumentsLoginContainerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  router = TestBed.get(router);
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('navigate to "" redirects to /register', () => {
    router.navigate(['/register']);
  });
});

To resolve above error i have added below router.
private router: Router

Later getting one more error
UploadDocumentsContainerComponent
    √ should create
HeadlessChrome 75.0.3770 (Windows 10.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\nError: Cannot call Promise.then from within a sync test
Please suggest me how to resolve this Test Case error?


text:
Q: How to sort Ruby table by column headers? I'm creating a To Do List App using Ruby on Rails and I wanted to know how I would go about sorting the information on the table by the headers that I have? Like i'd like to be able to click on "Title" "Client" or "Done" and it sort them ASC or DESC. Also a way to get them back in their original order if possible. T
Here is the code I'm trying:
projects_controller.rb:
class ProjectsController < ApplicationController

  before_action :set_project, only: [:show, :edit, :update, :destroy]
  helper_method :sort_column, :sort_direction

  def index
    @projects = Project.order(sort_column + " " + sort_direction)
  end

  private

  def sort_column
    Project.column_names.include?(params[:sort]) ? params[:sort] : "title"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end

  # GET /projects
  # GET /projects.json
  def index
    @projects = Project.all
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
  end

  # GET /projects/new
  def new
    @project = Project.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = Project.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Project.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:title, :description, :hours, :payrate, :done, :client)
    end

end

application_helper.rb:
module ApplicationHelper
    def sortable(column, title = nil)
      title ||= column.titleize
      css_class = column == sort_column ? "current #{sort_direction}" : nil
      direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
      link_to title, {:sort => column, :direction => direction}, {:class => css_class}
    end
end

index.html.erb:

Project List

        <%= sortable "title" %>
        <%= sortable "client" %>
        Description
        Hours
        <%= sortable "done" %>

      <% @projects.each do |project| %>

          <%= project.title %>
          <%= project.client %>
          <%= project.description %>
          <%= project.hours %>
          <%= check_box_tag "project_#{project.id}", "#{project.done}", project.done?, disabled: "#{project.done?}" %>

              <%= link_to " #{image_tag('show.png')}".html_safe, project, id:'showButton' %>

              <%= link_to " #{image_tag('edit.png')}".html_safe, edit_project_path(project), id:'editButton' %>

              <%= link_to " #{image_tag('destroy.png')}".html_safe, project, id:'destroyButton', method: :delete, data: { confirm: 'Are you sure?' } %>

      <% end %>

  <%= link_to 'New Project', new_project_path, id:"new" %>

A: There is a very good tutorial about it:
http://railscasts.com/episodes/228-sortable-table-columns
You should try this tutorial first, and if you still have questions, please ask again...
I hope it helps.

A: The simple way is use jQuery plugin: DataTables.


text:
Q: \hyphenrules does not break words Following the code used both here and here, using \hyphenrules should inform polyglossia about breaking points within a word. The following code does not break the word in question. Why not? What can I do? I'm using version 1.43 of polyglossia.
\documentclass{article}

\usepackage{polyglossia}
\setmainlanguage{english}

\begin{hyphenrules}{english}
\hyphenation{de-ri-va-tio-nal}
\hyphenation{non-de-ri-va-tio-nal}
\end{hyphenrules}

\begin{document}

\parbox{0pt}{\hspace{0pt}non-derivational}

\end{document}

A: In German language this is a well known problem, because german language contains a lot of concatenated words, single words divided by -. For example: Baden-Württemberg.
If you need hyphenation in the single words you need to add local hyphenations with \-.
In your case change non-derivational to non-de\-ri\-va\-tio\-nal.
Please see the following MWE
\documentclass{article}

\usepackage{polyglossia}
\setmainlanguage{english}

\begin{hyphenrules}{english}
\hyphenation{de-ri-va-tio-nal}
\hyphenation{non-de-ri-va-tio-nal}
\end{hyphenrules}

\begin{document}

\parbox{0pt}{\hspace{0pt}non-derivational}

No - in word:
\parbox{0pt}{\hspace{0pt}nonderivational}

With local hyphenations \texttt{\-}:
\parbox{0pt}{\hspace{0pt}non-de\-ri\-va\-tio\-nal}

\end{document}

and its result:

A: TeX doesn't hyphenate words that contain a hyphen (precisely the current \hyphenchar for the current font).
You can define a macro for this:
\newcommand{\hy}{-\nobreak\hspace{0pt}}

The \nobreak (that is, \penalty10000) disallows a break at the \hspace, which on the other hand allows hyphenation for the following word part.
\documentclass{article}

\usepackage{polyglossia}
\setmainlanguage{english}

\makeatletter % babel has `allowhyphens
\providecommand{\allowhyphens}{\ifvmode\else\nobreak\hskip\z@skip\fi}
\makeatother

\newcommand{\hy}{-\allowhyphens}

\begin{document}

\parbox{0pt}{\hspace{0pt}non\hy derivational}

\end{document}

Here I use a safer definition, that does nothing if \allowhyphens happens to be found in vertical mode. It is essentially the same as in babel.

Note that de-ri-va-tio-nal is very wrong for English hyphenation rules.


text:
Q: "Unable to obtain permission for "name of the share" | win2008r2 File Server So a friend and i wrote a script so we could get some info about the share on our file server but i keep getting an error about the shares, I am a Domain Admin so i dont think the problem is with my permissions.
Here is the script:
$MyPath     = "C:\File Share Info\Shares"
$shares     = gwmi -Class win32_share -ComputerName $computer #| select -ExpandProperty Name
$AllObjects = @()

foreach ($share in $shares) {
$acl = $null
$ShareName = $share.Name
$ShareCaption = $Share.Caption
if ($ShareName -notlike "*$*"){
    $objShareSec = Get-WMIObject -Class Win32_LogicalShareSecuritySetting -Filter "name='$ShareName'"
    #-ComputerName $computer
    try {
        $SD = $objShareSec.GetSecurityDescriptor().Descriptor

        foreach($ace in $SD.DACL){
            $UserName = $ace.Trustee.Name
            If ($ace.Trustee.Domain -ne $Null) {$UserName = "$($ace.Trustee.Domain)\$UserName"}
            If ($ace.Trustee.Name -eq $Null) {$UserName = $ace.Trustee.SIDString }
            [Array]$ACL = New-Object Security.AccessControl.FileSystemAccessRule($UserName, $ace.AccessMask, $ace.AceType)
            $Identity = $ACL[0].IdentityReference.Value

            $myObject = New-Object System.Object
            $myObject | Add-Member -type NoteProperty -name ShareAccessType -Value $ACL[0].AccessControlType
            $myObject | Add-Member -type NoteProperty -name Identity -Value $Identity
            $myObject | Add-Member -type NoteProperty -name ShareRights -Value $ACL[0].FileSystemRights
            $myObject | Add-Member -type NoteProperty -name SharePath -Value $Share.Path
            $myObject | Add-Member -type NoteProperty -name ShareName -Value $Share.Name
            $myObject | select ShareName, Identity, ShareRights, SharePath, ShareAccessType | Export-Csv "$MyPath\permissions.csv" -Append -Encoding Unicode #-NoTypeInformation -Delimiter "`t"

        }
    }
    catch
        { Write-Host "Unable to obtain permissions for `"$ShareName`""; $share.Name | Out-File "$MyPath\Failed.txt" -Append}
}
  }


text:
Q: passing json array to webmethod gives null I'm going crazy. Maybe someone can help.
I have my ajax on the website passing data to the asmx on the backend.
the data is as so. and it's valid json. http://jsonlint.com/
{ "data": [{"Address":"addasdf","City":"casdf","County":"casdf","State":"dc","Zip":"33333","ReferenceID":"asdf","LegalDescription":"asdf","PreviousOwner":"asdf","ClientNotes":"sadf","AcquisitionType":"sadf","ClientAcquisitionDate":"asdf","ForeclosureDate":"asdf"}]}

The ajax sending the data is here. And as far as I can tell this is sending correctly and is right.
$.ajax({
        type: "POST",
        url: "/ServiceFolder/BulkOrder.asmx/insertBulk",
        data: "{ \"data\": " + smyData + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, textStatus, jqXHR) { //
            //alert(data);
            console.log(data);
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            console.log(xmlHttpRequest.responseText);
            console.log(textStatus);
            console.log(errorThrown);
            alert("Screen shot this error getEntityMarkers: " + xmlHttpRequest.toString() + " " + textStatus.toString() + " " + errorThrown.toString());
        }
    });

I have my class that models the data being sent.
[Serializable]
public class BulkOrderObject
{
    public List<BulkOrderObjectData> data { get; set; }
}

[Serializable]
public class BulkOrderObjectData
{
    public string Address { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    public string ReferenceID { get; set; }
    public string LegalDescription { get; set; }
    public string PreviousOwner { get; set; }
    public string ClientNotes { get; set; }
    public string AcquisitionType { get; set; }
    public string ClientAcquisitionDate { get; set; }
    public string ForeclosureDate { get; set; }
}

And finally where I think my problems lie in the webmethod.
[WebMethod]
        public string insertBulk(List<BulkOrderObject> data)
        {

            string myreturn = String.Empty;
            myreturn += data.Count;  // data returns count

            //List<BulkOrderObject> l = data as List<BulkOrderObject>;

            try
            {
                foreach (var i in data)
                {
                    myreturn += i.data.Count;  // error here.
                }
            }
            catch (Exception ex)
            {
                myreturn += ex.ToString();
            }

            return myreturn;
        }

something funky is going on here at public string insertBulk(List< BulkOrderObject > data) when I try to get the number of entries in data.count it shows that there's 1. however when I try to foreach the data in data it returns an error.
    {"d":"1System.NullReferenceException: Object reference not set to an instance of an object.\r\n   at
 test.insertBulk(List`1 data)"}

It's as if it's not filling up the BulkOrderObjectData.
Any thoughts?


text:
Q: How to show description for Custom Function Parameters in Officejs We are using Excel add-in Custom Functions with Batching using OfficeJS and below are the clarifications.

*

*For any new custom functions we were able to show with description for the function selected in Excel.

*But for the parameters used in the functions could not show description for respective parameters when
selected the same.  .

Based on below sample, it is not showing number1 as description when entering num1 parameter.
Sample Custom Functions code
/**
 * Sample Custom addition function
 * @CustomFunction Sampleaddition Sample.add
 * @param num1[][] number1
 * @param [num2]  number2
 * @param [num3]
 */

Kindly let me know if anything missing on above sample or any other details wanted further.
Tried below sample code also but still description of parameters are not displayed both in online version and desktop version.
/**
 * Calculates the sum of the specified numbers
 * @customfunction
 * @param first First number.
 * @param second Second number.
 * @param [third] Third number to add. If omitted, third = 0.
 * @returns The sum of the numbers.
 */
function add(first: number, second: number, third?: number): number {
  if (third === null) {
    third = 0;
  }
  return first + second + third;
}

A: Please follow this format below. You could check if the description is generated the metadata file (you can reference document here


text:
Q: How to test nested input in Go I have function for getting user input using os.Stdin
func (i input) GetInput(stdin io.Reader) (string, error) {
    reader := bufio.NewReader(stdin)

    data, err := reader.ReadString('\n')
    if err != nil {
        return "", fmt.Errorf("get input error: %w", err)
    }

    return strings.ReplaceAll(data, "\n", ""), nil
}

In my programm I need to have 2 inputs:

*

*First for getting base info for example user name

*Second for getting aditional info that depends on first input

name,err := GetInput(os.Stdin)
if err != nil {
 // error handling.....
}

switch name {
  case "test":
    //do something...
    age, err := GetInput(os.Stdin)
    if err != nil {
      // error handling.....
    }
    fmt.Println(age)

  case "another":
    // Here another input
}

It it possible to write unit tests for that case?
For testing one user input I use this snippet and it works:
    var stdin bytes.Buffer
    stdin.Write([]byte(fmt.Sprintf("%s\n", tt.input)))
    GetInput(stdin)

But it didn't work with 2 nested inputs

A: Maybe consider having a function that returns a specific type as a result and put it into a separate package.
Since I see name and age mentioned, perhaps we can assume a concrete type like Person for illustration.
It is important to note that we want to include the actual reader as a parameter and not have a hard coded reference to os.Stdin. This makes the mocking of nested inputs possible in the first place.
With this, the signature of the method could look something like the following:
func NestedInput(input io.Reader) (*Person, error)

The corresponding type could be:
type Person struct {
    Name string
    Age  int
}

If one now combines your code snippets to a complete GO file with the name input.go in a separate directory, it might look something like this:
package input

import (
    "bufio"
    "fmt"
    "io"
    "strconv"
    "strings"
)

func getInput(reader *bufio.Reader) (string, error) {
    data, err := reader.ReadString('\n')
    if err != nil {
        return "", fmt.Errorf("get input error: %w", err)
    }

    return strings.ReplaceAll(data, "\n", ""), nil
}

type Person struct {
    Name string
    Age  int
}

func NestedInput(input io.Reader) (*Person, error) {
    reader := bufio.NewReader(input)
    name, err := getInput(reader)
    if err != nil {
        return nil, err
    }

    switch name {
    case "q":
        return nil, nil
    default:
        ageStr, err := getInput(reader)
        if err != nil {
            return nil, err
        }
        age, err := strconv.Atoi(ageStr)
        if err != nil {
            return nil, err
        }
        return &Person{Name: name, Age: age}, nil
    }
}

An input of q returns nil, nil and could be used to terminate the input, e.g. if the query was made in a loop.
Unit Test
The unit test
func Test_nestedInput(t *testing.T)

in a file named input_test.go should now provide the input data.
Since the NestedInput function now expects an io.Reader as a parameter, we can simply generate the desired input with, for example,
input := strings.NewReader("George\n26\n")

So the test could look something like this:
package input

import (
    "strings"
    "testing"
)

func Test_nestedInput(t *testing.T) {
    input := strings.NewReader("George\n26\n")
    person, err := NestedInput(input)
    if err != nil {
        t.Error("nested input failed")
    }
    if person == nil {
        t.Errorf("expected person, but got nil")
        return
    }
    if person.Name != "George" {
        t.Errorf("wrong name %s, expected 'George'", person.Name)
    }
    if person.Age != 26 {
        t.Errorf("wrong age %d, expected 26", person.Age)
    }
}

Of course, the tests can be extended with further details. But this, as you can see, mocks a nested input.


text:
Q: add qgraphicsitem children to scene I have a QgraphicsObject, and it has a list of Qgraphicsobject children list, I was wondering if there exists a way to add parent to scene and children list added automatically and when I remove parent item from scene all children removed? I want this because I want to add and remove item sever time but I don't want to handle children adding and removing, it's where I add child to my list:
myobject *c_object = new myobject(this); //I set parent item
m_advertisements.append(c_object);

A: QGraphicsItem:

Painting
Items are painted by the view, starting with the parent items and then drawing children, in ascending stacking order. You can set an item's stacking order by calling setZValue(), and test it by calling zValue(), where items with low z-values are painted before items with high z-values. Stacking order applies to sibling items; parents are always drawn before their children.

So, when you add an object (parent) with children they should be painted as described in docs. Children objects can not be painted if their parent was removed from scene.


text:
Q: Normalizing sample data to unit variance Suppose you have data points $X_1,...,X_n$ drawn from some distribution $\mathbb{P}$ (regard them as iid random variables) and let the distribution be "well-behaved" so that the mean is $\mu$ and variance is $\sigma^2$. Now suppose that we want to normalize our data, i.e., find a mapping $X_i \mapsto Y_i$ such that $Y_i$ are iid drawn from a distribution with mean $=0$ and variance $1$. Suppose that we don't know the true values $\mu,\sigma^2$, then it's not too hard to make the mean zero by using the map
$$
X_i \mapsto Y_i\equiv X_i -\hat{\mu}, \quad\hat{\mu} \equiv \frac1n \sum_1^n X_i
$$
Indeed, $\hat{\mu}$ is the sample mean and it's quite easy to check that
$$
\mathbb{E}Y_i =0
$$
Now if I would want to do the same for the variance, the natural method would be something like
$$
X_i \mapsto Y_i \equiv \frac{X_i -\hat{\mu}}{\hat{\sigma}}, \quad\hat{\sigma}^2 \equiv \frac{1}{n-1} \sum_{i=1}^n (X_i -\hat{\mu})^2
$$
Now we know by the convergence in distribution, that when $n\to \infty$, we see that $Y_i\to (X_i -\mu)/\sigma$ in distribution, but the variance doesn't seem to be normalized for arbitrary $n$.
Question. Is is actually possible to normalize the variance of a sample data set without knowing the true mean and variance?
EDIT. To be specific, I want to normalize $X_i$ so that it's population variance is $=1$, not it's sample variance. Indeed,
$$
\mathbb{E} (X_i -\hat{\mu}) =0
$$
So similarly, I would hope that
$$
\mathbb{E} Y_i^2 = 1
$$
Where $Y_i= f_i(X_1,...,X_n)$. What is $f_i$?

A: It's possible to "normalize" the data so that the sample mean is $0$ and the sample variance is $1$, but normalizing based on the sample mean and variance causes problems for the independence of the resulting statistics, because each post-map observation depends on sample statistics, which in turn depend on the other observation. This interdependence causes the sample variance to, on average, be smaller than the population variance, if we calculate the sample variance as $\frac{1}n \sum_{i=1}^n (X_i -\hat{\mu})^2$. This is why the formula $\frac{1}{n-1} \sum_{i=1}^n (X_i -\hat{\mu})^2$ is generally used. So we either use the formula with $n$ in the denominator, in which case we're not getting what we would get from the base distribution, or we use $n-1$, in which case our sample variance is not going to be $1$. And neither choice for the denominator addresses the interdependence issue (this issue is also why we use a t-distribution rather than a normal one for hypothesis testing when the base distribution is normal).


text:
Q: Progress bar в бесконечном ListView как реализовать progress bar во время подгрузки данных в ListView?

A: В первую очередь в xml разметке добавить компонент progress bar:

    <ProgressBar
        android:id="@+id/pbData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:visibility="gone"
        android:indeterminate="true"/>

значение gone параметра visibility, делает компонент невидимым.
Далее в коде, перед началом загрузки данных в ListView, делаете видимым ProgressBar:

mPbData.setVisibility(View.VISIBLE);

После завершения загрузки данных ProgressBar нужно сделать снова невидимым:

mPbData.setVisibility(View.GONE);


text:
Q: VXLAN does not work when brought up initially I am trying to get an overlay network working using VXLAN. It is all in all a fairly simple setup, but for whatever strange reason refuses to work correctly when brought up.
I have two (well, half a dozen really, but that is irrelevant here) hosts, A and B. Both are configured similarly:
ip -6 link add vx1 type vxlan id 99 dstport 4789 local <local-ipv6-address>
bridge fdb append 00:00:00:00:00:00 dev vx1 dst <remote-ipv6-address>
ip link set up dev vx1
ip -6 addr add <random-ula>::10/64 dev vx1

except obviously with local/remote swapped, and with different addresses in the last step.
I have ping6 running from A to B, and as soon as the interface is good to go, I can see traffic on host B (with tcpdump). But there are no responses from B to A. The situation is similar to Why linux does not respond to ICMP Request from VxLAN? but that does not help. This happens both after I bring up the interface by hand, or by having a similar config in /etc/network/interfaces. What does however "fix" the situation is if I send even a single ping from B to A, and suddenly everything magically works.
I've checked routing, iptables, fdb and anything I can think of. Nothing in any of the configs seems to change between simply bringing up the interface and sending the first "fix ping". My problem is of course reboots, so is there anything I can check and possibly do to fix this properly? One option is sending ping messages to all the other hosts in the overlay, but that seems hacky at best, and hardly a reliable solution. Especially when building a larger overlay..

A: I'm not sure about your case, but in my case, it was a misconfiguration from one of the end of the vxlan. The forwarding database (which you can look at using bridge fdb ) one node (A) was containing a wrong information: in particular the 00:00:00:00:00:00 MAC Address was (wrongly) said to be accessible at node A's IP address, instead of being accessible at the IP address of node B.
Appending the correct values using bridge fdb append 00:00:00:00:00:00 dev <VXLAN INTERFACE> dst <IP ADDRESS> and removing the wrong forwarding rules made it work.
The ping is triggering a "correct" behaviour because it allows the peer to discover the IP <-> MAC address mapping, without having to relay on MAC broadcast.


text:
Q: How to add a new value in array and remove if existed using jquery? I have a problem with my code. I am creating a form that has multiple textbox and what my process is. If the user checked the checkbox, there is a function for setting the product ID in the array. If the user unchecked, the product ID in the array must removed. I am using the checkbox onclick trigger effect.
Here's my sample code:
function setProduct(product_id) {

    var arr_product = [];

    //if existed, removed in the array
    if($.inArray(product_id), arr_product) {

        arr = jQuery.grep(arr_product, function(value) {
            return value != product_id;
        });

    } else {

        arr_product.push(product_id);

    }

    return arr_product;

}

function viewSetItems(product_id, product_name, image) {

    var url_link = 'index.php?route=product/product/getSetProducts&product_id=' + product_id;

    $.ajax({
        url: url_link,
        type: 'post',
        dataType: 'json',
        beforeSend: function() {
            $("#display-set-item").fadeIn();
        },
        success: function(data) {

           if(image == '') {
                image = "<?php DIR_IMG_DATA ?>image/cache/data/no_image-200x200.jpg";
           }

           $("#p-img").prepend("");
           $("#p-img").attr("rowspan",data.length + 1);

           var prod_array = [];

           data.forEach(function(i){

                var p_array = i.product_id + "_" + i.price;

                prod_array.push(p_array);

                name = product_name.replace("||", " "); // value = 9:61
                $("#p-name").text(name);

                $h_table = '';

                $nname = i.name;
                $p_name = $nname.replace("||", " ");

                $link = 'index.php?route=product/product&product_id=' + i.product_id;

                $h_table+="
";
                    $h_table+="<input type='checkbox' name='p_price[]' id='pp-"+i.product_id+"' value="+i.price+" onClick='setProduct("+i.product_id+")' />	";
                    $h_table+="" +$p_name+ "	";
                    $h_table+="" +i.price+ "	";
                $h_table+="
";

                $("#table-product-set").append($h_table);

            });

            prod_array.forEach(function(d) {

                var x = d.split("_");
                setProduct(x[0]);

            });

            alert(setProduct());

            $('#table-product-set tr:last').after("
CLOSE<input type='button' class='btn-blue pull-right' value='ADD TO REGISTRY' style=' margin-right: 5px' />
");

        },
        error: function() {
            $("#display-set-item").text('Error');
        }
    });

}

Sorry I have a little knowledge in jquery/javascript. I hope you can help me. Ok that's all guys, Thanks.

A: I'm assuming you meant you have a checkbox per item/product/etc., you have multiple items on a page, and you want to keep track of which items are ticked.
First of all, you're redeclaring your arr_product array on each call of setProduct(), so that's never going to work.
I can see you're dynamically adding the HTML for each checkbox, which is good: it means you already have a loop running through all of them. I would recommend adding a data attribute to each checkbox indicating its index in the array you're going to keep.
Add a variable var index = 0; to your code above the foreach() loop. At the bottom of your foreach() add index++;. You now have an index which keeps track of how many checkboxes you have added, which is also each checkbox its position in the array.
In each iteration of the loop, add this to the checkbox code: data-index="+ index +", making the total:
<input type='checkbox' name='p_price[]' id='pp-"+i.product_id+"' value="+i.price+" onClick='setProduct("+i.product_id+")' data-index=" + index + " />

Also in each iteration, add this event listener:
$("#" + "pp-" + i.product_id).on("change", function(e)
{
    arr_product[$(this).getAttribute("data-index")] = $(this).prop("checked");
}

You now have an event listener attached to each checkbox which sets the corresponding value in an array to true or false, based on whether its checked or unchecked.
Edit: of course the above assumes you place the arr_product somewhere where it isn't re-initialised continuously. Also, if you want to still use your function that's also possible.
Change your function signature to be setProduct(product_index, value), and then call it by replacing the line arr_product[.......("checked"); above with setProduct($(this).getAttribute("data-index"), $(this).prop("checked"));
P.S. I'd recommend using an index attached to the actual checkbox in this case because the handling is much easier overall than a ID-string. However, if you really want to use the ID you can replace the index with an ID.


text:
Q: Ad Hoc distribution for beta testing xcode 4.3 After following the great tutorials from http://www.raywenderlich.com/ on how to submit your app to the app store from square one I started planning my beta test program.
I'm not going to get into details of everything that wen well but of what I'm dealing with right now.
I've read many many posts on how to create provisioning profiles for ad hoc distribution of my app to beta testers.  I've focused on those helping user get the app over the air (OTA) after a forum recommendation.
I also know now that TESTFLIGHT is out there but I can't use it this time.
Everything works well except the part where the application actually gets installed on my device.  I keep getting the error "Unable to Download Application" after a few seconds of pressing "Install".
There are several possibilities and combinations of certificates, profiles, signatures, and here is where I think I'm doing something wrong.  I'd like to show you what I have and what I've done and maybe your experienced eyes can spot my missing step or misconfiguration.
On the iOS Provisional Portal:
1) Ad Hoc distribution profile with a couple of devices:

2) After I download and install my certificates (I've create a couple of each for testing purposes):

3) On my xCode's project configuration:

4) When I generate the archive:

5) I upload everything to my server and then try to get the .ipa to install on my iPhone (which is one of the two devices included on the profile)

And finally I get this:

What could be wrong?

A: The only difference I can see is in the CodeSigning, ensure both lines under Adhoc point to your certificate.
Second thing to verify: You did not mention the plist that is created during the "Save for Enterprice". Did you upload that to your server, too? And does your link point to this plist? Check out this answer for the plist stuff: How to send the build to already provisioned remote person's iPhone

A: I've had this exact problem even where, like you (as far as I can tell), everything is done right.
What I discovered is that if you've EVER had the url to the plist file or the app file incorrect then your iPhone will always fail to install. There's some kind of cacheing going on where the phone fails to download the updated plist file if it's previously downloaded an incorrect one.
The fix I've used is to try a different phone (that hasn't cached a previous version), or to make a  new version at a different URL. Sounds crazy, but it worked for me!

A: We have also faced with this problem couple of times and possible reasons might be;
Due to the screen shots, did you upload your files to exact location "http://www.becomingapps.com/en/ota/" location? When you give this URL during enterprise export.
Second possible reason we have seen is mismatched App Id's.

A: In case you haven't solved your problem, I think you can't use a wild card in your ad hoc profile.  It should have the full ...com.becomingapps.dilemma signature.
You also have to upload both the icons, but I'm assuming you did that since your screenshot shows a custom icon.
It's worth the effort to get this working, my customers love it.


text:
Q: Haproxy multiple backend servers & ports I am a newbie to haproxy and was wondering if someone can confirm that the following config is valid?  Effectively I would like to load balanced two servers on multiple ports.
<snippet>
Listen mybackendLB
  bind 10.6.200.14:555,10.6.200.14:8009,10.6.200.14:443
  mode tcp
  balance roundrobin
  option httpchk "/test.html"
  server app1 192.168.0.20:555 check port 8008
  server app1 192.168.0.20:8009 check port 8008
  server app1 192.168.0.20:443 check port 8008
  server app2 192.168.0.21:555 check port 8008
  server app2 192.168.0.21:8009 check port 8008
  server app2 192.168.0.21:443 check port 8008
<snippet>

In any case would this be a better option?
<snippet>
Listen mybackendLB
  bind 10.6.200.14:555,10.6.200.14:8009,10.6.200.14:443
  mode tcp
  balance roundrobin
  option httpchk "/test.html"
  server app1 192.168.0.20 check port 8008
  server app2 192.168.0.21 check port 8008
<snippet>


text:
Q: A code wars challenge I have been struggling with this challenge and can't seem to find where I'm failing at:
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1

695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n, p will always be given as strictly positive integers.
digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

I'm new with javascript so there may be something off with my code but I can't find it. My whole purpose with this was learning javascript properly but now I want to find out what I'm doing wrong.I tried to convert given integer into digits by getting its modulo with 10, and dividing it with 10 using trunc to get rid of decimal parts. I tried to fill the array with these digits with their respective powers. But the test result just says I'm returning only 0.The only thing returning 0 in my code is the first part, but when I tried commenting it out, I was still returning 0.
function digPow(n, p){
// ...
var i;
var sum;
var myArray= new Array();
if(n<0)
  {
    return 0;
  }
var holder;
holder=n;
for(i=n.length-1;i>=0;i--)
 {
   if(holder<10)
    {
     myArray[i]=holder;
     break;
    }
  myArray[i]=holder%10;
  holder=math.trunc(holder/10);
  myArray[i]=math.pow(myArray[i],p+i);
  sum=myArray[i]+sum;

}
 if(sum%n==0)
  {
  return sum/n;
  }
else
{
  return -1;
}}

A: Here is the another simple solution

  function digPow(n, p){
    // convert the number into string
    let str = String(n);
    let add = 0;
    // convert string into array using split()
    str.split('').forEach(num=>{
      add += Math.pow(Number(num) , p);
      p++;
    });

    return (add % n) ? -1 : add/n;
  }
  let result = digPow(46288, 3);
  console.log(result);

A: You have multiple problems:

*

*If n is a number it is not going to have a length property. So i is going to be undefined and your loop never runs since undefined is not greater or equal to zero
for(i=n.length-1;i>=0;i--) //could be
for(i=(""+n).length;i>=0;i--) //""+n quick way of converting to string

*You never initialize sum to 0 so it is undefined and when you add the result of the power calculation to sum you will continually get NaN
var sum; //should be
var sum=0;

*You have if(holder<10)...break you do not need this as the loop will end after the iteration where holder is a less than 10. Also you never do a power for it or add it to the sum. Simply remove that if all together.
Your end code would look something like:
function digPow(n, p) {
  var i;
  var sum=0;
  var myArray = new Array();
  if (n < 0) {
    return 0;
  }
  var holder;
  holder = n;
  for (i = (""+n).length - 1; i >= 0; i--) {
    myArray[i] = holder % 10;
    holder = Math.trunc(holder / 10);
    myArray[i] = Math.pow(myArray[i], p + i);
    sum = myArray[i] + sum;
  }
  if (sum % n == 0) {
    return sum / n;
  } else {
    return -1;
  }
}

Note you could slim it down to something like
function digPow(n,p){
   if( isNaN(n) || (+n)<0 || n%1!=0) return -1;
   var sum = (""+n).split("").reduce( (s,num,index)=>Math.pow(num,p+index)+s,0);
   return sum%n ? -1 : sum/n;
}

*

*(""+n)     simply converts to string

*.split("") splits the string into an array (no need to do %10 math to get each number

*.reduce( function,0) call's the array's reduce function, which calls a function for each item in the array. The function is expected to return a value each time, second argument is the starting value

*(s,num,index)=>Math.pow(num,p+index+1)+s Fat Arrow function for just calling Math.pow with the right arguments and then adding it to the sum s and returning it

A: Mistakes
There are a few problems with your code. Here are some mistakes you've made.

*

*number.length is invalid. The easiest way to get the length of numbers in JS is by converting it to a string, like this: n.toString().length.
Check this too: Length of Number in JavaScript

*the math object should be referenced as Math, not math. (Note the capital M) So math.pow and math.trunc should be Math.pow and Math.trunc.

*sum is undefined when the for loop is iterated the first time in sum=myArray[i]+sum;. Using var sum = 0; instead of var sum;.
Fixed Code
I fixed those mistakes and updated your code. Some parts have been removed--such as validating n, (the question states its strictly positive)--and other parts have been rewritten. I did some stylistic changes to make the code more readable as well.

function digPow(n, p){
var sum = 0;
var myArray = [];
var holder = n;

for (var i = n.toString().length-1; i >= 0; i--) {
  myArray[i] = holder % 10;

  holder = Math.trunc(holder/10);
  myArray[i] = Math.pow(myArray[i],p+i);
  sum += myArray[i];
}

  if(sum % n == 0) {
    return sum/n;
  } else {
    return -1;
  }
}

console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));

My Code
This is what I did back when I answered this question. Hope this helps.

function digPow(n, p){
  var digPowSum = 0;
  var temp = n;

  while (temp > 0) {
    digPowSum += Math.pow(temp % 10, temp.toString().length + p - 1);
    temp = Math.floor(temp / 10);
  }

  return (digPowSum % n === 0) ? digPowSum / n : -1;
}

console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));

A: I have created a code that does exactly what you are looking for.The problem in your code was explained in the comment so I will not focus on that.
FIDDLE
Here is the code.
function digPow(n, p) {
  var m = n;
  var i, sum = 0;
  var j = 0;
  var l = n.toString().length;
  var digits = [];
  while (n >= 10) {
    digits.unshift(n % 10);
    n = Math.floor(n / 10);
  }
  digits.unshift(n);
  for (i = p; i < l + p; i++) {
    sum += Math.pow(digits[j], i);
    j++;
  }
  if (sum % m == 0) {
    return sum / m;
  } else
    return -1;
}

alert(digPow(89, 1))

A: Just for a variety you may do the same job functionally as follows without using any string operations.

function digPow(n,p){
  var d = ~~Math.log10(n)+1;  // number of digits
      r = Array(d).fill()
                  .map(function(_,i){
                         var t = Math.pow(10,d-i);
                         return Math.pow(~~((n%t)*10/t),p+i);
                       })
                  .reduce((p,c) => p+c);
  return r%n ? -1 : r/n;
}

var res = digPow(46288,3);
console.log(res);


text:
Q: Stored procedure in while affected only first row I try to insert some data with php and a stored procedure. The stored procedure works fine but only for the first row.
PHP:
$sql = "SELECT * FROM [importliste_TCSv3]";

$stmt = sqlsrv_query($conn, $sql);

if ($stmt === false ) {
    die (print_r(sqlsrv_errors(), true));
}

while ($row = sqlsrv_fetch_array($stmt)) {
    // print works fine without call proc
    $query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
    $params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);

    $stmt = sqlsrv_query($conn, $query, $params);

    if ($stmt === false) {
        die (print_r(sqlsrv_errors(), true));
    }
}

Stored Procedure:
ALTER proc [dbo].[difInport]
@mandant_id varchar(50),
@kostenstelle varchar(50),
@vorname varchar(50),
@nachname varchar(50),

@ci_nummer int,
@anzahl_monitore_old int,
@raum varchar(50),
@gebäude varchar(50),
@bemerkung text,

@hardware_typ varchar(50),
@anzahl_monitore_new varchar(50),
@zubehör text

as

BEGIN
    SET NOCOUNT ON;

    DECLARE
    @latestPersonID int,
    @latestCmoID int,
    @latestFmoID int

    INSERT INTO [RC.Persons] (kostenstelle, vorname, nachname) VALUES (@kostenstelle, @vorname, @nachname);
    SET @latestPersonID = (SELECT SCOPE_IDENTITY())

    INSERT INTO [RC.CMO] (ci_nummer, anzahl_monitore, raum, gebäude, bemerkung) values (@ci_nummer, @anzahl_monitore_old, @raum, @gebäude, @bemerkung);
    SET @latestCmoID = (SELECT SCOPE_IDENTITY())

    INSERT INTO [RC.FMO] (hardware_typ, anzahl_monitore, zubehör) values (@hardware_typ, @anzahl_monitore_new, @zubehör);
    SET @latestFmoID = (SELECT SCOPE_IDENTITY())

    INSERT INTO [RC.Persons_RC.CMO] (cmo_id, person_id) VALUES (@latestCmoID, @latestPersonID);

    INSERT INTO [RC.Persons_RC.FMO] (fmo_id, person_id) VALUES (@latestFmoID, @latestPersonID);

    INSERT INTO [RC.Persons_RC.Mandant] (person_id, mandant_id) VALUES (@latestPersonID, @mandant_id);

END

I read this question: Call mysql PROCEDURE inside while loop works only first time
but I dont give any result set or is the set declaration with a select the result problem?

A: You are overwriting your $stmt variable. Change the name of the variable you use in the while loop:
while ($row = sqlsrv_fetch_array($stmt)) {
    // print works fine without call proc
    $query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
    $params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);

    $stmt_proc = sqlsrv_query($conn, $query, $params);

    if ($stmt_proc === false) {
        die (print_r(sqlsrv_errors(), true));
    }
}


text:
Q: Upper before Concat in Postgresql Assuming there is a table called cities with columns name and country, why doesn't this query work?
select
  concat(upper(name, ', ', country)) as location
FROM
  cities;

But the one below does?
select
  upper(concat(name, ', ', country)) as location
FROM
  cities;

I tried both approaches, but couldn't figure out why the first did not work, but the second did.
Now if there are two or more operations, how do I decide on their ordering so the query works?

A: UPPER function only accepts a single string parameter. reference
In the first query, you are passing multiple params, so that causes error.
In your second query, you concat multiple params into a single string then pass it to UPPER, so it works.

A: Postgres' UPPER() function is defined to accept a single string input, not a CSV list of several strings as input.  Apparently, your first query is working without uppercasing, but there is not any guarantee that Postgres should even accept that syntax.
The second version is the correct one, where you concatenate first, then passed that concatenated string as a single input into the UPPER() function.


text:
Q: I have trouble redirecting all traffic not coming from tripadvisor to another website (WordPress) I try to redirect all traffic that is not coming from tripadvisor to another website using php session and javascript on a wordpress website
I need help to correct my script
here is the non working script I developed using php session:
<?php
    if (!isset($_SESSION)) {
        session_start();
    }
    if (!isset($_SESSION['referrer'])) {
        $_SESSION['referrer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'n/a';
    }

    $referer = isset($_SESSION['referrer']) ? $_SESSION['referrer'] : null;
?>
<script type="text/javascript">
    var str = "<?php echo $referer ?>";
    var oktogo = str.includes("tripadvisor");
    if (oktogo== false) {
        window.location.href = 'https://www.mySecondWebsite.com';
    }
</script>

A: Hello guys I've corrected the script myself thanks for your help
Here is the script for people having the same needs
if (!isset($_SESSION)) {
session_start();
}

if(isset($_SERVER['HTTP_REFERER']) && substr_count($_SERVER['HTTP_REFERER'],"tripadvisor") == 1){

$_SESSION['is_refered_from_tripadvisor'] = true;

}

if(!isset($_SESSION['is_refered_from_tripadvisor']) || $_SESSION['is_refered_from_tripadvisor'] == false){
header("Location: https://www.mySecondWebsite.com");
}


text:
Q: Get Install File for Already Installed RPM I would like to install this custom package, packageA, onto another Linux box.
$yum list installed | grep packageA
packageA.x86_64

But, I don't have access to the installation file, i.e. packageA only exists on this box.
How can I do this?

A:
Rpmrebuild is a tool to build an RPM file from a package that has already been installed.

(I found it by looking for an rpm equivalent to dpkg-repack, which I knew about.)


text:
Q: How to Convert Object to Jtoken in C# public void Set(string name, object content)
        {

            this.Json.Add(name, content);

        }

How can I convert  content variable to Jtoken so that I can perform Json.add operation?

A: You can use JObject.FromObject:
this.Json.Add(name, JObject.FromObject(content));

Or JValue.FromObject if you are expecting values which are not mapped to json objects:
this.Json.Add(name, JValue.FromObject(content));


text:
Q: Move files with .bat ONE AT A TIME I have a .bat file that moves everything that starts with TEST_ and ends in .prn. The problem is, if more than one file is moved, something will break. Is there a way to add in a parameter to just move ONE FILE per run?
Original Code:
move s:\FILES\TEST_*.prn s:\ANOTHER_PLACE\Processed

This code works, but if two people uploaded a file at the same time, it would move both files, causing the server on the other end to have issues.

A: If I understand, you want to execute move once per file, not all files at once. You can do this:
FOR %%f IN (s:\FILES\TEST_*.prn) DO (
    move %%f s:\ANOTHER_PLACE\Processed\
)

So, for each file %%f matching s:\FILES\TEST_*.prn, you execute move.

A: If I understanded good this is what you want:
@Echo OFF

Set "InputDir=s:\FILES"
Set "OutputDir=s:\ANOTHER_PLACE\Processed"
Set "Pattern=TEST_*.prn"

FOR %%# IN ("%InputDir%\%Pattern%") DO ((Move "%%f" "%OutputDir%\" && Exit /B 0) || (Exit /B 1))

It moves the first file found alphabetically and then exits.
Also it returns 0 if file moved right, returns 1 if file can't be moved for any reason.
I hope this helps.

A: FOR %%f IN ("s:\FILES\TEST_*.prn") DO set "file=%%~ff"
if defined file move "%file%" "s:\ANOTHER_PLACE\Processed"


text:
Q: CSS spread
* horizontally across
* I'm trying to spread a list of
's aligned horizontally using float:left across my
.
Does anyone have any idea how this is done?

A: Is there some reason why you can't just set them to display: inline; (or inline-block)?  For example:
http://jsfiddle.net/TKmR5/

A: The answer is to use display: table; on the
 element and display: table-cell; on the
 elements.

A: You can use display: inline-block; it works in modern browsers.
Example: http://jsfiddle.net/joar/ELpDD/
As feela said in the comments to #7131346,

[…] "awkward space between items" is caused by not re-setting margins and paddings…

A: Float left and divide the width of the ul over de number of lis I think is what you are after. Have a look here: http://jsfiddle.net/b2nsW/
HTML:

item

item

item

item

CSS:
ul {
    width: 250px;
    background: red;
    padding: 0;
    margin: 0;
    overflow: auto;
}

li {
    width: 20%;
    float: left;
    background: green;
    margin: 2.5%;
}

A: li {
    display: inline-block;
}

ul{
    text-align: center;
}

Then adjust the padding or margins of the li elements to spread them across less or more across the ul.


text:
Q: Submit form only if a checkbox is checked I'm trying to submit a form with javascript, I need that when verifying a checkbox send the form automatically, in a few seconds.
<form  method="POST" action="{{ route('turnox', $event->id) }}">
    {{ method_field('PUT') }}
    @csrf

            Confirmar Asistencia:

                <input name="cconfirma" type="checkbox">

            Cancelar Turno:

                <input name="ccancela" type="checkbox">

</form>

If someone verifies a checkbox, the form is submitted automatically.

A:

let interv
window.addEventListener('DOMContentLoaded', () => {
  document.addEventListener('click', e => {
    if (e.target.type === 'checkbox') {
      console.log('form submitting in 1 second')
      interv = setTimeout(() => {
        console.log('form submitting...');
        // e.target.closest('form').submit();
      }, 1000)
    }
  })
})
<form method="POST" action="{{ route('turnox', $event->id) }}">

      Confirmar Asistencia:

    <input name="cconfirma" type="checkbox">

      Cancelar Turno:

    <input name="ccancela" type="checkbox">

</form>


text:
Q: JQuery find only work in IE So, we use MVC3 grid with two anchor tag in one table column.
We want that with click on a row, get anchor tag value from first table cell.
We succeed in IE*, but in Firefox and Chrome it does not work.
Here is code:
$("#interestTypesGrid tbody tr").live("click", function (e) {
    $("#SelectedInterestTypeID").val($(this).find('td:first a').val());
    $.post(URLGetInterestRates, $("#FormMasterData").serialize(), function (data) { $("#pagedInterestRates").html(data); });
});

So problem is in:
$(this).find('td:first a').val();

This only works in IE !!!

A:  tags don't have value attributes, so .val() shouldn't work.
Try using .text() instead (you may need to $.trim() it).
$(this).find('td:first a').text()

A: the val function is meant mainly for retrieving and setting the value of form elements. To get/set the contents of a non-form tag try using the text or html functions
$("#interestTypesGrid tbody tr").live("click", function (e) {
    $("#SelectedInterestTypeID").val($(this).find('td:first a').text());
    $.post(URLGetInterestRates, $("#FormMasterData").serialize(), function (data) { $("#pagedInterestRates").html(data); });
});

In this code I'm assuming that #SelectedInterestTypeID is a form element, if not you should change that to text as well.
I've tested this working sample in IE and Chrome.
Update
The sample HTML you provided:

    q
    34
    q12

value is not a valid attribute in HTML. If you're targeting HTML5 you could use a data attribute and the data function from jQuery, in fact it'd probably be easiest to put the attribute on the tr:

Then your javascript using the data function:
$("#interestTypesGrid tbody tr").live("click", function (e) {
    $("#SelectedInterestTypeID").val($(this).data("interestType").id);
    $.post(URLGetInterestRates, $("#FormMasterData").serialize(), function (data) { $("#pagedInterestRates").html(data); });
});

Another working sample using this method.
All standards be damned you can just use the attr jquery function to retrieve the value of any arbitrary element attribute.