text:
Q: How do I show Invisibles in GDB output window in Xcode 4? I just tracked down a string equality bug due to string length mismatch. The extra character was '\r' which doesn't show up in the output window in Xcode 4 at all. If it had, I wouldn't have to spend nearly as much time as I did tracking the issue down.
Is it possible to show whitespace characters in the output window? If so, what magic incantation must I recite to enable it?
I tried Show Invisibles under the Editor menu, but that only worked for the code editors, not the output window. I'm using Xcode 4 on an iOS app.

A: I can think of only one solution right now: Creating a category:
NSString+myAdditions.h
@interface NSString (myAdditions)

- (NSString *)showInvisibles;

@end

NSString+myAdditions.m
#import "NSString+myAdditions.h"

@implementation NSString (myAdditions)

- (NSString *)showInvisibles
{
    NSString *regexToReplaceWhitespaces = @"([\\s])";

    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceWhitespaces
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

    NSString *result = [regex stringByReplacingMatchesInString:self
                                                       options:0
                                                         range:NSMakeRange(0, [self length])
                                                  withTemplate:@"␣"];

    return result;
}

@end

Usage
NSLog(@"show me the unseen: %@", [@"soo      many    whitespace in here  \t\t <- look two tabs!" showInvisibles]);

Output
soo␣␣␣␣␣␣many␣␣␣␣whitespace␣in␣here␣␣␣␣␣<-␣look␣two␣tabs!

A: You could percent-escape your string. You can specify which characters to not escape in the third parameter (I included all of the common ones), the rest of which will be escaped:
NSLog(@"%@", CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)yourString, (CFStringRef)@" <>#%{}|\^~[]`;/?:@=&$", NULL, kCFStringEncodingUTF8);


text:
Q: Android- twitter.getFriendsStatuses missing in twitter4j 2.2.6 I am currently migrating from twitter4j-core-2.1.11.jar to 2.2.6.
twitter.getFriendsStatuses(twitter.getScreenName()).toString();

I don't see any such methods in 2.2.6. Surprisingly the libraries are not backward compatible.
Is there an equivalent method in 2.2.6 or some other way to fetch Friends statuses?

A: I was not able to get this method in twitter4j-core-2.2.6.jar
twitter.getFriendsStatuses(twitter.getScreenName()).toString();

so had to stick with 2.1.11
If anyone has a better option, please reply here, it might help someone else who comes searching.

redpajama_set_name: RedPajamaStackExchange


text:
Q: System of annihilating particles – calculating the Lyapunov exponent from annihilation locations. I'm a bit confused with the correct way of calculating the Lyapunov exponent for a particular system that I study.
Imagine we can place $k$ foo-balls and $k$ goo-balls on a surface. Each foo-ball is attracted by any other goo-ball, and when they get close enough, they annihilate each other. There is no closed-form solution of the system and it needs to be solved numerically. The system starts from an initial positional arrangement of these particles in a 2D plane, $S=[[x_1,y_1], [x_2,y_2],...]$ and they all annihilate in different locations one by one, $F=[[x'_1,y'_1],...]$.
In order to calculate the Lyapunov exponent for this system, I dislocate the $S$ a little ($\delta_0$) and this dislocates the $F$. What I cannot figure out is how to calculate the exponent when the initial conditions are more than one. Like simulating the solar system for example. A displacement in the initial condition could be just moving the earth for 1 meter or moving all the planets for 1 meter. Which would be right and how the exponent would be calculated from the final fixed point displacement?
The reason I am trying to find the exponent is that I have seen some simulation results which have made me think this system has a chaotic behavior and I am trying to check it.

A: After all balls have annihilated in your system, there is no dynamics anymore or the dynamics has converged to a fixed point – depending on your perspective. Anyway, there is no long-term chaotic behaviour.
However, the short-term behaviour may be chaotic – a so-called chaotic transient.
You can indeed use Lyapunov exponents to characterise this behaviour.
However, for this the annihilation locations are bad observables for several reasons:

*

*Each annihilation point is associated with a different time point.

*Annihilation is part of ending the chaotic transient. Thus its details do not yield good information about the transient itself. You are looking too late.

*Whether your balls annihilate does not inform the early dynamics. You could probably conceive a system without annihilation whose early dynamics is identical to the one you are observing.
Thus, instead of looking at the annihilation points, I recommend that you look at the position of your balls after a short time and in particular before any annihilations happen. More precisely, consider:
$$ \frac{ | \hat{S}(t)-S(t) | }{ | \hat{S}(0)-S(0) | },$$
where $S'$ is the displaced system and your initial displacement $|\hat{S}(0)-S(0)| = δ_0$ is as small as reasonably possible – I recommend two orders of magnitude above the numerical accuracy threshold. If you average the above for many initial conditions and you really have chaos, it should exponentially grow with $t$, as long as $|\hat{S}(t)-S(t)|$ is small compared to other length scales in the system, such as the usual minimum distance between balls. The exponential growth rate then is the Lyapunov exponent.

A displacement in the initial condition could be just moving the earth for 1 meter or moving all the planets for 1 meter.

That should not matter. The important thing is that the displacement is small.
Strictly speaking, there are some pathologic displacement directions (orthogonal to the largest Lyapunov vector), which will yield a misleading result. However, even if you want to hit this direction, you usually cannot because of numerical accuracies. If you want to be super sure, just randomise your displacement in direction, so the probability that you hit such a pathologic direction is zero.


text:
Q: Java Serialization Behavior I'm going through serialization and I can't understand the following:
I don't understand why the output of this code is:
import java.io.*;

public class InnerOuterTest {
    public static ObjectOutputStream out;
    public static ObjectInputStream in;

    static {
        try {
            out = new ObjectOutputStream(new FileOutputStream("save.ser"));
            in = new ObjectInputStream(new FileInputStream("save.ser"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        try {
            ShouldForgive f = new ShouldForgive();
            f.x = 5;
            write(f);
            ShouldForgive g = read();
            System.out.println(g.x);
            f.x = 0;
            g.x=8;
            write(f);
            ShouldForgive v = read();
            System.out.println("is "+v.x);
        } finally {
            out.close();
            in.close();
        }
    }

    private static void write(ShouldForgive f) throws IOException {
        out.writeObject(f);
    }

    public static ShouldForgive read() throws ClassNotFoundException, IOException {
        return (ShouldForgive) in.readObject();
    }
}

class ShouldForgive implements Serializable {
    int x = -1;
}

Is
5
8

And not
5
0

I tried f == g which returns false and if I reset the input stream. I found out that if I implement readObject it is only called once... I don't understand this behavior. (Why is the object only read once?)
I get the feeling that serialization only happens once... How is the object tracked? Even if I implement readObject and writeObject without actually reading or writing from the file I still get 8

A: If you call out.reset() after the first write, you will get the behaviour you are expecting, or if you use writeUnshared() instead of writeObject(). Objects that have already been written to the stream are not rewritten; instead a 'handle' to the previously written object is written. See the Javadoc for details.

A: OK...I think i got it...

*

*During serialization, its NOT the object which is serialized, but its Instance variable...
as extracted and stored. For an object its instance variable is everything...

*So during de-serialization, the same instance variables are inflated back, and using those
instance variable value, an Another Identical object is created on the heap..

*If you check the hashcode of both these objects, they will be different.
Thats causing the above behaviour mentioned by you.
Either follow this sequence
f.x = 0;
g.x=8;

or this
g.x=8;
f.x = 0;

Still the result will be 8, cause its now a completely different object on the heap with different instance variables.
Edited part
The below code will print f as 5..... for both the sysout
public static void main(String[] args) throws IOException, ClassNotFoundException {
        try {
            ShouldForgive f = new ShouldForgive();
            f.x = 5;
            write(f);
            ShouldForgive g = read();
            System.out.println(g.x);

            f.x=0;
            write(f);
            ShouldForgive v = read();
            System.out.println("is "+v.x);
        } finally {
            out.close();
            in.close();
        }
    }


text:
Q: ASP.NET jQuery not working I am trying to create some numeric only textboxes, this works when tested on JSfiddle but not in my ASP.NET project. code:
Master Page head:

<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />

Default Web Form inside Main content placeholder:

    Input variable a : <asp:TextBox runat="server" ID="varA"></asp:TextBox>

    Input variable c : <asp:TextBox runat="server" ID="varB"></asp:TextBox>

    Input variable b : <asp:TextBox runat="server" ID="varC"></asp:TextBox>

    <asp:Button ID="additionSubmit" runat="server" Text="Submit"
            onclick="additionSubmit_Click" />

     <asp:Label ID="lblAddition" runat="server" Text="" CssClass="label"></asp:Label>

A: Other answers already mention wrapping this in document.ready; that sorts out part of the problem.
Be aware also that ASP.net may alter the IDs of your textboxes. You've catered for this in the first:
$('input[id$=varA]').ForceNumericOnly();

but not the other two. You could also assign them specific CSS classes (which ASP.net won't alter), or set the ClientIDMode to 'Static':

        Input variable a : <asp:TextBox ClientIDMode="Static" runat="server" ID="varA"></asp:TextBox>

        Input variable c : <asp:TextBox ClientIDMode="Static" runat="server" ID="varB"></asp:TextBox>

        Input variable b : <asp:TextBox ClientIDMode="Static" runat="server" ID="varC"></asp:TextBox>

        <asp:Button ID="additionSubmit" runat="server" Text="Submit"
            onclick="additionSubmit_Click" />

        <asp:Label ID="lblAddition" runat="server" Text="" CssClass="label"></asp:Label>

A: You have to wait until your DOM is really ready to execute your script. Try with:
$(document).ready(function() {
    $('input[id$=varA]').ForceNumericOnly();
    $("#varB").ForceNumericOnly();
    $("#varC").ForceNumericOnly();
});

A: Try modify your script to become:
$(document).ready(function() {
   $('input[id$="varA"]').ForceNumericOnly();
   $('input[id$="varB"]').ForceNumericOnly();
   $('input[id$="varC"]').ForceNumericOnly();
});

A: Here is working solution, use only one jQuery library.
Use $(document).ready and use ClientID in jQuery like <%= VarA.ClientID %>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />

    <form runat="server">

            Input variable a :
            <asp:TextBox runat="server" ID="varA"></asp:TextBox>

            Input variable c :
            <asp:TextBox runat="server" ID="varB"></asp:TextBox>

            Input variable b :
            <asp:TextBox runat="server" ID="varC"></asp:TextBox>

            <asp:Button ID="additionSubmit" runat="server" Text="Submit" onclick="additionSubmit_Click"/>

            <asp:Label ID="lblAddition" runat="server" Text="" CssClass="label"></asp:Label>

    </form>


text:
Q: Django app don't run locally, there is no "error" or somthing else... I have Django 1.9 app that runs with python 3.5.1.
First when I run "manage.py runserver" I think it fail because I dont have  "psycopg2",he crushes because he couldn't find "psycopg2",
 I installed it with pip install,  and now there is no error, the "runserver" command works well and give me only that:
    $ /c/Python35/python.exe manage.py runserver

C:\django-master\project\urls.py:12: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
  url(r'^rank2/$', views.rank2, name='rank2'),)

C:\django-master\website\urls.py:21: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
  url(r'^project/', include('project.urls')),

It looks like he is running but when I entered 127.0.0.1 there is nothing, its probably not really work, but I dont know how to debug it because there are no errors, how can I know where the problem is? (I know it could be lot of things but I don't have any direction...)
Thanks...

A: Django is per default running on port 8000 not port 80. Either you go to 127.0.0.1:8000 or you start the server with /c/Python35/python.exe manage.py runserver 80


text:
Q: background image is not working and path is correct i'm trying to add an image as background below my header but it isn't showing.
My html is:

the imagen is supposed to be shown behind this text

My CSS:
.resumen{
    height: 50vh;
    background-image: linear-gradient(to top, rgba(161, 140, 209, 0.5) 0%,
    rgba(251, 194, 235, 0.5) 100%, url(../images/fondo-inicio.jpg));
}

ROOT directory organization:
portfolioweb (main folder)
    - index.html
    -> files (folder)
        -> images (sub folder)
            -imagen.jpg (image that isn't showing)
        -> css (sub folder )
            -style.css

I have tried and none of them works
url(../images/fondo-inicio.jpg)
url('../images/fondo-inicio.jpg')
url(/images/fondo-inicio.jpg)

A: you didn't close linear-gradient in the right position
 background-image: linear-gradient(to top, rgba(161, 140, 209, 0.5) 0%,
    rgba(251, 194, 235, 0.5) 100%, url(../images/fondo-inicio.jpg));

to
 background-image: linear-gradient(to top, rgba(161, 140, 209, 0.5) 0%,
    rgba(251, 194, 235, 0.5) 100%), url(../images/fondo-inicio.jpg);

A: try url('./../files/images/fondo-inicio.jpg');


text:
Q: Crash with Missing cell for newly visible row when updating UITableView I am experiencing a crash when I delete a row.
// Updating my data model
....
// apply the updates
self.tableView.beginUpdates()
self.tableView.deleteRows(at: indexPathsToDelete, with: .automatic)
self.tableView.endUpdates()

Steps to reproduce
- Add rows
- Delete rows, specifically making sure there's some rows outside the current screen (that will then be in screen when the deletion is successful
- Repeat until crash occurs
It doesn't always happen so my best guess is that it will happen only when the cells it's trying to load get recycled
This is in 10.0 simulator with Xcode 8.0
  *** Assertion failure in -[UITableView _updateWithItems:updateSupport:],
 /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.6/UITableView.m:3149
 Missing cell for newly visible row 2
 (null)

code for cellForRowAt
if isMultipe{
   let cell =  tableView.dequeueReusableCell(withIdentifier: DetailsTableViewCell.defaultIdentifier, for: indexPath) as! DetailsTableViewCell
return cell
    } else {
let cell =  tableView.dequeueReusableCell(withIdentifier: DetailsMultipleTableViewCell.defaultIdentifier, for: indexPath) as! DetailsMultipleTableViewCell
   return cell
}

the same bug reported here : https://forums.developer.apple.com/thread/49676

A: I had the same problem and I found out that UITableView has serious problems with animating insert/update/delete rows when section headers are variable height. Just convert the height to some constant and try it again.
This actually means deleting estimatedSectionHeaderHeight.

A: In my case it was crashing when cells have used autolayout for calculating it's height. So, the only guaranteed solution is use manual calculating heights. (what is actually sad..)

A: In my case I had this issue just for inserting the first row to an empty section, so I tried to fix it like this:
self.array.append(item)
if self.array.count > 1 {
    self.tableView.beginUpdates()
    self.tableView.insertRows(at: indexPathes, with: .top)
    self.tableView.endUpdates()
} else {
    self.tableView.reloadSections([1], with: .fade)
}

A: This problem happened to me when I had cells with different sizes. My code:
tableView.estimatedRowHeight = 150
tableView.rowHeight = UITableViewAutomaticDimension

During moving/inserting/deleting, app was crashing with "Missing cell for newly visible row" message. So I removed this line:
tableView.estimatedRowHeight = 150

and implement delegate method in which returned separate estimated height for each row.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {}

Hope it will help someone.

A: Remove indexPath in tableView.dequeueReusableCell
if isMultipe{
   let cell =  tableView.dequeueReusableCell(withIdentifier: DetailsTableViewCell.defaultIdentifier) as! DetailsTableViewCell
return cell
    } else {
let cell =  tableView.dequeueReusableCell(withIdentifier: DetailsMultipleTableViewCell.defaultIdentifier) as! DetailsMultipleTableViewCell
   return cell
}

A: I had a similar problem.
emrekyv suggested to delete estimatedSectionHeaderHeight but I have a table with one seaction and no header and no footer.
Expanding his idea and setting estimatedRowHeight to 0 (= not automatic) fixed the problem.
So the rule is:
Do not estimate any height when updating a UITableView.

A: In my case this happened when I forgot to call super.prepareForReuse() in my custom subclass.
See https://developer.apple.com/documentation/uikit/uitableviewcell/1623223-prepareforreuse:

If you override this method, you must be sure to invoke the superclass
  implementation.


text:
Q: responsive image area map conflict with helix menu I am using a helix menu in joomla 3.3.6.
Ihave used the following script downloaded from http://mattstow.com/experiment/responsive-image-maps/rwd-image-maps.html to make a image map responsive.
the problem is, after i added this script:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

the dropdown function in the helix menu doesnt work anymore.

A: jQuery-rwdImageMaps needs jQuery, so if it is working without the script above ...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

... then you are probably already loading jquery and this one is causing problems.
Try entering ...
$.fn.jquery

... at the console level without the code above to see if it is already loaded.
UPDATE:
This sounds like there MIGHT be a conflict between jQuery and one of the two plugins we're talking about. Take a look at jQuery Conflicts
The other possibility is where the jQuery that does exist is loaded ... can you ensure your image map source file and code is executed AFTER jQuery is loaded.


text:
Q: data accumulation with pandas I'd like to accumulate like this.

timestamp
id
strength

1383260400000
1
strength accumulated by square id1 or id2 == 1

1383260400000
2
strength accumulated by square id1 or id2 == 2

if timestamp is different, making another row.

here is code. but, result is below.
df2["strength"] = pd.to_numeric(df["strength"])
 for i in range(len(df)):
     if (df.iloc[i - 1, 0] != df.iloc[i, 0]) or \
             df.iloc[i - 1, 1] != df.iloc[i, 1]:
         k = k + 1
         print(k)
     df2.loc[k, "timestamp"] = df.iloc[i, 0]
     df2.loc[k, "id"] = df.iloc[i, 1]
     df2.loc[k, "strength"] = df2.loc[k, "strength"] + df.iloc[i, 3]

timestamp
id
strength

4.890249263573871e-05

1383260400000
1
0.00692127440351541

1383260400000
2
0.0031095399526760983

0.0001136447068307

0.0001557162945607

0.0002134019939307

here is raw input data.

timestamp
squareid1
squareid2
strength

1383260400000
1
751
1.0024511991972666e-06

1383260400000
1
752
4.636474149834957e-05

1383260400000
1
753
0.0001289563565283

1383260400000
1
754
6.849944595888879e-05

1383260400000
1
755
9.220729726979178e-07

1383260400000
2
1
5.1182385382982246e-05

1383260400000
2
55
5.1182385382982246e-05

1383260400000
2
56
3.0469237948520085e-06

1383260400000
2
152
8.513520849740889e-05

A: df['group_me'] = df.apply(lambda x: x.squareid1 if x.squareid1 - 1 != x.squareid2 else x.squareid2, axis=1)
output = df.groupby(['timestamp', 'group_me'], as_index=False)['strength'].sum()
print(output)

Output:
       timestamp  group_me  strength
0  1383260400000       1.0  0.000297
1  1383260400000       2.0  0.000139


text:
Q: Mudança de base binária para base decimal Venho tentando programar um código para resolução de um exercício. Eis a questão:
Escreva um programa na linguagem C que leia uma string de tamanho qualquer contendo dígitos binários e imprima na tela o valor decimal correspondente.
A leitura da entrada deve ser feita carácter a carácter usando a função getchar().
Contudo, após de criar um código que eu achava ser melhor complexidade para o programa, percebi um problema à qual não sei resolver.
O Código:
#include <stdio.h>

int main()

{
char c;
unsigned int dec=0, i=1;

do
{

    c = getchar();

    if ( c -'0'== 1)
    {
        dec+= i;
    }

    i*=2;

}
while(c != '\n');

printf("%d\n", dec);

return 0;
}

O problema é que o código está lendo o número e criando um polinômio com sentido esquerda -> direita, e polinômios de mudança de base são lidos no sentido contrario. Devido o uso da função getchar() não sei terminar o exercício. Alguém consegue resolver este problema ?

A: A lógica que tem funciona, mas lendo do bit de menor peso para o de maior peso. O que significa que tem de introduzir os bits ao contrário do que seria normal.
Para resolver esse problema em particular e mantendo a lógica que tem, pode guardar primeiro os bits num array, e depois percorrer esse array na direção inversa, aplicando as mesmas operações.
Exemplo:
#include <stdio.h>

int main() {
    char c;
    unsigned int dec = 0, i = 1;

    char bits[32];
    int bit_corrente = 0;
    while ((c = getchar()) != '\n') { //este while so guarda os bits
        bits[bit_corrente++] = c - '0';
    }

    int j;
    for (j = bit_corrente - 1;j >= 0; --j){ //agora percorre os bits na ordem inversa
        if (bits[j] == 1){
            dec += i;
        }
        i *= 2;
    }

    printf("%d\n", dec);
    return 0;
}

Veja no Ideone
É interessante mencionar que tem muitas formas de fazer a mesma conversão, mas esta é a mais semelhante à lógica que já tinha no código.


text:
Q: HTTP POST request works on emulator, but doesn't on real device I built a simple app which gets data from a remote database using HTTP POST requests. I decided to change its layout, but now the requests I realize doesn't work on a real device.
I simply change the layout and copied the same classes on this new project. I can't understand what's wrong. When I use the app it stops on the splash screen activity and waits there. I looked into the code and I noticed that I stops when are performed the POST requests.
When I execute the project on the emulater, it works perfectly.
This is my class:
public class MyHttpPostRequest extends AsyncTask<String, Void, String[]> {

private String link;
private String querySql;

public MyHttpPostRequest(String remoteLink, String richiestaSql) {
    this.link = remoteLink;
    this.querySql = richiestaSql;
}

@Override
protected String[] doInBackground(String... params) {

    // Create a new HttpClient and Post Header
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost request = new HttpPost(this.link);

    BufferedReader bufferedReader = null;
    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("query", this.querySql));

    StringBuffer stringBuffer = null;

    String[] token = new String[600];

    try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(entity);

        HttpResponse response= httpClient.execute(request);

        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        stringBuffer = new StringBuffer("");
        String line = "";
        String LineSeparator = System.getProperty("line.separator");
        int i=0;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line + LineSeparator);
            token[i] = line + LineSeparator;
            i++;
        }
        bufferedReader.close();
    } catch(Exception e){

    }

    return token;
}

@Override
protected void onPostExecute(String[] result) {
    super.onPostExecute(result);
}

public void eseguiRichiesta(){
    this.execute(this.link, this.querySql);
}

public void setValues(String remoteLink, String richiestaSql){
    this.link = remoteLink;
    this.querySql = richiestaSql;
}

public void setLink(String link){
    this.link = link;
}

public void setRequest(String requestSQL){
    this.querySql = requestSQL;
}
}


text:
Q: Android Layout : LinearLayout equal size circles I am trying to create the layout as seen below.

So far I have the following, however I'm afraid that, based on the screen resolution, the circles could become skewed since I'm hardcoding the height on the main container.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="85dp"
    android:baselineAligned="false"
    android:padding="10dp"
    android:weightSum="5">

    <RelativeLayout
        android:id="@+id/layoutAvatarItem1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_weight="1"
        android:background="@drawable/circle_drawable_color_1">

        <CircleImageView
            android:id="@+id/imgAvatarItem1"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:contentDescription="@string/general_content_desc"
            app:civ_border_color="@color/AppRed"
            app:civ_border_width="2dp" />

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/imgAvatarLoader1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:visibility="gone"
            app:indicatorColor="@color/White"
            app:indicatorName="BallPulseIndicator" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layoutAvatarItem2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="5dp"
        android:layout_marginEnd="5dp"
        android:layout_weight="1"
        android:background="@drawable/circle_drawable_color_1">

        <CircleImageView
            android:id="@+id/imgAvatarItem2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:contentDescription="@string/general_content_desc"
            app:civ_border_color="@color/AppRed"
            app:civ_border_width="2dp" />

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/imgAvatarLoader2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:visibility="gone"
            app:indicatorColor="@color/White"
            app:indicatorName="BallPulseIndicator" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layoutAvatarItem3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="5dp"
        android:layout_marginEnd="5dp"
        android:layout_weight="1"
        android:background="@drawable/circle_drawable_color_1">

        <CircleImageView
            android:id="@+id/imgAvatarItem3"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:contentDescription="@string/general_content_desc"
            app:civ_border_color="@color/AppRed"
            app:civ_border_width="2dp" />

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/imgAvatarLoader3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:visibility="gone"
            app:indicatorColor="@color/White"
            app:indicatorName="BallPulseIndicator" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layoutAvatarItem4"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="5dp"
        android:layout_marginEnd="5dp"
        android:layout_weight="1"
        android:background="@drawable/circle_drawable_color_1">

        <CircleImageView
            android:id="@+id/imgAvatarItem4"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:contentDescription="@string/general_content_desc"
            app:civ_border_color="@color/AppRed"
            app:civ_border_width="2dp" />

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/imgAvatarLoader4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:visibility="gone"
            app:indicatorColor="@color/White"
            app:indicatorName="BallPulseIndicator" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layoutAvatarItem5"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="5dp"
        android:layout_weight="1"
        android:background="@drawable/circle_drawable_color_1">

        <CircleImageView
            android:id="@+id/imgAvatarItem5"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:contentDescription="@string/general_content_desc"
            app:civ_border_color="@color/AppRed"
            app:civ_border_width="2dp" />

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/imgAvatarLoader5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:visibility="gone"
            app:indicatorColor="@color/White"
            app:indicatorName="BallPulseIndicator" />

    </RelativeLayout>

</LinearLayout>

Circle_drawable_color_1 XML
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/BackgroundColor1" />
    <stroke
        android:width="1dp"
        android:color="@color/AppRed"/>
</shape>

How can I create the layout above as a LinearLayout, horizontal orientation with 5 of my Relative layouts within it so that as the screen size grows/shrinks, the circles will also grow/shrink?
Thank you!

A: To achieve responsive UI, first you need to get rid of hard coded values
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" <!-- make it wrap so it can grow -->
    android:baselineAligned="false"
    android:padding="10dp"
    android:weightSum="5">

    <RelativeLayout
        android:id="@+id/layoutAvatarItem1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_weight="1"
        android:background="@drawable/circle_drawable_color_1">

        <CircleImageView
            android:id="@+id/imgAvatarItem1"
            android:layout_width="match_parent"
           <!-- make it match, so it stretches to fit -->
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:contentDescription="@string/general_content_desc"
            app:civ_border_color="@color/AppRed"
            app:civ_border_width="2dp" />

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/imgAvatarLoader1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:visibility="gone"
            app:indicatorColor="@color/White"
            app:indicatorName="BallPulseIndicator" />

    </RelativeLayout>
    <!-- repeat for other four circles -->
</LinearLayout>

Now LinearLayout will fit in width and divide the items equally based on available screen width, so width of your circles are calculated based on screen size, now all you need to do is to match the height of the circle to it's width in Java/kotlin
layoutAvatarItem1.post {
    layoutAvatarItem1.layoutParams = (layoutAvatarItem1.layoutParams as LinearLayout.LayoutParams).apply {
        height = width
    }
}

You can do same for all the other circles


text:
Q: batch rename multiple files in windows? I wonder what's wrong with my coding, because it's not working
I want to rename all the png files inside Chris.
but it failed
for /f  in ('C:/Users/Chris/Downloads/images/*.png')
 do ren "C:\Users\Chris\Downloads\images\*.png" "%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%-img.png"

A: No need for /f in argument, no need for quotes but your missing a variable declaration
The variable should be used in the do-part otherwise the for is not realy helpful
the for will enumerate the full path so you need to strip the filename using ~n
the do-part must be directly behind the for-statement or it needs to be inside round brackets
here's the complete code:
for %%i  in (C:/Users/Chris/Downloads/images/*.png) do (
   ren "%%i" "%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%-%%~niimg.png"
)

A: If order to use a for loop, you need to specify a variable to use (even if you don't use a variable in the loop at all), otherwise you'll get a syntax error. While variables can only be one letter, this is pretty much the only time in batch that variables are case-sensitive, so you've got 52 letters, plus a few additional characters that I've seen used, like #. Additionally, do must always be on the same line as the ).
A for /F loop can process strings, text files, and other batch commands.

*

*To process strings, use double quotes: for /F %%A in ("hello world") do echo %%A

*To process batch commands, use single quotes: for /F %%A in ('dir /b') do echo %%A

*To process text files, do not use any quotes at all: for /F %%A in (C:\Users\Chris\image_list.txt) do echo %%A
You may also want to go into the directory that you're processing just to make things easier.
pushd C:\Users\Chris\Downloads\images
for /F %%A in ('dir /b *.png') do (
    REM I'm not sure what the %HR% variable is supposed to be, so I'm ignoring it.
    ren "%%A" "%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%-img.png"
)


text:
Q: Python: Lambda return string if char is digit I am working on a dataframe. I used pd.read_csv to read a file.
I have a column in which is an ID. Some contains alphabet chars and some are purely numeric. Because of this, the numeric data where read as numbers. I want to transform them to string so later I can df.replace them with real names.
staff_df = pd.DataFrame([
    {'Name': 'Kelly', 'ID': 'ABC321'},
    {'Name': 'Sally', 'ID': 'XYZ123'},
    {'Name': 'James', 'ID': '123450'}
])

staff_df = staff_df.set_index('Name')

This is my code right now, but is invalid syntax:
staff_df[1] = staff_df[1].apply(lambda x: str(x) if x.isdigit())

It will be good if its lambda. :)


text:
Q: Simple Client Manager Soft - C# with Visual Studio or Java with Eclipse? )
Im currently studying Computer Science, and I know a bit of Java, C, C# and Python.
At the same time Im working part time in a Book Store, just selling books.
Lately Ive been thinking that we, in the library, could use the help of a small piece of software to keep track of our clients. So I decided to program it.
I have the basic idea of how to code it in mind; But I can not decide what to use; It would be one of my first programs with a (simple) visual interface.
So, what do you advice guys? C# and using VS, or Eclipse with Java, using one of the Visual Interface plugins.
Or maybe you have a better idea in mind, If so, I would love to hear it :)
Thank you for your time ;)

A: The first question here is which one you are more comfortable with, C# or Java and the required additional toolkits for GUI programming such as swing. Since you are going to make a kind of experimental small application you don't really need many bells and whistles of these technologies so whatever you pick you will be satisfied with. If your application is going to be run on any OS other than Windows (or multiple OSs) I strongly recommend you to use Java with whatever IDE you like. NetBeans and Intellij Idea are as good as Eclipse (even if not better) in desktop application programming but this is not important and just a matter of personal preference. But if you are going to develop just for Windows I think Visual Studio with C# will make a very satisfying experience for you and in my opinion you will spend less time developing the app if you go with the MS offering (This is the opinion of a long time Java fan)

A: This is perhaps not the best question to ask on SO as it's bound to get opinions rather than answers, with this in mind, I will give you my opinionated answer.
As your first real life application, it's probably best you go with something you're somewhat familiar with, either that or find a solution with simple, quick set up guides for beginners.
Both of the languages and environments you mentioned have these.
Myself,  I would use C#. It's always been my go to language to demonstrate some real world problems as it's generally quite quick to get going. Once you download Visual Studio and start writing code, it all just comes together. There is plenty of material available at MSDN which has examples of code with how it should be used, there are even some tutorials on there, I believe one of them is actually a book shop tool.
Have a look there and see what you find.
Ultimately, you'll likely have to make a decision as to the language and development style / environment that you like, but for now, you have one biased opinion from a happy and content .NET developer.

A: IMHO try Javascript (with jQuery) or if you know Excel - use it.
Building a working UI, that behaves as you would expect can be hard (read: time consuming) at first. Personally I find C# really easy, but that is because I have years of experience. General rule is that you learn by failed attempts and remember : expert has failed more then beginner has ever tried.


text:
Q: how to Colorize Shell Command Line Linux BASH Shell:

*

*not Change The Color of  Shell Prompt

*not Change The Color of  Shell Output line

I just want to only Colorize The Shell Command Line
(looks like under pic yellow)
enter image description here


text:
Q: calling a tell and told prolog predicate from java does not work I have the below code and when I run it through Prolog it creates a new file with a new rule. For example, I run
create_rec(check_symptoms(Symptoms,noOk))

it creates a new file with name rule_new and content all predicates with the old rules
and the new rule predicate with content is
 rule(r15,_G3583,_G3601):-check_symptoms(_G3593,noOk)

The problem is that when I call the predicate create_rec from Java it does not work:
rules([r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14]).

% other predicates

create_rec(Body) :-
    clause(rules(R_ids), B1),
    last(R_ids,LastRule_id),
    atom_codes(LastRule_id, Rule_codes),
    Rule_codes = [H|T],
    atom_codes(AtomNum,T),
    atom_number(AtomNum,Num),
    NewNum is Num+1,
    atom_codes(NewNum,NewNumCodes),
    atom_codes(NewRule_id,[114|NewNumCodes]),
    append(R_ids, [NewRule_id], New_R_ids),
    retract(rules(R_ids)),
    asserta((rules(New_R_ids))),
    asserta((rule(NewRule_id,A,B) :- Body)),save_rule.

    save_rule :-
        tell('rule_new.pl'),
        write(':- dynamic rule/3, rules/1.'),nl,
        write(':- [\'kb_anemia_V5b.pl\'].'),nl,
        write(':- encoding(utf8).'),nl,
        write(':- style_check(-singleton).'),
        clause(rules(R_ids),B),nl,
        write((rules(R_ids) :- B)),
        write('.'),
        get_rule_data(R_ids),
        told.

get_rule_data([]).
get_rule_data([Rule_id|Rest_Rule_Id]) :-
        clause(rule(Rule_id,A,B),Body1),
        % fix(B,[],B2),
        write(rule(Rule_id,A,B2):-Body1),write('.'), nl,
        get_rule_data(Rest_Rule_Id).

% other predicates

The code in Java is:
Term consult_arg[] = {
    new Atom(Diagnosis.class.getResource("anemia_diagnosis").getPath())};
Query consult_query = new Query( // to kanei query gia na ginei
                        "consult", //to consult
                        consult_arg);

boolean consulted = consult_query.hasSolution();

if (!consulted) {
    System.err.println("Consult failed");
    System.exit(1);
}

bodycr = body_txt1.getText();

String t9 = "create_rec(" + bodycr + " )." + "\n";

System.out.println("FUNCTION IS   " + t9);
Query q9 = new Query(t9);
diagnosis = q9.oneSolution().toString();
System.out.println(diagnosis);
JOptionPane.showMessageDialog(null, "KB is created  ");

It takes the body from the textarea and call the predicate. The pop up message is displayed , no bugs were found but the file is not created.
I don't know what is wrong. Can anyone help me?


text:
Q: How to use j2html when have a method that needs to return multiple tags? How to use j2html when have a method that needs to return multiple tags?
So here I have a reusable method that constructs a label and inputfield for a particular option. The label is put inside a td and the input field in another td field, all within a tr, and the tr is returned.
Logically this is just one thing (user input) so it makes sense to have within a single method rather than a separate method for label and input. This works fine for my webpages where i have a series of rows, each one containing label and input field all lines up nicely within a table. (Coming from a Java background I see use of table as simply a layout manager, and a more sensible approach then trying to use entirely CSS)
public Tag addInputTextTr(UserOption userOption, String value, String className)
{
    return tr(
            td(label(userOption.getLabelMsg())
                    .withTitle(userOption.getTooltipMsg())),
            td(input()
                    .withType(Html.TEXT)
                    .withName(userOption.getOption()).withValue(value)
                    .withClass(className)
            )
    );
}

Calling Code
addInputTextTr(UserOption.LICENSE_GUID1, licenseGuid1, LICENSE_INPUTFIELD_CLASS)

My problem is that sometimes I need three table cells so I can add a button at the end of the row. So to account for this I should just return the tds from this function and wrap into tr myself in calling method, but I cant just return two tds unless I wrap into a list, then this means i have to use each() in calling code which complicates it. I cannot return them in a span() since span() is not allowed within tr().
public List<Tag> addInputTextTds(UserOption userOption, String value, String className)
    {
        List<Tag> tds = new ArrayList<>();
        tds.add(
            td(label(userOption.getLabelMsg())
                    .withTitle(userOption.getTooltipMsg())));
        tds.add(
            td(input()
                    .withType(Html.TEXT)
                    .withName(userOption.getOption()).withValue(value)
                    .withClass(className)
            )
        );
        return tds;
    }

Calling code now
tr(
   each(addInputTextTds(UserOption.LICENSE_EMAIL, licenseEmail, LICENSE_INPUTFIELD_CLASS),
           next -> next
   )
),

I was looking for a j2html return type that could be used to store multiple elements ?

A: I spent a while playing different solutions for this. The simplest one I was able to come up with is:
public static void main(String[] args) {
    String html =
        html(
          body(
            ul(
              makeSomeChildren()
            )
          )
        ).renderFormatted();
}

private static DomContent makeSomeChildren() {
    return join(b("Child 1"), b("Child 2"));
}

which produces:

            Child 1Child 2


text:
Q: Calculate the volume under the function $f(x,y) = xy$ on a region $R$
I am trying to find the volume underneath $f(x,y) = xy$ on the region $R$ shown in the picture.
I tried integral on polar coordinates:
$$\int_0^{\pi/2}\int_1^4 \left(r\cos\theta\right)\left(r\sin\theta\right)\, dr \, d\theta$$
but this doesn't give one of the answer choices so I don't know what is wrong.
I tried also multiplying by one of the random things you have to add on the end of polar coordinate integrals like $r$ or $r^2$ but it doesn't work
$$\int_0^{\pi/2}\int_1^4 \left(r\cos\theta\right)\left(r\sin\theta\right)r \, dr \, d\theta$$
and this doesn't work either
$$\int_0^{\pi/2}\int_1^4 \left(r\cos\theta\right)\left(r\sin\theta\right)r^2 \, dr \, d\theta$$
None of them give answers that are one of the four choices.

A: The correct one is
$$
\int_0^{\pi/2}\int_1^4 \left(r\cos\theta\right)\left(r\sin\theta\right)r \, dr \, d\theta = \frac{255}{8}
$$
where $rdrd\theta$ is the differential area element and $(r\cos\theta)(r\sin\theta)$ is the height of the differential area element.


text:
Q: Constrain Django model by field value Consider the following Django model:
class Account(models.Model):

    ACCOUNT_CHOICES = [
        ('m', 'Main',),
        ('s','Secondary'),
        ('o', 'Other')
    ]
    user = models.ForeignKey(User)
    level = models.CharField(max_length=1, choices=ACCOUNT_CHOICES)

How can I enforce a database constraint of a maximum of one 'Main' account per user, while still allowing users any number of 'Secondary' or 'Other' accounts? In a sense, I want unique_together for user and level, but only when the value of level is m.
I know that I can manually check on saving, but I would prefer the database to check automatically and raise an IntegrityError when appropriate.

A: I don't think you can do that with your current model, but if those are the only two choices for the level field, consider changing it to a nullable BooleanField, for example
is_main = models.BooleanField(null=True)

and set it to None for secondary accounts. Then a unique_together will work because every null value is unique as far as SQL is concerned (see this answer).
Since there are more choices for the level field as you later clarified, you may add a third field and possibly override the .save() method to have it automatically set to None if level is not "m" for extra convenience.
Edit: If you are not concerned about portability, @Trent has suggested that PostgreSQL supports partial unique indexes, for example:
create unique index u_i on accounts(user_id, level_id) WHERE level_id = 'm';

Here is an SQL Fiddle.
Edit 2: Actually it looks like it is finally possible to create partial indexes in Django ORM starting from Django 2.2. See this question for details.


text:
Q: how to replace content of specified column in a huge file using Unix Command I have a huge file around 10 GB. And I want to replace its 35th column (separated by ;). Since, its a huge file, opening file in an editor is not an option. I want to do replace in all the lines of file.
Somebody suggested me to use Sed but i am not comfortable with it yet. Could somebody suggest a unix command that can achieve the same.

A: awk -F';' '{ $35 = "replacement" }' < oldfile > newfile

A: This might work for you (GNU sed):
 sed -i 's/[^;]*/replacement/35' file

A: the accepted solution didn't work for me. But helped me in finding this:
awk '{$35 = "replacement"; print $0}' < oldfile > newfile
for a tab separated file


text:
Q: Pandas - what is exactly "label" and where is it defined? In pandas documents, the term label is used as if it is granted that we know what it is, such as in Indexing and selecting data.

The axis labeling information in pandas objects serves many purposes:

pandas provides a suite of methods in order to have purely label based indexing. This is a strict inclusion based protocol. Every label asked for must be in the index, or a KeyError will be raised. When slicing, both the start bound AND the stop bound are included, if present in the index. Integers are valid labels, but they refer to the label and not the position.

But what is exactly label in Pandas and where is it formally defined? I believe we define the terminology first before using it.
Are they "a column name", "list of column names", "range of columns defined as a slice", "row index", "list of row indices", "range of rows defined as slice"?

A: From the documentation you linked to we can gather some examples of 'labels':

*

*A single label, e.g. 5 or 'a' (Note that 5 is interpreted as a label of the index. This use is not an integer position along the index.).

*A list or array of labels ['a', 'b', 'c'].

*A slice object with labels 'a':'f' (Note that contrary to usual Python slices, both the start and the stop are included, when present in the index! See Slicing with labels and Endpoints are inclusive.)

Therefore, we can conclude that a 'label' is a named value of the index (not being the integer position).


text:
Q: Mkdir permission denied php nginx I Tried create dir with php code mkdir($folder, 777, true);, but return mkdir(): Permission denied,  how i can solve this ?
Obs: I using: nginx, php7-fpm and owner folder www is www-data

A: Your code:
mkdir($folder, 777, true);

Add a zero before 777, It may solve the problem:
mkdir($folder, 0777, true);

Also, check with your localhost publish permissions.


text:
Q: Multi Layer JSON for AngularJS ng-repeat format My Data looks like this:
[
  {
    "TravelerExtended": {
      "ExtendedInt_1": {
        "#text": "0",
        "Label": "Do you require the hotel has a spa or fitness center?:"
      },
      "ExtendedInt_2": {
        "#text": "0",
        "Label": "Do you prefer to be prechecked into your room?:"
      },
      "ExtendedInt_3": {
        "#text": "0",
        "Label": "Connecting/Adjoining rooms, when traveling with family?:"
      },

Then, my $scope is this:
define(function () {
    return function ($scope, $ticket, $person, $http, $el, $app) {
        // TODO

    $scope.is_loading = true;

    var params = {
        url: "http://10.100.1.98:81/myidapi.php",

        // Any other parameters will be sent as-is
        // to your remote web service.
        // For example, here we are sending an 'email' parameter:
        id: $ticket.id
    };

    $http.get('DP_URL/agent/misc/proxy', {params: params}).success(function(data) {
        $scope.is_loading = false;
        $scope.profiles = data;

    });

    };

});

Then, of course, I have the HTML output trying to use the various NG functions:

        Extended Profile

         {{field.label}} {{field.#text}}

I can't seem to figure out how to get to the third level of data.  It seems that that perhaps the initial data load is malformed, or that I just am bungling up the ng-repeat functions.

A: ng-repeat works on array... in the data structure which you pasted, you got one array only (profiles) and within it an object (TravelerExtended) within which there are 3 more objects (ExtendedInt_1, ExtendedInt_2, ExtendedInt_3).
To traverse them, you need to work within a single ng-repeat (because you have one array only). The following code does the traversing for the data structure you pasted.

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
    "Alfreds Futterkiste",
    "Berglunds snabbköp",
    "Centro comercial Moctezuma",
    "Ernst Handel",
  ]

  $scope.profiles = [{
      "TravelerExtended": {
        "ExtendedInt_1": {
          "text": "0",
          "Label": "Do you require the hotel has a spa or fitness center?:"
        },
        "ExtendedInt_2": {
          "text": "0",
          "Label": "Do you prefer to be prechecked into your room?:"
        },
        "ExtendedInt_3": {
          "text": "0",
          "Label": "Connecting/Adjoining rooms, when traveling with family?:"
        }
      }
    },
    {
      "TravelerExtended": {
        "ExtendedInt_1": {
          "text": "0",
          "Label": "2 Do you require the hotel has a spa or fitness center?:"
        },
        "ExtendedInt_2": {
          "text": "0",
          "Label": "2 Do you prefer to be prechecked into your room?:"
        },
        "ExtendedInt_3": {
          "text": "0",
          "Label": "2 Connecting/Adjoining rooms, when traveling with family?:"
        }
      }
    }
  ];

  /*
  for(var i=0; i<$scope.profiles.length; i++){
    console.log($scope.profiles[0].TravelerExtended);
    console.log($scope.profiles[0].TravelerExtended.ExtendedInt_1);
  }
  */

});

    {{traveler.TravelerExtended.ExtendedInt_1.Label}} {{traveler.TravelerExtended.ExtendedInt_1.text}}

    {{traveler.TravelerExtended.ExtendedInt_2.Label}} {{traveler.TravelerExtended.ExtendedInt_2.text}}

    {{traveler.TravelerExtended.ExtendedInt_2.Label}} {{traveler.TravelerExtended.ExtendedInt_2.text}}

A: What said from Akber is right. If you need to cycle automatically inside your object you could do something like this:
$http.get('DP_URL/agent/misc/proxy', {params: params}).success(function(data) {
       $scope.is_loading = false;
       $scope.profiles = formatData(data);

   });
formatData(dataObject) {
       var dataArray = [];
       angular.forEach(dataObject, function(value, key) {
               dataArray.push(value);
       });
       return dataArray;
   }


text:
Q: In MongoDB, how to roll back update to one collection if update fails on another collection? For example, a user is deleted in the members collection. Thus, all of its documents must also be deleted in all other collections.
After successfully deleting the user from the members collection, how do I ensure that the cascading deletes will succeed in other collections? What if they don't succeed? How do I know of this inconsistency that is now in my database?


text:
Q: Books on multivariable calculus I'm looking for a book that covers the following subjects: multivariable functions, extremes of multivariable functions, integration, implicit function theorems, functions defined by integrals, vector valued functions, Green's theorem, Stokes theorem, divergence theorem, second order ODEs.
I need to learn this for work reasons so in looking for a book that's primarily easy to follow and very intuitive as to why stuff works. Extreme formality is not a necessity at the moment.
Also, could all this be learned in about a week of uninterrupted study?
E: Considering the 1-2 week deadline a secondary stretch goal and prioritizing reading ease, what would be the best option?
Thanks a lot!

A: If you really want to just cram that stuff into your head, you can find it all in Do Carmo's Differential Geometry in the chapter appendixes where it is offered as review. To be honest, you could find summaries of that stuff on wikipedia. Really all you're asking for is to know a few formulas - how to optimize multivariable functions, do vector calculus and then the theorems you listed above. You won't get much out of it at all that way, but I guess that's why I'm telling you it's really just for cramming sake.
If you want to learn something, even if it takes longer, I might suggest the books by Zorich, which I always liked. If you use these books, it will take you a while, but you will come to understand deeply what is going on when you are applying these ideas you're discussing. There is some emphasis on the implicit and inverse function theorems, which are really important theorems that arise in analysis, at the end. I don't know what kind of work you're looking for, but in my work, I use these theorems much more than Green or Stokes.


text:
Q: How to set firefox so that it asks for profile while opening? How to set Firefox so that it will ask choose profile while running Firefox ? Can i edit the Firefox binary for the same ? if yes, how can it be possible ?

A: If you are not using Unity

*

*Copy the global firefox.desktop file to ~/.local/share/applications:
cp /usr/share/applications/firefox.desktop ~/.local/share/applications

*Open the local copy with gedit:
gedit ~/.local/share/applications/firefox.desktop

*Look for the first line, starting with Exec=
Change it into
Exec=firefox -P

*Log out and back in, now when you run firefox, it will show:

If you are using Unity:
There is another option to conveniently choose between profiles:

Add both profiles to the firefox quicklist.
To do so

*

*copy the global firefox.desktop file to ~/.local/share/applications:
cp /usr/share/applications/firefox.desktop ~/.local/share/applications

*Then open the local copy:
gedit ~/.local/share/applications/firefox.desktop

and look for the line:
Actions=NewWindow;NewPrivateWindow;

[I'll use default and TestTest as examples for your profiles, replace the names by your real profile names.]
Change the line into:
Actions=NewWindow;NewPrivateWindow;default;TestTest;

*Now add the following section to the very bottom of the file:
[Desktop Action TestTest]
Name=TestTest
Exec=firefox -P TestTest
OnlyShowIn=Unity;

[Desktop Action default]
Name=default
Exec=firefox -P default
OnlyShowIn=Unity;

*log out and back in, your Firefox launcher should look like in the image,
and you can choose from which profile to open a new window.

EDIT
As requested by OP, an additional section. The solution above works fine, but new windows are opened in the same profile.
To avoid that, add another item to your firefox quicklist, to open a new window with an arbitrary profile. To do so:

*

*Open the local firefox.desktop file that you created (copied), as described in the answer.

*Look (again) for the line:
Actions=NewWindow;NewPrivateWindow;default;TestTest;

change it into:
Actions=NewWindow;NewPrivateWindow;default;TestTest;New window with profile;

*Add to the very end of your file a section:
[Desktop Action New window with profile]
Name=New window with profile
Exec=firefox -new-instance -P
OnlyShowIn=Unity;

Now you can choose to open a new window in a specific profile:

A: Or when you don't want to change your desktop files you can simply edit ~/.mozilla/firefox/profiles.ini and change line:
StartWithLastProfile=1

to:
StartWithLastProfile=0

A: Finally i managed to edit the binary of Firefox to get the profile while opening.
Open  /usr/bin/firefox file in any text editor with sudo privilege and edit the last part of the file.
After editing that file would be look like this.
else
    exec $MOZ_LIBDIR/$MOZ_APP_NAME -P --no-remote "$@"
fi

Thats all. After saving the file when you open Firefox it will ask for profile.


text:
Q: How to multiply two columns in yii2 grid view I want to multiply two columns in the yii2 grid the grid view is as follows
<?= GridView::widget([
        //'dataProvider' => $dataProvider,
        'dataProvider'=>new ActiveDataProvider([
          'query' => Adanalytics::find()->
                where(['publisher_id' =>  Yii::$app->user->identity->id ])->
                select('id,ad_id,MAX(impression) AS impression, MAX(view) AS view, MAX(clicks) AS clicks,MAX(cpc) AS cpclick,MAX(cpv) AS cpview, (MAX(clicks)*MAX(cpc)) AS totalccost')->
                groupBy('ad_id, visitor_ip'),
        ]),
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'id',
            'ad_id',
            //'advertiser_id',
            //'publisher_id',
            //'visitor_ip',
            //'type_ad',
            'impression',
            'view',
            'clicks',
            //'placed_date',
            //'cpc',
            //'cpv',
            'cpclick',
            'cpview',
            'totalccost',
            //'cpi',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

But it is not giving me the desired output where am I going wrong how can i do this?

A: If you need the column only as display value in the gridview you can create a calculated column.
'cpview',
[
    'label' => 'Totalcost',
    'value' => function($model){
        return $model->cpclick * $model->clicks;
    }
],

Or else you can add at the start of your Adanalytics class
public $totalccost;

A: if you want to use the calculation anywhere you can do following.
in your model
public function getTotalcost()
{
   return $this->clicks * $this->cpclick;
}

and you can label to this attribute
public function attributeLabels()
{
    return [
        ...
        'totalcost' => Yii::t('app', 'Total cost'),
    ];
}

in grid view column
...
'cpview',
'totalcost'

You can use this function anywhere as $model->totalcost

A: I have solved the problem by using yii2 db query which is like this way.
$subquery = Adanalytics::find()->
            select('id,ad_id,date_event,max(cpc) cpclick,max(cpv) cpview,max(impression) impression,max(view) view,max(clicks) clicks,visitor_ip,publisher_id')->
            from('ad_analytics')->
            where(['publisher_id' =>  Yii::$app->user->identity->id ])->
            groupBy('ad_id,date_event,visitor_ip');
  $query=Adanalytics::find()->
        select('ad_id,date_event,sum(cpclick) total_click_cost,sum(cpview) total_view_cost,sum(impression) total_impression,sum(view) total_views,sum(clicks) total_clicks,publisher_id')->
        from(['t'=>$subquery])->
        groupBy('t.ad_id,t.date_event');

And called the column in grid view.
'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'ad_id',
        'total_impression',
        'total_views',
        'total_clicks',
        'total_click_cost',
        'total_view_cost',
        'date_event',

        ['class' => 'yii\grid\ActionColumn'],
    ],

Defined them in model before calling.
  public $total_click_cost;
   public $total_view_cost;
   public $total_impression;
   public $total_views;
   public $total_clicks;


text:
Q: problems installing sqlite3-rubygem and mysql I have recently updated my mac to snow leopard and am having a terrible time configuring it for rails development. I have followed the tutorial at hivelogic (http://hivelogic.com/articles/compiling-ruby-rubygems-and-rails-on-snow-leopard) and am being returned with the following error. I have also attempted to install sqlite3-ruby gem and am returned with identical issues. I have tried uninstalling the whole build and reinstalling it. I have also tried working with macports. What is the next step?
michael-orcutts-macbook:src michaelorcutt$ sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql

Password:

Building native extensions.  This could take a while...

ERROR:  Error installing mysql:

ERROR: Failed to build gem native extension.
/usr/local/bin/ruby extconf.rb --with-mysql-dir=/usr/local/mysql

checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lmygcc... no
checking for mysql_query() in -lmysqlclient... no

*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
 --with-opt-dir
 --without-opt-dir
 --with-opt-include
 --without-opt-include=${opt-dir}/include
 --with-opt-lib
 --without-opt-lib=${opt-dir}/lib
 --with-make-prog
 --without-make-prog
 --srcdir=.
 --curdir
 --ruby=/usr/local/bin/ruby
 --with-mysql-config
 --without-mysql-config
 --with-mysql-dir
 --with-mysql-include
 --without-mysql-include=${mysql-dir}/include
 --with-mysql-lib
 --without-mysql-lib=${mysql-dir}/lib
 --with-mysqlclientlib
 --without-mysqlclientlib
 --with-mlib
 --without-mlib
 --with-mysqlclientlib
 --without-mysqlclientlib
 --with-zlib
 --without-zlib
 --with-mysqlclientlib
 --without-mysqlclientlib
 --with-socketlib
 --without-socketlib
 --with-mysqlclientlib
 --without-mysqlclientlib
 --with-nsllib
 --without-nsllib
 --with-mysqlclientlib
 --without-mysqlclientlib
 --with-mygcclib
 --without-mygcclib
 --with-mysqlclientlib
 --without-mysqlclientlib

Gem files will remain installed in /usr/local/lib/ruby/gems/1.8/gems/mysql-2.8.1 for inspection.
Results logged to /usr/local/lib/ruby/gems/1.8/gems/mysql-2.8.1/ext/mysql_api/gem_make.out

Thanks!

A: Check your MySQL Server version. You need to install the 64-bit version.


text:
Q: Convert MySQL backup (dump script) to MS SQL? I have a mysqldump output of a fairly large (by measure of doing things manually) database saved in a text file.  Does anybody know of a (free) way to use this to build a database in MS SQL?  I'm specifically using SQL Server 2008.

A: You could reload that data back into MySQL and execute mysqldump using the following:
mysqldump -h... -u... -p... --compatible=mssql > MSSQL_Compatible_Data.sql
Here is what the mysqldump --help --verbose says on that
--compatible=name   Change the dump to be compatible with a given mode.
By default tables are dumped in a format optimized for
MySQL. Legal modes are: ansi, mysql323, mysql40,
postgresql, oracle, mssql, db2, maxdb, no_key_options,
no_table_options, no_field_options. One can use several
modes separated by commas. Note: Requires MySQL server
version 4.1.0 or higher. This option is ignored with
earlier server versions.
Give it a Try !!!

A: I used something like this:
-- Path/Filename of inputfile for later use
declare @Out varchar(100)
set @out = 'c:\data\Test\TBL1245.dat'

-- Define a structurefile based on a predefined target-table for later use:
exec master..xp_cmdshell  'bcp DB4711.dbo.[TBL1245] format nul -t\t  -c -x -f "c:\data\Test\Config\TBL1245.xml" -T'

-- initialie the targettable:
truncate table   DB4711.dbo.[TBL1245]

-- Load the data:
INSERT DB4711.dbo.[TBL1245]
exec('SELECT *
FROM OPENROWSET (
    BULK ''' + @out + '''
    , FORMATFILE = ''c:\data\Test\Config\TBL1245.xml''
    , ROWS_PER_BATCH = 100
) as co_in
where KeyFLD is not NULL') -- a condition may be set here if needed

Assuming you have a table (TBL1245) in a database (DB4711) to hold all the fileds of your datadumo-file. if you have to change delimiter see in ms-bol for the bcp parameters.


text:
Q: Is it possible to change the color of a border every 75px? I'd like to put a border with 3 alternating colors with a height of 75px on both the left side and right side of my website. The left side was easy - there were many divs each with a height of 75px. I simply used the CSS nth-of-type selector to alternate the border colors. The right side of my website, however, is a div of unknown width and height that contains the content of my website. How can I achieve the same effect if I'm unable to use the nth-of-type selector?
Here's a section of the border of my left hand page:

I'd prefer not to use images. CSS3 is fine as long as it gracefully degrades if the user's browser isn't up to spec.

A: you may use a repeating-linear-gradient with background-size or an image to fake that border.
 div {
   height:300px;
   background:repeating-linear-gradient(to bottom,#0194BE 0, #0194BE 75px, orange 75px, orange 150px, #E2D397 150px, #E2D397 225px) repeat-y;
   background-size:2px 225px;
 }

http://codepen.io/anon/pen/yDqrb
Else look for the use of border-image http://www.w3.org/TR/css3-background/#border-images.
if you use multiple background, you can draw all borders and even do the fake columns


text:
Q: What would the equivalent of the Dehn's Invariant of higher dimensions be? Dehn's invariant in $\Bbb R^3$ is constructed by taking the tensor product of the edge lengths and the dihedral angles at each edge and govens what polyhedra are equidecomposable. I assume that this invariant is dimension specific and for higher dimensions, for say $\Bbb R^4$ you could find the tensor product of the 1D faces and 2D dihedral angles and the 2D faces and its dihedral angles between the 3D faces. Giving you two invariants for $\Bbb R^4$ and I would assume $n-2$ invariants for $\Bbb R^n$.
Is this correct? Does it even make sense to take the dihedral angles between 3D faces in $\Bbb R^4$. Would this mean that for two polyhedra, of dimension n, they would need held equal invariants at every level for them to be equidecomposable?

A: Encyclopedia of Mathematics states "For higher dimensions there is a generalization, called the Hadwiger invariant or Dehn–Hadwiger invariant. This has given results in dimension four, [a4], and for the case when the group consists of translations only, [a2]" and gives references
[a2]    C.H. Sah, "Hilbert's third problem: scissors congruence" , Pitman (1979)
[a4]    B. Jessen, "Zur Algebra der Polytope" Göttinger Nachrichte Math. Phys. (1972) pp. 47–53


text:
Q: Начало изучения OpenGl Здравствуйте.
У меня есть пару вопросов, как мне кажется, стандартных при старте изучения OpenGl.

*

*
Расскажите подробнее про версии (как мне известно, их 4), в чем их различие, существенное ли оно и т.д. и т.п.

*
Подскажите пожалуйста хорошую книгу или видеоуроки без литья воды и заумных выпендрежей.

A: Если вы уже научились программировать в windows, то вам сюда - это уже чистый (без дополнений) opengl под windows.
А книги по opengl почти все одинаковые (ищите их на ozon.ru), все описывают его стандарт (но хвалят все opengl red book и вот эту).
Обновление
Весь opengl - это набор функций, что-то убирают, что-то добавляют отсюда, и версии разные. Насчет крайсиса я смотрел сравнивающую directx и opengl демку, разницы при рендеринге нет http://www.youtube.com/watch?v=HC3JGG6xHN8


text:
Q: How to unflatten a JSON object and merge similar keys? I have JSON in the given format :
{
"literature":
[
  {
   "category": "medical",
   "title": "med title",
   "abstract":"med abstract"
  },
  {
  "category": "medical",
  "title": "med title2",
  "abstract":"med abstract2"
  },
  {
  "category": "economics",
  "title": "eco title",
  "abstract":"eco abstract"
  },
  {
  "category": "science",
  "title": "sci title",
  "abstract":"sci abstract"
  }
]
  }

Desired Output :
{
"literature":
[
  {
"medical":
[
  {
   "title": "med title",
   "abstract":"med abstract"
  },
  {
  "title": "med title2",
  "abstract":"med abstract2"
  }
]
},
  {
  "economics":
[
  {
  "title": "eco title",
  "abstract":"eco abstract"
  }
 ]
},
  {
  "science":
   [
     {
  "title": "sci title",
  "abstract":"sci abstract"
     }
   ]
  }
]
}

I would convert the JSON to javascript object using JSON.parse() and then I would modify that object, making the category attribute as the key and merging the data inside the similar keys as illustrated above. I'm struck since the last three days, Please help me out.

A: Create new object and use for...of to rewrite values

const response = {
"literature":
[
  {
   "category": "medical",
   "title": "med title",
   "abstract":"med abstract"
  },
  {
  "category": "medical",
  "title": "med title2",
  "abstract":"med abstract2"
  },
  {
  "category": "economics",
  "title": "eco title",
  "abstract":"eco abstract"
  },
  {
  "category": "science",
  "title": "sci title",
  "abstract":"sci abstract"
  }
]
  }

function groupByCategory(items) {
 const grouped = {}
 for(const item of items) {
  grouped[item.category] = grouped[item.category] || [];
  const itemCopy = { ...item };
  delete itemCopy.category
  grouped[item.category].push(itemCopy)
 }

 console.log(grouped)
}

groupByCategory(response.literature)

A: You can be done easily with reduce like below

const rawData = {"literature":[{"category":"medical","title":"medtitle","abstract":"medabstract"},{"category":"medical","title":"medtitle2","abstract":"medabstract2"},{"category":"economics","title":"ecotitle","abstract":"ecoabstract"},{"category":"science","title":"scititle","abstract":"sciabstract"}]}

function formatData(data) {
  return Object.keys(data).reduce((acc, key) => {
      acc[key] = data[key].reduce((groups, {category, ...rest}) => {
      if (!groups[category]) {
        groups[category] = [];
      }
      groups[category].push(rest);
      return groups;
    }, {});
    return acc;
  }, {});
}

const result = formatData(rawData);

console.log(result)


text:
Q: Running a PL/SQL block using Java Say I have following procedure -
DECLARE
   enqueue_options     dbms_aq.enqueue_options_t;
   message_properties  dbms_aq.message_properties_t;
   message_handle      RAW(16);
   message             custom_payload_type;

BEGIN
   message := custom_payload_type('Subject','Body');

   dbms_aq.enqueue(queue_name => 'my_demo_queue',
         enqueue_options      => enqueue_options,
         message_properties   => message_properties,
         payload              => message,
         msgid                => message_handle);

   COMMIT;
END;

Using spring jdbc I already created a datasource>
I Dont have this procedure stored in data base. These procedure hardcoded in java side.
How to run this SQL block using java?

A: Use a CallableStatement:
String plsql = "..... your code in here ...";
Connection conn = dataSource.getConnection();
CallableStatement cstmt = conn.prepareCall(plsql);
cstmt.execute();

A: If you only have the stored procedure in your Java code as a String, you need to create the stored procedure with Connection.createStatement() and then execute it with something like prepareCall("{call  your_procedure_name()}") and execute.
See Creating Stored Procedures in Java DB with SQL Scripts or JDBC API for more detailed steps. Or this page for the Oracle equivalent.
Rough code steps are below. For brevity, I ommited try catch blocks, setting input parameters for the call statement, registering output parameters, etc. Like I said, the full answer can be obtained by extracting relevant paragraphs from the documentation links I posted above.
Connection conn = dataSource.getConnection();
String createProcedure = "create procedure enque_message(" + ... ;
Statement stmt = conn.createStatement();
stmt.executeUpdate(createProcedure);

CallableStatement cStmt = conn.prepareCall("{call enque_message()}");
boolean hadResults = cStmt.execute();
while (hadResults) {
    ResultSet rs = cStmt.getResultSet();
    // process result set
}


text:
Q: Problems with parsing facebook using Jsoup I wrote a program to parse facebook, and I can get the whole DOM tree already. Things go well but when I want to select all <p>-tags, the problem is it returns a zero sized array.
PS: Nothing goes wrong when I parse other websites but facebook.
Here is my code:
public static void main(String[] args) throws IOException {
    doc = connect(); //connect the website,
    System.out.print(doc.outerHtml());//in the wole html file, i can find the tag <p>
    newsHeadlines = doc.select("p"); //nothing
    doc.getElementsByTag("p");//nothing either
    oldEleStr = newsHeadlines.text();
    System.out.println(oldEleStr);//nothing
}

static Document connect() throws IOException {
    org.jsoup.Connection connection = Jsoup
            .connect("facebook.com")
            .cookies(
                    splitCookies(facebookCookies));
    Document doc = connection.get();
    return doc;
}

A: You may want to try something like:
Document new_doc = Jsoup.parse(doc.outerHtml());
Elements elements = doc.select("p");
for (Element aa : elements) {
    //TODO:
}


text:
Q: Why does this approximation for 8 work? I previously saw that peculiarly $\frac{987654321}{123456789}\approx 8$. I was wondering if there was any significance to it i.e. if there is any way to derive this approximation (aside from long division).
I already shared my solution. I would love to see other interesting methods (if any).

A: More generally, in base $b$, the number with digits decreasing from $b-1$ to $1$ is
$$ N = \sum_{i=0}^{b-2} (i+1) b^i = \frac{b-2}{(b-1)^2} b^{b} + \frac{1}{(b-1)^2}$$
while the number with digits increasing from $1$ to $b-1$ is
$$D = \sum_{i=0}^{b-2} (b-1-i) b^i =  \frac{b^b}{(b-1)^2} - \frac{b^2-b+1}{(b-1)^2}$$
For large $b$, the dominant terms are those with $b^b$, so
$$ \frac{N}{D} \sim b-2 $$

A: We can express $987654321$ as approximately $\sum_{k=-9}^\infty -k\cdot 10^{-k-1}$ and $123456789$ as approximately $\sum_{k=1}^\infty k\cdot 10^{9-k}$
If we take
$$f(x)=\sum_{k=-9}^\infty x^k=\frac{x^{-9}}{1-x}$$
then
$$f'(x)=\sum_{k=-9}^\infty kx^{k-1}=\frac{-9x^{-10}+10x^{-9}}{(1-x)^2}$$
$$\implies f'(x)=\sum_{k=-9}^\infty kx^{k-1}=\frac{-9x^{-10}+10x^{-9}}{(1-x)^2}$$
$$\implies x^2f'(x)=\sum_{k=-9}^\infty kx^{k+1}=\frac{-9x^{-8}+10x^{-7}}{(1-x)^2}$$
$$\implies -10^2\cdot f'\left(\frac{1}{10}\right)=\sum_{k=-9}^\infty -k\cdot 10^{-k-1}=\frac{8\cdot 10^{10}}{81}$$
Similarly, if we take
$$g(x)=\sum_{k=0}^\infty x^k=\frac{1}{1-x}$$
then
$$g'(x)=\sum_{k=1}^\infty k\cdot x^{k-1}=\frac{1}{(1-x)^2}$$
$$\implies x^{-8}g'(x)=\sum_{k=1}^\infty k\cdot x^{k-9}=\frac{x^{-9}}{(1-x)^2}$$
$$\implies 10^8\cdot g'\left(\frac{1}{10}\right)=\sum_{k=1}^\infty k\cdot 10^{9-k}=\frac{10^{10}}{81}$$
Hence, from our approximations for $987654321$ and $123456789$, it follows that $\frac{987654321}{123456789}\approx 8$

A: We have that in base $8$

*

*$987654321=7267464261_8$

*$123456789=726746425_8$
then
$$987654321-8\cdot 123456789=7267464261_8-10_8\cdot 726746425_8=11_8=9$$


text:
Q: stored procedure returns different columns We've been running stored procedures on an MS SQL database though ODBC using PHP. Whenever we run a sp it always returns the same two column names, regardless of the sp run. If the results set has more than two columns, only the first two are returned.
It's like it's got stuck on the results from a previous query. Even when run on their own, in a php file containing only that sp, every sp returns two columns with the same titles as before, regardless of the number of columns or column titles that should be returned. The contents of the columns matches the first two columns we would expect.
Example: looking up contact like in an address book returns the following with the column names of a sp executed this morning, which contained only two columns in the result set.
01234 567890 | John
01234 567890 | Alice
When it should return
01234 567890 | John | Smith | M
01234 567890 | Alice | Chalk | F
with column names 'number' 'fName' 'sName' and 'gender'.
Code is:
$query = "{CALL dbo.storedProc('functionName', $search, 'id')}";
$resultSet = odbc_prepare($connection, $query);
odbc_execute($resultSet, array());
odbc_result_all($resultSet);


text:
Q: Hadoop PriviledgedActionException Through my web application I am trying to run a mapreduce job. The application is deployed on tomcat server when the map reduce job runs
I get follwing exception
15/12/17 23:38:36 ERROR security.UserGroupInformation: PriviledgedActionException as:tomcat7 cause:org.apache.hadoo
p.security.AccessControlException: Permission denied: user=tomcat7, access=WRITE, inode="":hduser:supergroup:rwxr-x
r-x
15/12/17 23:38:36 INFO ipc.Server: IPC Server handler 6 on 54310, call mkdirs(/out/StichedFile/_temporary, rwxr-xr-
x) from 104.154.95.48:41285: error: org.apache.hadoop.security.AccessControlException: Permission denied: user=tomc
at7, access=WRITE, inode="":hduser:supergroup:rwxr-xr-x
org.apache.hadoop.security.AccessControlException: Permission denied: user=tomcat7, access=WRITE, inode="":hduser:s
upergroup:rwxr-xr-x
        at org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker.check(FSPermissionChecker.java:217)
        at org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker.check(FSPermissionChecker.java:197)
        at org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker.checkPermission(FSPermissionChecker.java:141)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkPermission(FSNamesystem.java:5758)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkAncestorAccess(FSNamesystem.java:5731)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.mkdirsInternal(FSNamesystem.java:2502)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.mkdirs(FSNamesystem.java:2469)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.mkdirs(NameNode.java:911)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:587)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1432)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1428)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
        at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1426)

How to get rid of this problem?

A: This is most probably a permission issue. There are two ways to solve it.
You can disable permission in hdfs-site.xml
<property>
    <name>dfs.permissions</name>
    <value>false</value>
  </property>

Or either you can give write permission to user 'tomcat7' in hadoop.

A: user tomcat7 don't have write permissions to call
mkdirs(/out/StichedFile/_temporary

Set permissions (write & read) for this user for this directory or add this user to superuser group to address this error.


text:
Q: Traversing a heap vs a BST in a sorted manner Cheers, I came across a question which I thought was a bit tricky.
It stated that we have to compare the worst-case time complexity of traversing all the elements in a sorted manner using a heap, and a BST. Which one from the below is true?

*

*Sorted traversing in a BST is faster

*Sorted traversing in a heap is faster

*Both are O(n)

*Both are O(nlogn)

Traversing a BST in a sorted manner is O(n) using In Order Traversal, but what about the heap? I think that the way the heap is constructed makes us have no clue about how to traverse its elements in a sorted manner. That's why a heap is used for quick min/max finding and removals and insertions. But that's where it stops. I think we can also derive this from the way that it constructed, as the Complete Binary Tree is created by placing every node with key  bigger or equal to our current node to, the right OR the left (each node is greater or equal than its children).Is my way of thinking correct?
Also I think (4) is just a trick answer if anyone gets confused with heap-sort, and has nothing to do with an actual correct answer, so I would end up answering (1). Any wrong assumptions? Thanks for your time!

A: Here's one way to see why it's not possible (in the comparison model) to iterate over the items of a binary heap in sorted order in time O(n). Given any group of n elements, you can build a heap from them with the heapify algorithm in time O(n). If you could then iterate over that heap in sorted order in time O(n), you could then sort n items in time O(n) by simply applying the algorithms in order. In fact, this tells you something stronger - any (comparison-based) algorithm for iterating over a heap in sorted order must take time Ω(n log n) in both the worst and average case.
It is possible to iterate over the items of a binary heap in sorted order in time O(n log n), either by copying the heap and using a heapsort or by using an auxiliary heap as follows: enqueue the root element, then repeatedly dequeue from the heap and enqueue the node's children.
In that sense, option (1) is correct because an inorder traversal of a BST takes time O(n), compared with O(n log n) for a binary heap. Option (2) is incorrect (though conceivably for small binary heaps you'd see heapsort beating an inorder traversal of a BST due to locality of reference). Option (3) is wrong because the heap iteration takes time Ω(n log n) in the comparison model. But weirdly enough, option (4) is also correct. Yes, an inorder traversal takes time O(n), but since big-O is an upper bound it would be less precise but not technically wrong to bound it as O(n log n). But option (1) is probably the best one.


text:
Q: Battlefield: Bad Company 2 online disconnecting I got Battlefield Bad Company 2 last night on Steam and I was trying to play online, but I get disconnected within 5 minutes of joining and usually get an error saying: "You have lost connection to the EA server".
I have read that BFBC2 uses port forwarding so I went to www.portforward.com and there was a guide to set it up for my DLink router, however I still get disconnected. I don't believe its an issue with my internet because I have played other online games fine on it, and can download things such as movies with sufficient speed.
I am going to give it another try this evening, but I was wondering if anyone else who came across this problem possibly had other suggestion on what I could do to possibly fix this?
Edit: I tried updated my punkbuster as well as playing server without punkbuster along with other troubleshooting steps but the disconnection continued, I then contacted ea and they got me to run a program that traces packets, and they told me the problem is with my internet service provider and that I am losing packets.

A: I contacted ea and they got me to run a program that traces packets, and they told me the problem is with my internet service provider and that I am losing packets. If anyone else comes across this problem I first recommend the punkbuster solution, then doing the port forwarding and if all else fails contact ea, and it may be the same as my issue. Its rogers internet but its through techsavy


text:
Q: How to use VS2010 publishing to add write access to a folder for Network Service? I need to ensure some upload directories always have write access for Network Service. I created a ProjectName.wpp.targets XML file containing configuration to add this in during the publishing process in Visual Studio 2010 but it doesn't seem to work. There are no errors but write access is not applied. I restart VS after any change, so it's not caching a previous version. Here's my XML:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="SetupCustomAcls" AfterTargets="AddIisSettingAndFileContentsToSourceManifest">
        <ItemGroup>
            <MsDeploySourceManifest Include="setAcl">
                <Path>$(_MSDeployDirPath_FullPath)\Assets\Uploads\FirstFolder</Path>
                <setAclAccess>Read,Write</setAclAccess>
                <setAclResourceType>Directory</setAclResourceType>
                <AdditionalProviderSettings>setAclResourceType;setAclAccess</AdditionalProviderSettings>
            </MsDeploySourceManifest>
            <MsDeploySourceManifest Include="setAcl">
                <Path>$(_MSDeployDirPath_FullPath)\Assets\Uploads\SecondFolder</Path>
                <setAclUser>NETWORK SERVICE</setAclUser>
                <setAclAccess>Read,Write</setAclAccess>
                <setAclResourceType>Directory</setAclResourceType>
                <AdditionalProviderSettings>setAclUser;setAclResourceType;setAclAccess</AdditionalProviderSettings>
            </MsDeploySourceManifest>
        </ItemGroup>
    </Target>
    <Target Name="DeclareCustomParameters" AfterTargets="AddIisAndContentDeclareParametersItems">
        <ItemGroup>
            <MsDeployDeclareParameters Include="FirstFolderSetAclParam">
                <Kind>ProviderPath</Kind>
                <Scope>setAcl</Scope>
                <Match>^$(_EscapeRegEx_MSDeployDirPath)\\Assets\\Uploads\\FirstFolder$</Match>
                <Description>Add write permission to the FirstFolder.</Description>
                <DefaultValue>{$(_MsDeployParameterNameForContentPath)}/Assets/Uploads/FirstFolder</DefaultValue>
                <Value>$(_DestinationContentPath)/Assets/Uploads/FirstFolder</Value>
                <Tags>Hidden</Tags>
                <Priority>$(VsSetAclPriority)</Priority>
                <ExcludeFromSetParameter>True</ExcludeFromSetParameter>
            </MsDeployDeclareParameters>
            <MsDeployDeclareParameters Include="SecondFolderSetAclParam">
                <Kind>ProviderPath</Kind>
                <Scope>setAcl</Scope>
                <Match>^$(_EscapeRegEx_MSDeployDirPath)\\Assets\\Uploads\\SecondFolderFuelBills$</Match>
                <Description>Add write permission to the SecondFolder.</Description>
                <DefaultValue>{$(_MsDeployParameterNameForContentPath)}/Assets/Uploads/SecondFolder</DefaultValue>
                <Value>$(_DestinationContentPath)/Assets/Uploads/SecondFolder</Value>
                <Tags>Hidden</Tags>
                <Priority>$(VsSetAclPriority)</Priority>
                <ExcludeFromSetParameter>True</ExcludeFromSetParameter>
            </MsDeployDeclareParameters>
        </ItemGroup>
    </Target>
</Project>

I am publishing to a network file share, so perhaps that is something as all the examples I can find (not many) are concerned with IIS.
How to get Network Service writing to those directories? Do I need to explicitly add something in the project properties?
Richard


text:
Q: Webservices: Should returning or passing enums be avoided? I have a .net webservice that services data updates to client applications. As part of the mechanism, we used an enum to differentiate between 'types' of updates. So the webmethod returns a list of types that have an enum to define what the update is for.
We recently added an additional 'update type' to the system. While this worked fine for the new version of our client application (also in .net), older versions threw errors as the new enum type (which is serialized as a string and passed down the wire) could not be cast to the enum (as the enum value isn't specified in the generated code in Reference.cs).
Our answer is to avoid including that new value in the webmethod's result (to satisfy the older versions of the client app) and use a new method for here on that instead passes the INT value of the enum to client applications.
In terms of backward compatibility and robustness, is it a good idea to even pass Enum values when dealing with webservices? We just had a new value to account for, but I'm thinking in terms of refactoring/renaming enums for the future.
Defining the rule "Don't pass enum values over webmethods. Pass their INT values instead" seems like a really broad rule so I'm not certain of the unintended consequences when supporting older versions of client applications.

A: I think there is nothing wrong with passing an enum around. When the result is serialized as XML using XSD there is even a specific element to define enums (xs:enumeration).
I had like to see the actual problems with the older client software to have a better idea of the problem, but when talking standards, this should work.


text:
Q: How to put a UISegmentedControl under a NavigationController? I was wondering what the best approach in order to have a UISegmentedControl appears just under the a navigationController just like in the AppStore application:

The content I what to put in the different views are UITableView just like the AppStore app.
What I was thinking so far was:

*

*a viewController with the UIToolbar with
UISegmentedController

*in this ViewController attaching my UITableViews

But what I can't figure out, is how to structure my controller source code files.
Do you have best practice, working examples or at least advices?

A: I would use UITableView's tableHeaderView property for that. That way it will scroll together with the table view's contents.
To prevent the bar from scrolling together with the table content, I would make it a sibling view (relative to UITableView) and place it just above the table view. If you choose this approach you will have the following view hierarchy: controller's view holds the toolbar and the table view. Note that you will have to set up the table view and handle row deselection in -viewWillAppear: yourself, duplicating functionality of UITableViewController.


text:
Q: openconnect - I can ping a website but can't wget or access by browser I need to access the VPN of my university. On their website they provide the following solution:

*

*install openconnect

*install vpnc

*login to vpn via:
# openconnect --script /etc/vpnc/vpnc-script vpn.example-university.edu

*Enter credentials

Everything works fine, I can successfully login and stay connected. Now there is something weird going on: I can ping websites but can't access them neither via webbrowser nor wget.
The script changes my resolv.conf and adds one domain (university domain) and one nameserver (university ip) to it. I do not have any iptable configuration (All policies are ACCEPT).
On Ubuntu it just worked fine, but now I am using arch linux.


text:
Q: React - Test if conditionally rendered elements in component are rendered when state changes with Jest and Enzyme I have a ReactElement in my component which is rendered if a state attribute is set. Now I would like to test that behaviour by setting the state inside of my test and check if the element has been rendered afterwards. If I update the state by using setState({key: object}) on the mounted wrapper, its seems like it has no effect on my component although the state of the wrapper has been updated. Am I  doing the state update at the wrong place?
MyComponent.tsx
class MyCompoonent extends React.Component {
    ...
    render() {
        ....
        // Render
 if state is set
        {this.state.myObject && (
Test me
)}
    }
}

MyTest.tsx
...
it('should render div if state is set', () => {

    // Create fake object
    const fakeObject: FakeObjectType = { name: "fake" };

    // Mount component
    const wrapper = mount(<Component />);

    // Update state
    wrapper.setState({
        myObject: fakeObject
    }, () => {

        // Prints fakeObject as part of state
        console.log(wrapper.state());

        // I don´t think I need that?!
        wrapper.update();

        // Wrapper has not been rerendered,
        //
 is still not part of the printed output
        console.log(wrapper.debug());

        // Test failes ;(
        expect(wrapper.containsMatchingElement(
Test me
)).toBeTruthy();
    }
});


text:
Q: 'this' referring to something inside function instead of the object (jQuery) I have the following class:

function courseOversight() {
  this.courseBlocks = []; // Stores the courseblocks on the page
  this.getCourseBlocks = function() {
    $(".course-block").each(function(){
      var block = new courseBlock();
      this.courseBlocks.push(block);
    });
  }
}

As you can see, I'm trying to fill in the object's courseBlocks array with the courseBlocks on the page. However, in the each() loop, 'this' refers to the course-block I'm currently adding, and not to the courseOversight object. How would I access the courseOversights courseBlocks array without using the now unavailable 'this' keyword? Thanks!

A: You can solve this by assigning 'this' to a variable before you enter the each like the following
function courseOversight() {
var _this = this; //Assign 'this' context to a new var
this.courseBlocks = []; // Stores the courseblocks on the page
this.getCourseBlocks = function() {
    $(".course-block").each(function(){
        var block = new courseBlock();
        // Now you can call the following like this.
        // _this.courseBlocks.push(block);
        this.courseBlocks.push(block);
    });
}
}

A: You may save this to another variable (p.e. self)

function courseBlock(){
}

function courseOversight() {
  var self = this;
  self.courseBlocks = []; // Stores the courseblocks on the page
  self.getCourseBlocks = function() {
    $(".course-block").each(function(){
      var block = new courseBlock();
      self.courseBlocks.push(block);
    });
  }
  self.getCourseBlocks();
  console.log("Tests: ", self.courseBlocks);
}
courseOversight();

Block 1

Block 2

Block 3