text:
Q: Reports API access for Google Admin First, I have admin privilege on my domain but I do not have access to security.  I am working with my I.T. department, which does have security access, however, everything we've found seems to be enabled on our account.  App access control is set to "Trust internal, domain-owned apps".  Every time I try to run just the basic quickstart for UserUsageReport (https://developers.google.com/apps-script/advanced/admin-sdk-reports#reference) I get an error:
/**
 * Generates a user usage report for this day last week as a spreadsheet. The
 * report includes the date, user, last login time, number of emails received,
 * and number of drive files created.
 */
function generateUserUsageReport() {
  var today = new Date();
  var oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
  var timezone = Session.getScriptTimeZone();
  var date = Utilities.formatDate(oneWeekAgo, timezone, 'yyyy-MM-dd');

  var parameters = [
    'accounts:last_login_time',
    'gmail:num_emails_received',
    'drive:num_items_created'
  ];
  var rows = [];
  var pageToken;
  var page;
  do {
    page = AdminReports.UserUsageReport.get('all', date, {
      parameters: parameters.join(','),
      maxResults: 500,
      pageToken: pageToken
    });
    if (page.warnings) {
      for (var i = 0; i < page.warnings.length; i++) {
        var warning = page.warnings[i];
        Logger.log(warning.message);
      }
    }
    var reports = page.usageReports;
    if (reports) {
      for (var i = 0; i < reports.length; i++) {
        var report = reports[i];
        var parameterValues = getParameterValues(report.parameters);
        var row = [
          report.date,
          report.entity.userEmail,
          parameterValues['accounts:last_login_time'],
          parameterValues['gmail:num_emails_received'],
          parameterValues['drive:num_items_created']
        ];
        rows.push(row);
      }
    }
    pageToken = page.nextPageToken;
  } while (pageToken);

  if (rows.length > 0) {
    var spreadsheet = SpreadsheetApp.create('G Suite User Usage Report');
    var sheet = spreadsheet.getActiveSheet();

    // Append the headers.
    var headers = ['Date', 'User', 'Last Login', 'Num Emails Received',
      'Num Drive Files Created'];
    sheet.appendRow(headers);

    // Append the results.
    sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);

    Logger.log('Report spreadsheet created: %s', spreadsheet.getUrl());
  } else {
    Logger.log('No results returned.');
  }
}

/**
 * Gets a map of parameter names to values from an array of parameter objects.
 * @param {Array} parameters An array of parameter objects.
 * @return {Object} A map from parameter names to their values.
 */
function getParameterValues(parameters) {
  return parameters.reduce(function(result, parameter) {
    var name = parameter.name;
    var value;
    if (parameter.intValue !== undefined) {
      value = parameter.intValue;
    } else if (parameter.stringValue !== undefined) {
      value = parameter.stringValue;
    } else if (parameter.datetimeValue !== undefined) {
      value = new Date(parameter.datetimeValue);
    } else if (parameter.boolValue !== undefined) {
      value = parameter.boolValue;
    }
    result[name] = value;
    return result;
  }, {});
}

The error I am getting is:
GoogleJsonResponseException: API call to reports.userUsageReport.get failed with error: Caller does not have access to the customers reporting data.

I meet the three requirements of the above link, as far as I can tell, which are:
API access enabled
Google account with admin privileges
Access to Google Drive
So why do I keep getting this error?  Is there a setting that my I.T. is missing to enable this?  I have complete access to directory_v1 but reports_v1 gives me the same error every time I try to call it.  We've even followed the instructions here: https://support.google.com/a/answer/7281227?visit_id=637781417279518974-3468793296&rd=1#zippy=%2Creview-the-third-party-apps-in-your-environment%2Cblock-all-third-party-api-access
Any help is appreciated.

A: *

*Definitely try calling the same method in API explorer as mentioned by @Fernando Lara to investigate user permissions and rule-out any session issues as well.

*In addition to that make sure the caller of this script has Reports Admin privilege enabled as stated on this documentation.

*One scenario you might encounter is regarding the "scopes cache/caller" on your script project. Since the Apps Scripts editor automatically controls the authorization scopes given the code context, I've noticed that sometimes when you modify domain-level permissions, some kind of scope cache is retained in the project. To workaround that, I just cut my code to a notepad, add a blank function calling DriveApp.getFiles();, save my project and run this method. Re-authorize the Drive scope, let it finish then delete everything and paste your code again and run it to trigger the OAuth flow once again.

A: I think the problem could be related to the specific admin roles that your account may have. Since you mention that you do not have access to the Security section of the Admin console, this means you are not a super admin and just have specific admin roles assigned to your account.
I would recommend making a test using the "Try this API" function from the API explorer first, just to discard the admin roles issue. If it fails with the same error it means the problem is related to the admin roles. Or you can just ask if your user has the Reports admin role assigned.


text:
Q: Shifting after dynamically adding a point creates a space in chart So I'm using Highcharts to plot data from real time every 1 second. After 40 points being added to the chart I start shifting the points. The problem is that I have more than one series in the chart and when it start to shift it creates a weird space in from of all series except the first one..

As you can see on the red doesnt start in the same place of the blue one.
    setLiveDataPoint: function(data){
        var graph = this;
        var num = graph.yAxis.length; // Number of Y axis (Field, Quality)
        var yAxis = graph.yAxis;

        for(var i = 0; i < num; i++){
            var xFieldId = "time"; // defaults to time
            var serie = graph.highchartObj.get(yAxis[i].id);
            var x = parseInt(data[xFieldId][data.records - 1]);
            var y = data[yAxis[i].id][data.records - 1];
            var shift;
            if(graph.pointsOnGraph == 40){
                shift = true;
            } else {
                shift = false;
                if(i == 0){
                    graph.pointsOnGraph += 1;
                }
            }
            serie.addPoint({
                x: x,
                y: y
            }, true, shift);
        }

        return graph;

When I make a call have every data in the same json response, then I loop for the yAxis to plot the point in the chart..

redpajama_set_name: RedPajamaStackExchange


text:
Q: "just married" or "just wed"? I saw this for the first time in something recent: "just wed".
I wonder how and when it is used (BrE only, under certain conditions). Does it mean exactly the same as "married"?

A: Both "just married" and "just wed" mean the same thing.
In my experience, I have seen "just married" more than "just wed." A Google Ngram confirms the usage of just married as more frequent:

Perhaps the shorter phrase was used to fit on the license plate.
You will also see "newlyweds" to refer to people who have just been married.

A: It's just one of those English things where there's a choice between Saxon-German or Norman-Latin words.
Wed is Germanic, meaning to wager/bet/promise; to marry comes from the Latin.

A: They mean the same thing.

Just wed

Sounds better, in my opinion.


text:
Q: jQuery: some keys of objects cannot be accessed Using jQuery, I have loaded some data to an object defined by var tmp={}.
Somehow the data will be displayed by console.dir(tmp), but I cannot get some values by accessing it directly (e.g. tmp.val)!
The object I am storing data to is called tmp in the following example. Unfortunately, I cannot present the complete code how the data is gathered since it is too much.  What I can present is the output.
console.log(tmp)

$.each(tmp,function(key,val){
    console.log(key);
});

The fist line will display:
Object
  class: "modul7"
  class_name: "Some kind of class name."
  collectionRelevant: 1

The second code will display:
class
class_name

The collectionRelevant is missing.
I know my question is vague.
Has anyone stumbled over something like this? I have no clue anymore in which direction to seek the error.

A: I think native JavaScript should be enough for this task.
for( var key in tmp ) {
  // key
  console.log(key);
  // value
  console.log(tmp[key]);
}


text:
Q: Topology with a strange distance We define the distance in the plane $\mathbb{R}^2$
$$\rho((x_1,y_1),(x_2,y_2)) =\begin{cases}
|y_1-y_2| & \text{if } x_1=x_2 \\
|y_1|+|x_1-x_2|+|y_2| & \text{if not}
\end{cases}$$
. I want to determine what are the open sets in the topology of $\mathbb{R}^2$ associated with this distance. I'm really stuck with this question, because I don't know how to separate in cases to find the open sets. I think that the points in the $x$-axis must be important, but I don't understand how.

A: This is usually called the river metric. In my Dutch intro to metric spaces we called it the "Amazone-metriek" on the plane.
Image the plane really being a "forest" with a river : the $x$-axis, and there are "paths" orthogonal to that river.
If you want to move from $(x,y)$ to $(u,v)$, two things can be the case: you're on the same path, so $x = u$, then we can just move along the path like we're in the reals, and the distance becomes $|y-v|$. If not, we go down to the river (starting from $x$ this is distance $|y|$), then travel to the other point's path via the river so that's distance $|x-u|$ and then go up or down the path to $(u,v)$, distance $|v|$. So we get the distance $|y| + |v| + |x-u|$ in total.
This means that for a point away from the river, say with $y$-coordinate $|y|> 0$, a small ball around it will only be able to "see" vertical points. On the river, we can always see some points close to it in other "paths".
Draw some pictures to build your intuition. It's all about what "small" balls looks like to get a grip on what neighbourhoods of a point are.

A: You should remember that an open set of a topology derived from a metric is a union of open balls. And that if a ball is an element in a topology $T$ then the topology $T_\rho$ is contained in $T$.


text:
Q: apache superset http://localhost:5000/chart/add not rendering I have cloned apache superset brach 1.4.0 and running dev-server. Everything is working fine except chart add section.
While navigating to http://localhost:5000/chart/add not getting blank page and not rendering page at all except logo and header part.


text:
Q: Как присвоить переменной со второго по пятый символ заданной строки? Присвойте переменной x значение строки из символов со второй по пятый из строки txt.
Нужно присвоить переменной x символы со второго по пятый из строки txt.
txt = "Hello world"
x = #???

Нужно подставить что-то, чтобы программа работала.

A: Для начала поговорим об индексах. Индекс - номер определённого элемента в какой-либо последовательности. Строка - тоже последовательность, значит у каждой буквы в ней есть свой номер - индекс. Понятное дело, отсчёт начинается с 0.
s = "Аянами Рей!"
print(s[0])
# Вывод: А
print(s[1])
# Вывод: я

Помимо того, что вы можете хотеть выбрать какой-то элемент последовательности, вы также можете хотеть выбрать сразу несколько элементов.
В данном случае вам помогут срезы.
Срезы - это инструмент, с помощью которого вы можете обрезать какую-либо последовательность, оставляя лишь некоторые её элементы.
Синтаксис: [первый_индекс:последний_индекс:шаг]
Например, вы можете срезать первые два символа.
s = "Аянами Рей!"
print(s[2:])
# Вывод: нами Рей!
# в данном случае 'н' имеет индекс 2, поэтому с него начинается строка

Или оставить только их.
s = "Аянами Рей!"
print(s[:2])
# Вывод: Ая
# т.е. убираются все буквы со второй до самого конца

Или срезать последние два.
s = "Аянами Рей!"
print(s[:-2])
# Вывод: Аянами Ре
# т.е. остаются все буквы, кроме последних двух

А можно обрезать сразу со второго по пятый, то что вам и нужно.
s = "Аянами Рей!"
x = s[2:5]
print(x)
# Вывод: нам
# т.е. 2, 3 и 4 символ по счёту

Подробнее можно посмотреть тут или по запросу в гугл "срезы python"


text:
Q: Does the use of `is` in a when expression over a sealed class result in reflection at runtime? In Java, if I have a class hierarchy like so:
private interface Foo { }

private class FooBar implements Foo { }

private class FooZoo implements Foo { }

And then I have a function like so:
public int Return0IfFooBarElseIfFooZooReturn1ElseReturn2(Foo foo) {
    if (foo instanceof FooBar) {
        return 0;
    } else if (foo instanceof FooZoo) {
        return 1;
    } else {
        return 2;
    }
}

At run time, reflection will be used to determine the type of foo. In an ideal world, we would like to avoid having our code use reflection. In addition, as far as I know, there is no way to create a sealed type hierarchy in Java, meaning you will always need to provide an else branch to have the code compile.
However in Kotlin you can create a sealed type hierarchy, like so:
sealed class Foo {
  object FooBar : Foo()
  object FooZoo : Foo()
}

And you can then write a when expression to switch on the type and return a value like so:
fun return0IfFooBarElseReturn1(foo: Foo) = when (foo) {
  is Foo.FooBar -> 0
  is Foo.FooZoo -> 1
}

There is an interesting property about this; namely, there is no need for an else, because the when expression is exhaustively checking the sealed type hierarchy. So, from this property, can the compiler derive enough information in order to compile bytecode which somehow is not going to use reflection at runtime to determine if the passed instance is of a given type?
Or in other words, is there any difference (with regards to reflection) at run time between the Kotlin code above, and the Kotlin code below:
interface Foo

class FooBar : Foo { }

class FooZoo : Foo { }

fun return0IfFooBarElseReturn1(foo: Foo) = when (foo) {
    is FooBar -> 0
    else -> 1
}

I am asking this, because generally as programmers, we would like to avoid reflection (where possible), but the official Kotlin docs for sealed classes show an example of switching on an instance using is (https://kotlinlang.org/docs/reference/sealed-classes.html). I also do this a fair bit in the code I do at work, and whilst I don't really see any issue with doing it, some co-workers have voiced concerns as it looks like a code smell.

A: Whatever the compiler does behind the scenes is irrelevant to whether this is good practice. Reflection is code smell when you're using it to micromanage the behavior of objects which could otherwise be taking care of their own behavior through polymorphism.
In the case of sealed classes, you are working with a finite set of classes, so micromanaging their behavior is less arduous, but in my opinion is still a smell if you're doing it outside the file that defines them.
Here's an interesting article about when it makes sense to rely on reflection rather than polymorphism. The TLDR:

Polymorphism only makes sense when the polymorphic behavior is really a behavior of the target. When it's the behavior of the observer, you need runtime typing.

So if your when statement is asking each object to do something or calculate something, it is likely a situation where polymorphism should be preferred. If your when statement is doing something to the objects or needs to sort them in some specific way, the reflection may be more appropriate.
One area where I think it makes sense to use sealed classes in when they are the return value of something that parses a file or something from the Web. Unlike the Expr example where everything can evaluate to a Double, when you read from some unpredictable file, the return value may have an unpredictable type. You might want to sort the return value into a specific handler. Or the return value might be an error that you handle differently than a valid value.
You can also use sealed classes as a better alternative to checked exceptions. By wrapping a result in a class that can be a valid result holder or an error, you force the caller to handle errors if it needs to, or it can bubble them up without the function signature having to know anything about the types of errors it might encounter. Then at whatever level needs to handle the error, it can be unpacked with a when statement.


text:
Q: NSMutableArray initialization I'm very newby on Objective C. I've read a lot of topics related but couldn't get solution.
I'm using a NSMutableArray, and alloc and init by the following mode:
events = [[NSMutableSet alloc] init];

Is it right? In this way, I can add objects to the array without problems, but when I iterate or to read, I got SIGABRT: unrecognized selector sent to instance. Attempting several modifications, the best I could get was another exception: EXC_BAD_ADDRESS. The line I'm using to read the array is:
Event *event = [events objectAtIndex:1];

Thanks in advance.
Junior

A: you have said you are using NSMutableArrays, but then initialised a set, try using:
NSMutableArray *events = [[NSMutableArray alloc] init];

sets don't respond to objectAtIndex, because they are unordered. if you want an object out of a set, you can call anyObject on it. or you can use enumeration to go through all objects.
eg
id obj=[events anyObject];

or
for(id obj in events){
    NSLog(@"%@",obj);
}

A: What's going on in between? Remember that arrays are zero-indexed; there may not be two elements in there. Try using the count method.

A: events = [[NSMutableArray alloc] init];
[events addObject:event1];
[events addObject:event2]

for (int i = 0; i < [events count]; i++) {
    Event *event = (Event)[events objectAtIndex:i];
    NSLog("Event: %@", event);
    [event release];
}

Like this.


text:
Q: How to center image on mobile while doing it on desktop? I am making a welcome page.
I have this image that seems centered on desktop.
Desktop view:

However, the mobile view is horrible:
Mobile view:

So.. we can see the image is not centered correctly. Now, I could fix this with hacks but hacks just rob me from learning the proper way to do it.
How can I center the image on mobile and desktop?
My code: (profits.png needs to be centered)

Welcome to example

follow up

 Type your username

    <input type="text" placeholder="Type a username" style="font-size: 30px; text-align: center;" align="center">
    <button id="playbutton">Play</button>

Why us?

comming soon

...

A: You need use data-at2x for making Images as responsive in web site
EXAMPLE
.

And also change image size, height, width according to Mobile screen.

A: The problem is you have a fixed width in your img.. thats why your margin: 0 auto; is not working properly.. try changing it to percentage. or use media queries and set the width accordingly to the mobile size..
look at this..


text:
Q: Is it possible to foward declare a function or method in Javascript? JSHint is telling me that my methods are not recognized if they are not defined before they are used.
I can try to re-arrange all my methods in order but I'm hoping there is a way to aboid the warnings by "forward declaring" the methods.
I'm not too sure what the correct name is but I want the interpreter to know that these functions exist further on down in the code.
Full report here - http://www.jshint.com/reports/67008
Thanks

A:
I want the interpreter to know that these functions exist further on down in the code.

The interpreter does know that these functions exist further down in the code. The code should run with no problems. It is only jshint that doesn't like it.
There is nothing wrong with declaring your functions in the order that you find useful and meaningful, for example it is normal (and helpful) to declare related functions near each other. Personally, I find it helpful to declare page initialisation type functions at the top of my script, even though they will inevitably call other functions that are declared later.
If you introduced some kind of "pre-declaration" to your code I would think that'd make your code harder to read and maintain, because obviously then you've got to match up the pre-declarations with the real declarations even though they will be spaced far apart in the code. When you come back the next week and change your functions you have to remember to update both parts of the code. Which means you're more likely to introduce inconsistencies and bugs.
So, given that the point of jshint is to make your code more reliable, surely you don't want to add some artificial construct just to pass jshint even though that would make the code less reliable in the long run?
The only restructuring you should consider to avoid that warning is re-ordering the functions, but in my opinion you're better off ignoring the warning in this case. (Is there an option to turn the warning off?)

A: I think all you can do is set undef:false, which leads to other issues.
You may need to ignore it, restructure, or run it with the assumption a file containing the functions will be loaded before the code that calls them.


text:
Q: How to display all images "Uploaded By" an author I have multiple users, that have the ability to upload media. When I look at the media library it shows the file information, and included at the bottom is an "Uploaded By 'username'"
How can I use this username to loop through the media library and display all images from a user?
Here's a picture of the information with the media.

A: You can do it via WP_Query loop:
$args = array(
   'author'      => $author_id, // Replace with author id
   'post_status' => 'any',
   'post_type'   => 'attachment'
);
$query = new WP_Query( $args );

More info how to use WP_Query: Codex WP Query


text:
Q: Swift code in Object-C: No visible @interface for 'ClassName' declares the selector 'alloc' I'm trying to use a swift class inside Objective-C code.
 ThisClass *thisClass = [[ThisClass alloc] init];

However, when trying to allocate and initialize that class, I get this error:

No visible @interface for 'ThisClass' declares the selector 'alloc'

Class is declared as such in the Swift file:
@objc class ThisClass : NSObject {

The class inherits from NSObject, so I don't know what its problem is.
Here is my class inside my ProjectName-swift.h:
SWIFT_CLASS("_TtC21ProductName16ClassName")
@interface ThisClass : NSObject
@property (nonatomic, copy) NSArray<Presentation *> * __nonnull presentations;
@property (nonatomic, copy) NSArray<Presentation *> * __nonnull userPresentations;
@property (nonatomic, strong) NSCache * __nonnull imageCache;
- (UIImage * __nullable)imageForPresentationSlideWithPresentation:(Presentation * __nonnull)presentation slideNumber:(NSInteger)slideNumber;
- (UIImage * __nullable)thumbnailForPresentationSlideWithPresentation:(Presentation * __nonnull)presentation slideNumber:(NSInteger)slideNumber;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

A: The problem is that in your real code (as opposed to what you are showing here) you have capitalized the name of your variable PresentationData. But this is already the name of the class. That sort of thing drives the compiler nuts (and is not good for readers of your code either - variable names should always start with a small letter).


text:
Q: Splitting a Dataset into Multiples based on a row separator Suppose I have a dataset like the following

with some rows containing nothing but dashes.
Question: Is there a way to split this dataset into multiple datasets (with the same headers) at the "dash" points?  In this particular example, there would be 3 datasets (the first one containing 2 rows, the second one containing 3 rows, and the third one containing 1 row), each with the labels "Name", "Duration", and "Notes".

A: If we have
ds = Dataset[{
   <|"a" -> 1, "b" -> 2|>,
   <|"a" -> 1, "b" -> 2|>,
   <|"a" -> 1, "b" -> 2|>,
   <|"a" -> "-----", "b" -> "-----"|>,
   <|"a" -> 1, "b" -> 2|>,
   <|"a" -> 1, "b" -> 2|>,
   <|"a" -> "-----", "b" -> "-----"|>,
   <|"a" -> 1, "b" -> 2|>
   }]

(obviously replace with your own dataset)
We can do the following:
Dataset /@
 Select[SplitBy[Normal[ds], #a != "-----" &],
  First[#]["a"] != "-----" &]

It's a bit rough, but easily extended to be a bit more graceful.
First, we change the dataset into a list of associations, using Normal[ds]. Then we split that list using SplitBy to get successive runs of rows in the dataset that don't have "a" -> "-----" (You may want to be a bit more specific with this predicate depending on your dataset). Then, we select only the sublists that aren't the "separator" sublists with Select[..., First[#]["a"] != "-----"&]. Then we simply turn the resulting lists back into Datasets.


text:
Q: Load Assembly in AppDomain and Invoke Entry Point I'm having the hardest time with this. I've googled for hours, and been to many different questions on here, but I just can't get it.
static void Main(string[] args)
{
    AppDomainSetup domainSetup = new AppDomainSetup { PrivateBinPath = typeof(Program).Assembly.Location };
    AppDomain domain = AppDomain.CreateDomain("TempDomain", null, domainSetup);
    InstanceProxy proxy = domain.CreateInstanceFromAndUnwrap(typeof(Program).Assembly.Location, typeof(InstanceProxy).ToString()) as InstanceProxy;
    if (proxy != null)
    {
        proxy.LoadAssembly(Properties.Resources.mfX3DAu);
    }
    AppDomain.Unload(domain);
    Console.Read();
}

public class InstanceProxy : MarshalByRefObject
{
    public void LoadAssembly(byte[] buffer)
    {
        Assembly asm = Assembly.Load(buffer);
        asm.EntryPoint.Invoke(null, null);
    }
}

The resource "mfX3DAu" is a .Net Assembly obfuscated with Confuser.
It loads fine, and it is in the new AppDomain, but every time I try and invoke it I get

An unhandled exception of type 'System.ExecutionEngineException' occurred

Someone I talked to before said they got it working with this specific assembly, so it must be possible.

A: I think you need this its in VB.NET look for yourself how to wrap it into c#
Try
    Dim myWebClient As New WebClient()
    Dim a As System.Reflection.Assembly = System.Reflection.Assembly.Load(myWebClient.DownloadData("http://..."))
    Dim method As System.Reflection.MethodInfo = a.EntryPoint
    Dim o As Object = a.CreateInstance(method.Name)
    method.Invoke(o, New Object() {New String() {"1"}})
Catch ex As Exception
    MsgBox(ex.Message.ToString)
End Try

A: In .Net world, there is no DLL Main method which would get called whenever the assembly is loaded into an application domain. .Net however supports Module Initializers. Module Initializers are global functions, C# does not support global functions and thus Module Initializers cannot be defined and used using C# language. CLR supports Module Initializers and IL Code (OpCodes) can be used to write Module Initializers.
For more information, please refer to following link: Module Initializers


text:
Q: parse String color without java i have a code like this :
String hex = String.format("0x%02x%02x%02x", r * 0.5, green * 0.6, blue * 0.7));

0.5 and 0.6 and 0.7 are variables
and i want to set background color of a view from variable hex :
v.setBackgroundColor(Integer.parseInt(hex, 16));

When i try to convert it to Hexadecimal integer it throws exceptions like
java.lang.NumberFormatException

how can i do this?

A: 0x causes NumberFormatException. try Integer.decode instead:
v.setBackgroundColor(Integer.decode(hex));

Read:

*

*https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#decode(java.lang.String)

A: There are potentially three problems with this code:

*

*As @shiftpsh notes: Integer.parseInt does not understand the 0x prefix.  There are two ways to solve this:

*

*Use Integer.decode rather that Integer.parseInt.

*Don't include the 0x prefix in the format.

*The second potential problem is that %02x means hexadecimal, zero-padded with a minimum of two digits.  But if any of r, green or blue were large enough, the resulting color value would be greater than 255, and you would get more than 2 hex digits.  That would result in an incorrect RGB value when the string is decoded.

*I am rather surprised that %02x works for an argument like r * 0.5.  The latter is a double and according to my reading of the javadoc the x conversion is not applicable.

However, if the sole point of this code is to create and RGB value from r, green and blue, there is a significantly more efficient way to do it.
 int r0 = ((int)(r * 0.5)) & 0xff;
 int g0 = ((int)(green * 0.6)) & 0xff;
 int b0 = ((int)(blue * 0.7)) & 0xff;
 v.setBackgroundColor((r0 << 16) | (g0 << 8) | b0);

Alternatively, using android.graphics.Color.argb to do the RGB conversion should be just as efficient .... though that is an Android API rather than a Java API.  (I could not find a directly equivalent Java SE library method that is as efficient.)


text:
Q: trying to understand LSH through the sample python code the concise python code i study for is here
Question A @ line 8
i do not really understand the syntax meaning for "res = res << 1" for the purpose of "get_signature"
Question B @ line 49 (SOLVED BY myself through another Q&A)
"xor = r1^r2" does not really make any sense to me, which the author later tried "(d-nna(vor))" to calculate "hash_sim" -- (refer to line 50)
Question C @ about hash_sim in general
that question is more to do with LSH understanding, what variable "d" (line 38) is doing in the sample code ---- which is later used to calculate hash_sim in line 50
Question D @ line 20 and 24 -- synatx for "&"
not only having problem in understand the syntax "num = num & (num-1)", but also unsure what function "nnz" is doing in the context of hash_similarlity. this question may relate to my question (-b-) when the author apply the "xor" into "nnz", and again equation for "xor" (question b) looks odd to me.
p.s.
both my python and LSH understanding are at the beginner level, and I kind of entering in the loop for this problem. thanks for taking your time to going through my confusion as well as the codes

A: a. It's a left shift: https://docs.python.org/2/reference/expressions.html#shifting-operations It shifts the bits one to the left.
b. Note that ^ is not the "to the power of" but "bitwise XOR" in Python.
c. As the comment states: it defines "number of bits per signature" as 2**10 → 1024
d. The lines calculate the bitwise AND of num and num + 1.
   The purpose of the function is documented in the comment above:
   "# get number of '1's in binary"


text:
Q: Merge two .m4a files or convert .wav file to m4a I was looking for a way to record in mpeg-4 with the ability to pause and resume but it seemed like there isn't one. So I decided to record in raw wave format and convert to .m4a. Is there a way I can convert .wav file to .m4a in android. I've looked around for mencoder port for android but found none, there were some post's about porting ffmpeg to android on linux but its not quite clear how i can use it in android to merge two .m4a files or convert .wav file to .m4a.

A: There are two possible things you could mean by "merging" the audio files, and two different ways to go about it using ffmpeg:
Putting two separate audio tracks into the same file
Like on a DVD where there's a normal audio track, and another audio track like commentary or a dubbed language.  To do this with ffmpeg and two m4a files, use the command ffmpeg -i in-1.m4a -acodec copy out.m4a -i in-2.m4a -acodec copy -newaudio.  The order of options is important, so don't mess with it.
Concatenating two audio files
Making the second file play immediately after the first.  The easiest way to do this is to use a program designed for audio manipulation like SoX.  It appears that there is a recent but unstable Android port of SoX.If you want to do the concatenation strictly in ffmpeg, then you can do the following:

*

*ffmpeg -i in-1.m4a -f s16le in-1.rawThis outputs the audio file to raw PCM.  You need to pay attention to the sampling rate and the number of channels, because this information will not be stored in the raw PCM file and you will need it later.  ffmpeg will show you the audio stream information as it is re-encoding.  It will look something like Audio: aac, 44100 Hz, stereo, s16, 63 kb/s, which means that your sampling rate is 44100 and your number of channels is 2 (stereo).  Most often, you will be dealing with a sampling rate of 22050, 44100 or 48000; and 1 ("mono"), 2 ("stereo"), or 6 ("5.1") channels.

*ffmpeg -i in-2.m4a -f s16le in-1.rawNow decode the second file to raw PCM.

*ffmpeg -f s16le -ar 44100 -ac 2 -i 'concat:in-1.raw|in-2.raw' -acodec libfaac out.m4aAgain, order of options is very important.  Change the sampling rate (-ar) and channels (-ac) options as appropriate for your input.

A: Assuming that you build ffmpeg with the relevant formats and codecs, converting wav to m4a is as simple as:
ffmpeg -i in.wav out.m4a

If you're doing audio work, you might have better luck with SoX.


text:
Q: Jade - Only output a property if defined? I've not doubt somebody will have covered this:
id="#{data.id}"

Output
<input id="undefined"> //if I haven't defined id

Desired
//If ID is undefined
<input>
//If ID is defined
<input id="someID">

A: You could simply code:
input(id= data.id)

When the id is undefined, a falsy value, Jade won't add the attribute to the tag. This feature is also useful when you are setting property attributes like checked or selected.
Another option is using the &attributes syntax:
- var attrs = data.id ? {id: data.id} : null;
input&attributes(attrs)

A: You can wrap your code within an if ... else statement so that you wrap up the case where your id is not defined:
id = data.id
if id === "undefined"
  input#someID
else
  input#id


text:
Q: Is there any way through which I can lock the XML file while I am writing into it using Delphi? I have a multiple processes which write into same XML file. I am using NativeXML library.
I want to lock my file while any process writes into it so that the data in file should not be overwitten.

A: When you create a file, create it with exclusive rights, or at least with write access sharing disabled, then write to it as needed. Nobody else will be able to open the file for writing until you close it first.
In fact, NativeXML already does exactly that when saving XML to a file via its SaveToFile() method.  It uses a TFileStream, and that is the default behavior of TFileSteam when creating a new file.
But, if you need more control over the access rights, then you can create your own TFileStream object so you can fill in its constructor parameters as needed.  Or create a THandleStream object that refers to a file handle that you create using Window's CreateFile() API directly.  Then you can have NativeXml write to that stream via its SaveToStream() method.


text:
Q: Promise in node I just started with node js and I'm in trouble in a procedure.
In my code, I get a list of items via json (array) and do a loop that list to see if there is a record in the database or not.
If there is no record in the database, I do an insert if there is I do an update.
The problem is that the system is going too fast over the query and does not wait for the result to see whether or not due to javascript asynchronously.
The need does he wait for the check query to return then continue and finally wait for the insert as well, for the insert must have the answer before continuing the loop "for".
The code would look like this:
var input = JSON.parse (req.param ('data'));
for (var i in input) {
   iCode var = input [i] .codeOSNum;
   qry = 'select count(*) as qtd from table where code = '+iCode; //need wait result from this query
   var connection = new sql.Connection(config);
   var request = new sql.Request(connection);
   request.query(qry, function(err, recordset) {
     if (recordset[0].qtd = 0) {
        //do stuff to insert like: 'insert into blablabla' and need wait return.
     } else {
        //do stuff to update.
     }
  }); //and finally go to next item from loop 'for' and repeat until the end os json array.
}

I use indicated promise, but do not know how to use. I am newbie and desperate.


text:
Q: Grails Query Result return This is mu Controller Query;
      Sql sqlStatement = new Sql(dataSource)
    def sqlString = ("SELECT DISTINCT DATE_FORMAT(doc_hdr_0.date_created,'%D %M %Y') AS 'X', Count(DATE_FORMAT(doc_hdr_0.date_created,'%D %M %Y')) AS 'Y'\n" +
            "FROM doccon.doc_hdr doc_hdr_0\n" +
            "GROUP BY DATE_FORMAT(doc_hdr_0.date_created,'%D %M %Y')")

    def returnList = []
    sqlStatement.eachRow(sqlString){
        returnList << it.toRowResult()
    }
    sqlStatement.close()
    [returnList:returnList]

Result
    [{X=12th September 2015, Y=3}, {X=14th September 2015, Y=1}, {X=15th September 2015, Y=2}, {X=16th September 2015, Y=16}, {X=8th September 2015, Y=2}] THIS WHAT I WANT WITHOUT = INSTED :
I want to change the = sign to : how can I do that?
when I change [returnList:returnList] to render returnList
the result is
[['X':'12th September 2015', 'Y':3], ['X':'14th September 2015', 'Y':1], ['X':'15th September 2015', 'Y':2], ['X':'16th September 2015', 'Y':16], ['X':'8th September 2015', 'Y':2]]
now the result is [[k,v]] strange


text:
Q: How does firestore read write and delete calculated? I am trying to analyze and optimize the number of Reads and Writes in my cloud Firestore Database.

*

*How Does Firestore calculate Reads and Writes?

*How much Reads does it cost when querying for a single document from a list of 10 documents from a collection?

A: Firestore calculates the reads and writes based on the number of documents returned.
Reads:
For example, If you read a document like this,
db.collection('users').doc(userId).get(); //it will cost you one read

Let's assume your user collection has 100 documents.
db.collection('users').get(); //it will cost you 100 reads

When you query the collection, the cost is calculated based on the number of documents returned by the query.
For example
db.collection('users').limit(50).get(); //it will cost you 50 reads
db.collection('users').where('age','<','20').get(); //assume you have only 3 users are below age 20, this will only cost you 3 reads.

Writes:
Writes are calculated based on the number of documents create and update operations.
For example,
db.collection('users').add(data); //one write
db.collection('users').doc(userId).update(data); //one write

Batch Operations:
When a batch operation is made, the cost is calculated based on the number of documents that are affected by the batch.
batch.set(docRef1, data1); //one wrire
batch.set(docRef2, data2); //one write
batch.set(docRef3, data3); //one write
batch.delete(docRef3); //one delete

In total this batch will cost 3 writes & one delete.


text:
Q: React: How to implement a function that collects table row data and pass that data to a state in another component In my react app, I have a button which when clicked I want that table row data to be collected and passed to a state in another component.
Basically i have two components. Table and the 2nd is Table Edit modal. I only want to manage one state and that is the state found in my Table Edit modal. I have an edit button on each row found in Table which i want it to pass that row data for it to be stored in the state found in `Table Edit modal``.
My code is not working. I'm getting an error that points to the Table component

'editEmployeeData' is not defined  no-undef

Table component
const EmployeeTable = (props) => {
  const employeesDetail = useSelector((state) => state.hr_data.employeesDetail);
  const modalState = useSelector((state) => state.hr_data.modalState);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getEmployeeData());
  }, [dispatch]);

  const classes = useStyles();

  const columns = [
      { name: "name", label: "Name" },
      { name: "phone_no", label: "Contact" },
      { name: "email", label: "Email" },
      { name: "department", label: "Department" },
      { name: "salary", label: "Salary" },
      { name: "date_employed", label: "Date Employed" },
      {
        name: "Actions",
        options: {
          filter: true,
          sort: false,
          empty: true,
          customBodyRender: (value, tableMeta, updateValue) => {
            const i = tableMeta.rowIndex;
            const data = this.employeesDetail;
            return (
              // OPEN MODAL
              <Fragment>
                <Tooltip title="Edit">
                  <EditIcon                        <==== EDIT BUTTON
                    color="action"
                    onClick={()=> editEmployeeData(   <==== EVENT THAT COLLECTS THE FIELDS DATA
                      data[i].id,
                      data[i].name,
                      data[i].phone_no,
                      data[i].email,
                      data[i].department,
                      data[i].job_title,
                      data[i].salary,
                      data[i].date_employed
                    )}
                  />
                </Tooltip>
              </Fragment>
            );
          },
        },
      },
  ];

  return (
    <div className={classes.root}>

      {/* EDIT EMPLOYEE MODAL */}
      <EditEmployeeModal
        toggleModal={() => dispatch(toggleModal())} // modal activate
        updateEmployeeData={() => dispatch(updateEmployeeData())}
        modalState={modalState} // boolean
        editEmployeeData={editEmployeeData}      <==== PASSING HERE
      />
    </div>
  );
};

export default EmployeeTable;

Edit Table data component/modal
class EditEmployeeModal extends Component {
  state = {
    id: "",
    name: "",
    phone_no: "",
    email: "",
    department: "",
    job_title: "",
    salary: "",
    date_employed: "",
  }

  editEmployeeData(       <==== NOT WORKING
    id,
    name,
    phone_no,
    email,
    department,
    job_title,
    salary,
    date_employed
  ) {
    this.setState({
      id,
      name,
      phone_no,
      email,
      department,
      job_title,
      salary,
      date_employed,
    });
    this.props.toggleModal();
  }
...
export default EditEmployeeModal;


text:
Q: Uploading data via a post method to a server Android Studio I'm trying to upload an image to a server via a POST request in android studio and I'm totally stuck. The console gives me no information that could indicate whats going wrong and when i click upload it just doesn't work.
Here's the code:
public class UploadActivity extends AppCompatActivity implements View.OnClickListener {
ImageView imageToUpload;
Button uploadButton;
EditText imageNameText;
ImageButton backButton;
private static final int RESULT_LOAD_IMAGE=1;
private static final String SERVER_ADDESS = "http://lukertestsite.000webhostapp.com/";      // address of my free 000webhost domain

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload_page);

    imageToUpload = (ImageView)findViewById(R.id.imageToUpload);
    uploadButton = (Button)findViewById(R.id.uploadImageButton);
    imageNameText = (EditText)findViewById(R.id.imageName);
    backButton = (ImageButton)findViewById(R.id.returnButton);

    // set a listener for each button that will pass this as the view, since this class implements listener
    imageToUpload.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.imageToUpload:
            Intent localImagesIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(localImagesIntent, RESULT_LOAD_IMAGE);

            break;
        case R.id.uploadImageButton:
            Bitmap pic = ((BitmapDrawable) imageToUpload.getDrawable()).getBitmap();        // grab the pic as a bitmap
            new UploadImage(pic,imageNameText.getText().toString()).execute();
            break;

        case R.id.returnButton:

            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RESULT_LOAD_IMAGE && resultCode==RESULT_OK && data!=null) {        // ensuring the gallery intent is what calls the method, and the result is ok and data is passed i.e. not null
        Uri selectedImage = data.getData();                             // making a uniform result (basically a pointer to the image)
        imageToUpload.setImageURI(selectedImage);           // set the image to upload display to the selected image.
    }
}

// asynch task to commiunicate with server in the background

private class UploadImage extends AsyncTask<Void,Void,Void>{
    Bitmap image;
    String name;

    public UploadImage(Bitmap image, String name){
        this.image=image;
        this.name=name;

    }

    @Override
    protected Void doInBackground(Void... voids) {
        // encode image in base 64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        image.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);    // compress as a png into bytearraystream
        String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);

        ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("image",encodedImage));
        dataToSend.add(new BasicNameValuePair("name",name));

        HttpParams httpRequestParams = getHttpRequestParams();
        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost(SERVER_ADDESS + "UploadPic.php");

        try{
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            System.out.println("set post entity");
            client.execute(post);
            System.out.println("executing post");
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Toast.makeText(getApplicationContext(),"Your pic was uploaded",Toast.LENGTH_SHORT);     //Toast to alert user their file was uploaded
        System.out.println("toasted");
    }
}

private HttpParams getHttpRequestParams(){

    System.out.println("getting request params");
    HttpParams httpRequestParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*40);
    HttpConnectionParams.setSoTimeout(httpRequestParams,1000*40);

    return httpRequestParams;
}

And here's the output i get in the console.
> Connected to process 13772 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ample.picloade: The ClassLoaderContext is a special shared library.
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/ample.picloade: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ample.picloade: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xf0cd5a30, tid 13864
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf0ae20c0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xf0ae20c0: ver 2 0 (tinfo 0xf0e1e7f0) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
    HostConnection::get() New Host Connection established 0xf0cd5af0, tid 13864
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fa2b4000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
I/Choreographer: Skipped 122 frames!  The application may be doing too much work on its main thread.
W/ample.picloade: JNI critical lock held for 65.664ms on Thread[1,tid=13772,Runnable,Thread*=0xe2cc4610,peer=0x71ffe018,"main"]
I/AssistStructure: Flattened final assist data: 1464 bytes, containing 1 windows, 9 views
I/System.out: getting request params
I/System.out: set post entity
I/System.out: executing post
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10152; state: ENABLED
I/System.out: toasted

And here's the PHP file that's used in the code:
<?php
if(isset($_POST['name'])){ $name = $_POST['name']; }
if(isset($_POST['image'])){ $image = $_POST['image']; }

$decodedImage = base64_decode("$image");
file_put_contents("picbox_pics/" . $name . ".PNG", $decodedImage);

?>

Any idea's would be greatly appreciated, as I've been stuck for a day or so now. I think it may have something to do with the "D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10152; state: ENABLED" that happens just when the toast should (or at least some time before my "toasted" print), but I can't turn that option off in the emulator, and I'm not even sure that's the issue.
EDIT: heres the php output:
Notice: Undefined index: name in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 2

Notice: Undefined index: image in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 3
Here is some more debugging info:Array ( )
Warning: file_put_contents(picbox_pics/.PNG): failed to open stream: No such file or directory in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 9

A: You didn't call show() on the toast that is why it doesn't show. should be like this:
Toast.makeText(getApplicationContext(),"Your pic was uploaded",Toast.LENGTH_SHORT).show();


text:
Q: how to use selenium wait.until with anchor element in java i have selenium project written in c# and i want to migrate it to java, but i have a problem that i could not solve by myself.
lets say i have a webElement elem1 and i want to find another element elem2 using elem1 as the anchor.
so in java i can do it like that:
WebElement elem1 = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.uiContextualLayer.uiContextualLayerBelowLeft"))) ;

WebElement elem2 = elem1.findElement(By.tagName("li"));

now, my problem starts when i want to do the same but with wait.until() for elem2. the thing is that elem1 is always appear in the DOM, but elem2 will appear in the DOM only after some time (it depends on some code that is not relevant for this issue), so using the above code will throw an exception.
in c# i used lambda expression and it was very simple:
IWebElement elem1 = wait.Until((d) => { return d.FindElement(By.CssSelector("div.uiContextualLayer.uiContextualLayerBelowLeft")); });

IWebElement elem2= wait.Until((d) => { return **elem1**.FindElement(By.TagName("li")); });

in java i cant find a way to do the wait.until AND use elem1 as the anchor for the findElement function.
here is a sample of the html i'm working on:

                       …

i don't want to get all the elements that has the "li" tagName into a list and than go over each element to find the element i need. i'm pretty sure i'm missing something which is very basic, and would appreciate any suggestion/explanation.

A: The most Java-style way is to have methods that return locators and write your own inline ExpectedCondition that uses these methods.
public By getElem1Locator() {
    return By.cssSelector(....);
}
public By getElem2Locator() {
    return By.tagName(....);
}

...

    WebElement elem2 = wait.until(new ExpectedCondition<WebElement>() {
        public WebElement apply(WebDriver driver) {
            try {
                return driver.findElement(getElem1Locator()).findElement(getElem2Locator());
        } catch (NoSuchElementException e) {
            return null;
        }
    });

...

The reason why we want to use locators and not final WebElement instances is that if DOM changes while we are waiting, the WebElement can become stale.
A quick and dirty solution is to use a single Xpath selector for the second element
WebElement elem2 = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[contains(concat(' ',normalize-space(@class),' '),' uiContextualLayer ') and contains(concat(' ',normalize-space(@class),' '),' uiContextualLayerBelowLeft ')]//li"));

You should also take a look at Page Factory


text:
Q: How to use "has_child" in the Rest High Level Client of ElasticSearch I want to issue the following search query in ElasticSearch.
GET /example1/_search
{
  "query": {
    "has_child": {
      "type": "schedule",
      "query": {
        "bool": {}
      },
      "inner_hits": {},
      "max_children": 10,
      "min_children": 1,
      "score_mode": "min"
    }
  }
}

How do I write the above query in the Rest High Level Client in Java?

A: Use HasChildQueryBuilder.
Official documentation.


text:
Q: tkz-euclide x RequirePackage I was reading into the forums about drawing with TIKZ, as recently I found myself in need to create drawings in my documents - I'm a teacher and I'm trying to use XeLaTeX to create worksheets and also texts for my students to read, and since they're in middle school I figured that using images would help them understand the ideas better, for both 2d and 3d geometry. Today I heard about the tkz-euler package, but when I loaded it in my preamble, I got errors. So, I copied a code from this post and loaded my preamble with it:
This is the code I've got:
\RequirePackage[l2tabu, orthodox]{nag}
\documentclass[a4paper,12pt]{article}
\usepackage[hmargin=2cm,vmargin=2cm,bmargin=2cm]{geometry}
\usepackage[brazil]{babel}
\usepackage{fontspec}
\usepackage{units,gensymb}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{comment}
\usepackage{tkz-euclide}
%\usetikzlibrary{shapes.geometric}
%\usetikzlibrary{calc}
\usetkzobj{all}
\usepackage{pgfplots}

\usepackage{siunitx}
\usepackage{icomma}
\usepackage{newtxmath} %Para fonte times (usar text para texto)
\sisetup{output-decimal-marker = {,}} %Vírgula como separador decimal no siunitx
\newcommand*\circled[1]{\tikz[baseline=(char.base)]{\node[shape=circle,draw,inner sep=2pt] (char) {#1};}} %Para fazer números em círculos
\let\sin\relax\DeclareMathOperator\sin{sen}

\begin{document}
\begin{tikzpicture}

\tkzDefPoint(0,0){A}  \tkzLabelPoint[below left](A){A}
\tkzDefPoint(3,0){B}  \tkzLabelPoint[below right](B){B}
\tkzDefSquare(A,B)    \tkzGetPoints{C}{D}
\tkzDrawSquare(A,B)
\tkzLabelPoint[above right](C){C} \tkzLabelPoint[above left](D){D}
\tkzDefMidPoint(C,D) \tkzGetPoint{E}  \tkzLabelPoint[above](E){E}
\tkzDefMidPoint(B,C) \tkzGetPoint{F}  \tkzLabelPoint[right](F){F}
\tkzDrawSegments(A,E E,F A,F)
%\tkzDrawPolygon(A,E,F)
\tkzDrawPoints[fill=black](E,F)
\tkzMarkAngle[fill=red,%
             %size=0.4,   % for small squares you may want to use this
             opacity=0.4](F,A,E)
\tkzLabelAngle[pos=1.2](E,A,F){$\alpha$}

\end{tikzpicture}
\end{document}

At first I thought it was a compatibility problem about TIKZ vs. tkz-euclide, that's why TIKZ isn't even in the document, but I've come to realize that the very first line was causing the errors, so commenting out \RequirePackage[l2tabu, orthodox]{nag} worked.
My problem is that that I got that line a while ago and can't remember why, so I am kinda unsure whether to delete it or not. So:

*

*What is the function of \RequirePackage[l2tabu, orthodox]{nag}?

*Is it a good move to swap TIKZfor tkz-euclid or do they complete each other? I also have use for tikz-3dplot, what packages should I keep?

*The pgfplots package is there since I saw it where I copied the code from. What's it's function in this situation?

Thanks in advance!

A: *

*The point of the nag package is to tell the user if he is doing something that is considered bad practice or obsolete. Now, it wont catch all such things of course, but it is supposed to catch a lot of the things described in l2tabu. Exactly why it causes a conflict here I cannot say though.

*tkz-euclide loads TikZ. tkz-euclide is designed for creating figures like the one you've made, while TikZ is more general. You can do whatever tkz-euclide can with just TikZ, but in some cases the former has much easier ways of achieving certain types of constructions.
In other words, if you like tkz-euclide, keep it. It doesn't prevent you from using TikZ, nor (I think) tikz-3dplot.

*pgfplots does precisely nothing here, as far as I can see, its features aren't used at all.
Also, as you're loading siunitx I don't think there is any point in loading units.


text:
Q: Is using a bigger buffer useful? I use buffer for quite a long time when I need to copy a stream or read a file.
And every time I set my buffer size to 2048 or 1024, but from my point of view a buffer is like a "bucket" which carries my "sand" (stream) from one part of my land (memory) to an other part.
So, increase my bucket capacity will in theory allow me to do less travel? Is this a good things to do in programming?

A: The answer is: it depends. Unfortunately, there is NO single answer to your question. The number of variables (which include the speed of the hardware, the source of the stream, the type of the disk the file is being read from, memory available, OS file caching algorithm, etc, etc) all affect the answer.
For particular situations, I advise performance measurement to see if a bugger buffer helps.

A: Let's pretend you are copying a data structure from one file to another, and you use a buffer to store the data between the time you read it and the time you write it.
There is an overhead when you read and write data.  On disk, the head has to find the sector and read or write the track.  In memory, it takes a processor instruction to move a chunk of memory (usually 1-8 bytes at a time) plus a bus operation to move data from one part of memory to another, or between memory and the processor or memory and disk.  Each chunk that you read is processed in a loop somewhere and the smaller the chunks, the more times the loop has to be executed.
If your buffer is a single byte, you will incur this overhead every time you read or write a byte of data.  In our example, the disk can't read and write simultaneously, so the write may have to wait until the read is finished.  For a one-byte file, this is the best you can do, but for a 1MB file, this will be extremely slow.
If you have a 10MB buffer and want to copy a 10MB file, you can read the whole thing into your buffer, then write it all out again in one step.
Now, if you want to copy a 20GB file, you probably don't have that much memory.  Even if you do, if every program allocated 20GB of memory for buffers, there wouldn't be anything left!  When you allocate memory, you have to release it, and both the allocation and release can take time.
If a client of some kind is waiting for whole chunks of data, sometimes smaller chunks are better.  If the client gets a few chunks and knows they don't want the rest, they can abort, or maybe they can display what they have while waiting for more so that a human user can see that something is going on.
If you know the amount of data you are copying before you have to allocate your buffer, you can make a buffer that's the ideal size for the data you are copying.  Either the exact size of all your data, or big enough for the data to be copied in a reasonable number of chunks.  If you have to guess, some size around 1MB is reasonable for an unknown purpose.
To create the perfect sized buffer, you need to study the data that you are going to use it for.  If you are copying files, how big are most of the files people copy?  Then you guess at a good buffer size and time it.  Tweak the size and time it again.  Your total available memory may limit your maximum size.  Eventually you arrive at the ideal buffer size for your specific goal.

A: It all depends on what you are doing and with what machinery and so forth.  Try different numbers and see what happens.
However, I have found that the bigger the buffer, the faster the reads and writes.  I mention this because you talk about 1024 and 2048.  Try some really big buffers instead.  I found in one case I was reading 8 times as fast by switching from 8Kb up to 100Kb, and I got noticable improvements up to 1Mb.
I'm no hardware expert, but I've found generally computers do sequential byte copies at many times the speed of an individual byte copy.  Maybe they do things in parallel, maybe it moves data through caches faster, maybe it's magic.  But using big buffers and array copies (or loops that optimizers can turn into array copies) can save a lot of time.

A: There is an optimal size to a buffer. Too small a buffer can trigger more system calls than necessary, while too big a buffer can trigger unnecessary reloads of the CPU cache. The best way to answer this question for your specific situation is to use a profiler.


text:
Q: End of File (EOF) Hello I've written an algorithm where it prints last number  , but I wonder how to make it  not to print default value of "number" for example(4.94066e-324) when there's no number written in console/file.
#include <iostream>
using namespace std;

int main() {
double number;
for (; cin >> number;);
cout << number; }

A: One way is to check wether the first input operation succeeds or not:
#include <iostream>

int main() {
    double number;

    if(std::cin >> number)
    {
        while (std::cin >> number);

        std::cout << number;
    }
    else
    {
        std::cout << "There is no number :(";
    }
}

Few things I changed here:

*

*removed using namespace std;, it's considered bad parctice

*a while is better suited for this task than a half-empty for
And of course this can be generalized to any std::basic_istream.

A: You can use a flag to check if you have ever got any input, like this:
#include <iostream>
using namespace std;

int main() {
    double number;
    bool flag = false;
    for (; cin >> number;)
        flag = true;
    if(flag)
        cout << number;
}


text:
Q: do something when an ajax call is successful in axios - chaining then() in axios I'm trying to do something when an ajax call is successful in axios
    save() {

      this.isUpdateTask ? this.updateProduct() : this.storeProduct()

      this.endTask()

    }

if the ajax call to update or store the product is successful, I want to run the endTask() function.
I don't want the endTask() function to be run when the ajax call is not successful.
how can I do that?
the store function:
    storeProduct() {
      return axios
        .post("products", this.getFormData())
        .then(
          response => this.products.push(response.data.data)
        )
        .catch(
          error => (this.serverErrors = error.response.data.errors.detail)
        )
    },

A: You can call this methods inside a new promise like this below example:

   save() {
      Promise.resolve()
      .then(() => {
        return this.isUpdateTask ? this.updateProduct() : this.storeProduct()
      })
      .then(() => {
        this.endTask()
      })
    }

Have other ways to do also:
save() {
  (this.isUpdateTask ? this.updateProduct() : this.storeProduct()).then(() => {
    this.endTask()
  })
}

Or assign to a variable:
save() {
  const promiseUpdate = this.isUpdateTask ? this.updateProduct() : this.storeProduct()

  promiseUpdate.then(() => {
    this.endTask()
  })
}

Or with async/await:
async save() {
  await this.isUpdateTask ? this.updateProduct() : this.storeProduct()
  // this code runs only if everything happen successful
  await this.endTask()
}

And about the endTask execute until when response is not successful, is because you treat the error inside the storProduct.
.catch(
  error => (this.serverErrors = error.response.data.errors.detail)
)

So, in this case, is necessary re-throw the error again:
.catch(
  error => {
    this.serverErrors = error.response.data.errors.detail
    throw error
  }
)

The catch of Promise, have same effect of try/catch from javascript.
Have more reference about catch on promise here.

A: Anything inside the .then is only executed when a successful response is received
.then(response => {
    this.products.push(response.data.data)
    this.save()
    })

A: Try this:-
storeProduct() {
  return axios
    .post("products", this.getFormData())
    .then(
      response => this.products.push(response.data.data)
      this.endTask();  //call endtask() here after successfull api call and response back from api
    )
    .catch(
      error => (this.serverErrors = error.response.data.errors.detail)
    )
}


text:
Q: Difference between UIView.init and without init in swift 3 I am programmatically adding two UIView. As shown below example:-
 let firstview = UIView(frame: CGRect(x: 0, y: self.view.frame.height-63,width:self.view.frame.width, height: 80))
 let secondview = UIView.init(frame:CGRect(x: 0, y: self.view.frame.height-63,width:self.view.frame.width, height: 80) )

Both are work perfectly.

What is the difference between both of these UIViews?

A: Both are the same and call the same init function of UIView. It is best practice to not directly call the init though and just use UIView(frame:)

A: Writing empty parentheses after a class name ( MyClass() ) in Swift is equivalent to calling its initializer by writing MyClass.init().
The same works for initializers accepting input arguments, so the two lines in your question are equivalent.


text:
Q: Passing input to subprocess popen at runtime based on stdout string I am trying to run following code
process = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE)
while process.poll() is None:
   stdoutput = process.stdout.readline()
   print(stdoutput.decode())
   if '(Y/N)' in stdoutput.decode():
       process.communicate(input=b'Y\n')

this cmd argument runs for a few minutes after which it prompts for a confirmation, but the process.communicate is not working, neither is process.stdin.write()
How do I send input string 'Y' to this running process when it prompts for confirmation

A: Per the doc on Popen.communicate(input=None, timeout=None):

Note that if you want to send data to the process's stdin, you need to create the Popen object with stdin=PIPE.

Please try that, and if it's not sufficient, do indicate what the symptom is.

A: On top of the answer from @Jerry101, if the subprocess that you are calling is a python script that uses the input(), be aware that as documented:

If the prompt argument is present, it is written to standard output without a trailing newline.

Thus if you perform readline() as in process.stdout.readline(), it would hang there waiting for the new line \n character as documented:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string

A quick fix is append the newline \n when requesting the input() e.g. input("(Y/N)\n") instead of just input("(Y/N)").
Related question:

*

*Python subprocess stdout doesn't capture input prompt


text:
Q: Excel VBA - Assistance on comparing ranges and arrays I've got this workbook I've been trying to get to work via macro code. And I've had some assistance with it, but nobody seems to understand what I'm after. It's a workbook used to track and keep a summary of the amount of work clothes each user in our company has received. So, basically, I've got three sheets in this workbook: https://skydrive.live.com/view.aspx?cid=5D018DB0458F03ED&resid=5D018DB0458F03ED%21163

*

*Summary

*Users

*Articles

The general idea was that I would create a PivotTable from the data in the Summary sheet. But I want the workbook to be dynamic using vba code. So I'll go through each sheet here.
Users: This workbook contains just one column (A), A1 is called "Name" and each row under that contains each user in our Company.
Articles: This workbook contains two columns, A1 is the name of the article (pants etc) and the other one is the price of that item.
Summary: This is the tricky part. This sheet should mirror the data from the other two sheets, but I need to keep track of how many of each item each user has received as well. I keep this data in Column D in the Summary sheet. So each name in the Users sheet needs to be repeated as many times as there are items in the Articles sheet. If there are 10 items in the Article sheet, the name must be repeated 10 times. That way, I can say how many of each item that user has received.
So, the tricky part is to actually mirror the content from the Users and Articles sheet, but still keep the data from column D in the summary sheet. Also keep in mind that if I remove a row from the Users sheet then that user needs to be removed completely from the Summary Sheet, including the amount of each item that was registered. And if I add an item to the Articles sheet, then that item needs to be added for each user in the Summary sheet.
I've got some macro code there that somebody helped me with, but I didn't really get what was going on. I'm not that sturdy with arrays and loops. And this is what I'm trying to learn now because I see the potential of learning it.
I do however get that I need to collect the data from all sheets in their own ranges, storing all of the data. Then I need to compare the Users range with the Summary Range to see if the user is present in that range. If it is, make sure to update the data from the Articles Range as well as keeping the amount from ColumnD. If it's not in the Summary sheet, add it. The same goes for each item as well.
But, what if I mistype a user and don't realize it until after I've been adding amounts for that user? If I then go back to the Users sheet and rename the user, would I loose all of the data I previously added? Or is it possible to be able to rename users as well? In that case, I'd probably need some sort of ID for each user, much like CID in Windows? Is this all a bit too overkill? It all comes down to what it more worth while, timewise. I'd really appreciate some help here :)
Public Sub NewCollect()
' Declare variables
Dim shtUsers, shtmyArticles, shtmySummary, shtmyAmount As Worksheet
Dim arrUsers, arrarticles, arramount, arrsummary As Long

' Set worksheets
Set shtUsers = Sheets("Brukere")
Set shtArticles = Sheets("Artikler")
Set shtSummary = Sheets("Oppsummering")
Set shtAmount = Sheets("Antall")

' Get range from shtUsers
With shtUsers
    If Not .Range("A2") = "" Then
        arrUsers = .Range("A2", .Cells(Rows.Count, "A").End(xlUp)).Resize(, 2)
    End If
End With

' Get range from shtArticles
With shtArticles
    If Not .Range("A2") = "" Then
        arrarticles = .Range("A2", .Cells(Rows.Count, "A").End(xlUp)).Resize(, 3)
    End If
End With

' Get range from shtAmount (The new sheet)
With shtAmount
    If Not .Range("A2") = "" Then
        arramount = .Range("A2", .Cells(Rows.Count, "A").End(xlUp)).Resize(, 2)
    End If
End With

' Get range from shtSummary
With shtSummary
    If Not .Range("A2") = "" Then
        'Here I have no idea where to even begin
    Else
        ' If Summary sheet is blank, get data from other sheet and insert
        ReDim tempArr(1 To UBound(arrUsers) * UBound(arrarticles), 1 To 6)
        For u = 1 To UBound(arrUsers)
            For i = 1 To UBound(arrarticles)
                j = j + 1
                tempArr(j, 1) = arrUsers(u, 1)
                tempArr(j, 2) = arrUsers(u, 2)
                tempArr(j, 3) = arrarticles(i, 1)
                tempArr(j, 4) = arrarticles(i, 2)
                tempArr(j, 6) = arrarticles(i, 3)
            Next
        Next
        ' Add the data
        .Range("A2").Resize(j, 6).Value = tempArr
    End If
End With

Edit: I just added a new column to both users and articles sheets kalled ID where I can add an ID for each item. Updated the actual sheet on my SkyDrive now.

A: I would first start by totally separating your input from your output. This is based on experience since I put together a rather complex accounting spreadsheet for an accountant a couple of years ago which would act as a general ledger and P&L.
Control information was on one sheet, GL codes were on another, transactions were on yet another, and a macro basically went through and created summary and detail balance sheets and income/expenditure statements on four other sheets.
The original attempt tried to manipulate information on the input side but it turned out to be a nightmare. Once the input and output were separated, it became a lot easier to manage.
In other words, have something like the following sheets:

*

*People.

*Items.

*Transaction.

*Output.

The first three of those are input only. The transaction are a list of what items were given to what people (a many-to-many relationship). Then I would have a macro which performs as follows.
First, clear out the fourth sheet totally (Output). Then, for each active person in the People sheet, go through the Transaction sheet and create an Output entry for any transaction attached to that person.
By the way, I say 'active' above since you might want to maintain the history, keeping records around for people who have left. That would be a flag of some sort in the People sheet.
You'll probably need to look up the items and prices as part of this process.
You can report on errors as part of the macro as well, such as Transaction entries that have no valid People or Items.
You may also want to consider the possibility that some people/items may have identical names (and even an identical item may change price periodically). To that end, it might be wise to attach a unique ID to each person and item to ensure there's no possibility of mis-identification. Those unique IDs would be stored in the Transactions sheet.

Since the macro I discussed weighs in at 37K, I can't post the lot here. But this is the main processing bit which processes the transactions sheet and updates the accounts page with balances:
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Option Explicit

Public Const TxnSheet = "Txns"
Public Const TxnColId = "a"
Public Const TxnColDate = "b"
Public Const TxnColAcct = "c"
Public Const TxnColAmt = "d"
Public Const TxnColDesc = "e"
Public Const TxnColNotes = "f"
Public Const TxnRowStart = "2"

Public Const AcctSheet = "Accts"
Public Const AcctColReport = "a"
Public Const AcctColType = "b"
Public Const AcctColBold = "c"
Public Const AcctColItalic = "d"
Public Const AcctColFontPlus1 = "e"
Public Const AcctColOther2 = "f"
Public Const AcctColOther3 = "g"
Public Const AcctColOther4 = "h"
Public Const AcctColOther5 = "i"
Public Const AcctColLevel = "j"
Public Const AcctColSign = "k"
Public Const AcctColAcct = "l"
Public Const AcctColVal = "m"
Public Const AcctColNotes = "n"
Public Const AcctRowStart = "2"

' Process all transactions.

Sub ProcessTransactions()
    Dim TxnId As Integer
    Dim Balance As Double
    Dim WsTxn As Worksheet
    Dim WsAcct As Worksheet

    Dim RowTxn As String
    Dim RowAcct As String

    Dim RowTxn2 As String
    Dim RowTxn3 As String

    Dim StartDate As Date
    Dim EndDate As Date
    Dim CutoffDate As Date
    Dim PastCutoff As Boolean

    ' Get user-configurable stuff

    StartDate = GetConfig("start_date")
    EndDate = GetConfig("end_date")
    CutoffDate = GetConfig("cutoff_date")
    PastCutoff = False

    ' For filling in transaction IDs.

    TxnId = 1

    Set WsTxn = Worksheets(TxnSheet)
    Set WsAcct = Worksheets(AcctSheet)
    RowTxn = TxnRowStart

    ' Select the worksheet and cell so we can see what's happening.

    WsTxn.Select
    Range(TxnColAcct + RowTxn).Select
    Range(TxnColAcct + RowTxn).Show

    ' Process all transaction lines.

    Do While Range(TxnColAcct + RowTxn).Value <> ""
        ' Check for start of transaction (non-blank date).

        If Range(TxnColDate + RowTxn).Value <> "" Then
            ' Check date within range.

            If Range(TxnColDate + RowTxn).Value < StartDate Or Range(TxnColDate + RowTxn).Value > EndDate Then
                Range(TxnColDate + RowTxn).Select
                MsgBox "ERROR: ProcessTransactions: Date out of range"
                End
            End If

            If Range(TxnColDate + RowTxn).Value > CutoffDate Then
                PastCutoff = True
            End If

            ' Start of transaction, fill in transaction ID and increment.

            Range(TxnColId + RowTxn).Value = TxnId
            TxnId = TxnId + 1

            ' Check that transaction is balanced.

            RowTxn2 = FindNextTxn(RowTxn)
            RowTxn3 = PrevRow(RowTxn2)

            Balance = 0
            Do While RowTxn2 <> RowTxn
                RowTxn2 = PrevRow(RowTxn2)
                Balance = Balance + Range(TxnColAmt + RowTxn2).Value
            Loop
            If Balance > 0.001 Or Balance < -0.001 Then
                Range(TxnColAmt + RowTxn + ":" + TxnColAmt + RowTxn3).Select
                MsgBox "ERROR: ProcessTransactions: Unbalanced transaction"
                End
            End If
        Else
            ' Not transaction start, clear transaction ID column.

            Range(TxnColDate + RowTxn).Clear
        End If

        ' Get account line, error if account not in accounts worksheet.

        RowAcct = FindAccount(Range(TxnColAcct + RowTxn).Value)
        If RowAcct = "" Then
            MsgBox "ERROR: ProcessTransactions: Invalid account '" & Range(TxnColAcct + RowTxn).Value & "'"
            End
        End If

        ' Update accounts value.

        If Not PastCutoff Then
            WsAcct.Range(AcctColVal + RowAcct) = WsAcct.Range(AcctColVal + RowAcct) + Range(TxnColAmt + RowTxn).Value
        End If

        ' Move to next transaction.

'        Sleep 50
        RowTxn = NextRow(RowTxn)
        Range(TxnColAcct + RowTxn).Select
        Range(TxnColAcct + RowTxn).Show
    Loop

    Range(TxnColDate + RowTxn).Select
    Range(TxnColDate + RowTxn).Show
End Sub

It may not be that useful without knowing the sheet layout but it's the best I can do without being able to send you the whole workbook.


text:
Q: Ubuntu server or Debian server (to run C++ apps developed on Ubuntu) I have written a number of C++ server side daemons for my website, using my Ubuntu 9.10 dev machine.
The C++ apps I mentioned above are "GUI-less" daemons (and libraries used by the daemons).
I am now about to host my website and need to decide whether to go with Debian server or Ubuntu server.
In a nutshell, here is the situation:

*

*I developed on Ubuntu desktop because I preferred the more friendly GUI

*I would like to deploy on Debian Server because of the (perceived?) robustness of the Debian server over Ubuntu server (I may be totally wrong here - and in fact, this is really what this question is all about)

*If Debian server is indeed more robust than Ubuntu server, then I have no choice but to go with Debian server - BUT, will my Ubuntu developed C++ apps run on the server? (or do I need to recompile them on the server? (I'd HATE to have to do this, because I want to keep the server machine clean and light - no GUI, no dev tools etc). This last question is really about binary compatability between Ubuntu and Debian.

I want the server to be robust, secure and stable, and simply act as a server (i.e. LAMP and very little else - no GUI etc). Given that requirement, and the fact that I need to run my C++ apps (developed on Ubuntu 9.10),
I need advice on which OS to choose for the server. Ideally, any advice will be backed with a reason. I am particularly interested in hearing from people who have been in an identical situation, or done something similar.

A:
Also, there seems to be a new "patch"
  every few weeks - which I would not
  like on a server (I want to leave the
  server well alone, and let it get on
  with its business of serving pages).

You're doing it wrong.
Debian stable has an excellent security policy, and if they offer a security update it means that they fixed some package that has a security flaw. You don't really have the option of not updating it, or you'll get hacked sooner or later.
Of course you could write a script that calls the updates and upgrades automatically every day, but you'd better pay personally attention to your server.

I dont want to be grappling with the
  learning curve associated with a new
  OS

ubuntu is just a modified debian for desktop use: likely you won't have any problem.

A: My experience with Ubuntu and Debian would lead me to Debian on the server - they have far more of a focus on stable, solid releases and more of a history in the server space, and my experiences with Ubuntu have been pretty uneven.
That said, that's just my personal experience; I know there are people running server farms on Ubuntu, so it's not out of the question.
If you do chose Ubuntu, be sure to pick an LTS (Long Term Release), so you get bugfix/security support for 3-5 years, instead of 18 months in the regular Ubuntu releases.
Finally, Florian is quite correct that you're best off having a local environment that mirrors your production environment; the best way to achieve that is probably a Xen/KVM/etc guest with whatever your server is built with.

A: Just an alternative to consider - run a small virtual machine in your Ubuntu host that runs a Debian server. The purpose of this is to generate Debian packages. You can pollute this VM with as many developer packages as you need and all the build tools necessary. Then, use the command line just to compile and build your package for deployment. Not the most elegant solution, but it should allow you to do 90% of your development on Ubuntu and deploy a binary package that definitely works on Debian.

A: In my experience it is better to have a server that does nothing but serve. By this I mean avoid desktop user interfaces on servers. You can do all you need with the command line, if you can't the app is not meant for the web server. This will increase stability and virtually nullify downtime, whilst also maintaining separation of dev/pub. Ensure that the apps you write are command line compatible and you should be golden for the daemons. If the app absolutely must have a UI, make the UI web based.

A: If I understand correctly, you mainly use the computer through the graphical UI, and I can guess you might be a bit lost in front of a command line only computer. It is true that the UI changes, but keep in mind that both use GNOME and are not so different. But it is true that Debian is more rough.
Regarding updates, Debian also has regular updates on its stable release, almost daily. As for binary compatibility, the best is to recompile your software for the target system you aim to deploy to, even if it should work as is, as long as the versions you use have about the same age.
With this in mind, I have about the same feeling that ubuntu may be a better route for you.

A: As Ubuntu is based on Debian the differences aren't that big (except for the GUI - but you won't use a GUI for you server, right?). If you can work on the command line with Ubuntu you can do the same on Debian.
On both Debian and Ubuntu you'll get only important updates, like security fixes, for the stables releases, so for the same software you should expect amount the same amount of updates on Debian.
Using the same system for development as you have on the server helps to avoid a lot of problems.

A: Ubuntu is Debian. Most things developed on Ubuntu should 'just work' on Debian. If you want stability you may want to look into Ubuntu's LTS (Long Term Server) which is designed to provide a longer period of stability than the regular six month release cycle that the regular Ubuntu Desktop release provides. Or you may want to look into Debian Stable. Currently Debian Stable is version 5.0 but a new Debian Stable will likely be released this year.
Debian Stable is very stable. It gets tested extensively for roughly two years before release and there are minimal updates to it - only security patches and the most critical changes. It has a reputation in the industry as being an extremely stable Linux.

A: There is no need to recompile your app for Debian if it was developed on Ubuntu.  You are compiling for the Linux Platform, not a specific distribution.  With that said, that is not a guarantee that you don't have dependencies in your app that you would have to ensure are installed on your production server.
My recommendation is to continue to develop in whatever way is comfortable for you, however you should have a test machine.  For this purpose Virtual Machines are a great solution.  For ease, I would recommend VirtualBox, but Xen, KVM, or VMware could all serve your purposes.
The important thing to note is that you should ensure that your test server (the VM) is as close in configuration to your production box as possible.  What I recommend is either automating your build process, scripting your installs and configs, or (the hard way) taking detailed notes of the changes that you make on one server and reproducing them on the other.
Once you have them almost ready to start testing and deploying your app, take a snapshot of the VM.  This is a feature of most virtualization platforms that allows you to roll back to a certain state.  (In this case, your pre-app-deployed state.)  Then test your app.  If it works, deploy it.  If it continues to work in production, get rid of the snapshot and that is your new "live" image.  (You can keep your snapshots, but if you are going to be upgrading your app in production, you should be upgrading it in test...)  If it works in test but not in prod, you will have to find the specific fix for prod.  Once you do that, you will need to replicate your changes back to your test box and resume the testing cycle.
Yes, it's work.  But it's the right way.
-Waldo


text:
Q: Loading a resource in a JAR file I have a Java project in Netbeans. It runs fine with Maven. So I assembled it. It contains the following code to load a file that is in the JAR:
ClassLoader loader = MyClass.class.getClassLoader();
SERVICE_URL = loader.getResource("my.wsdl");

This returns a URL like:
jar:file:/path/to/my/file/MyClass-1.0-SNAPSHOT-jar-with-dependencies.jar!/my.wsdl

but the library that needs this parameter doesn't appear to be able to use it.
Is there any way this file can be in the JAR and be referred to from the code like this?

A: You may have to use ClassLoader.getResourceAsStream(), copy it to a temporary file, and then create a URL with File.toURI().toURL()


text:
Q: python - how to pivot without aggregate so my df looks like that:

task
feature
activity

a
e
1

d
2

f
3

e
4

d
5

f
6

e
7

d
8

f
9

e
10

d
11

f
12

--------
--------
--------

b
e
13

d
14

f
15

e
16

d
17

f
18

e
19

d
20

f
21

e
22

d
23

f
24

and I want it to look like that:

task
e
d
f

a
1
2
3

4
5
6

7
8
9

10
11
12

--------
--------
--------
---------

b
13
14
15

16
17
18

19
20
21

22
23
24

the numbers and letters here are just for example, in the real df the characters are different and the numbers are random.
I tried using pivot but got this message:
ValueError: Index contains duplicate entries, cannot reshape

and then I tried pivot_table() but the whole point is that I don't want to aggregate.
I'd be happy to know if there is a solution for that. Thanks!


text:
Q: Python while loop with invalid syntax Just to give some background on the project I am working on before I show the code. I am currently developing a Python script that will be running on a Raspberry Pi to monitor the float switch from a sump pump in my basement. This code will check to see if the sump pump is not working by these two criteria:

*

*If the switch is on for more than three minutes

*If the switch turns on and off more than 10 times in three minutes

I am not done with the rest of the code, but here is what I have:
import time

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
floatSwitch = GPIO.input(17)

import smtplib

running = True
log = open("sumpPumpLog.txt", "r+")
startTime = time.time()

def elapsedTime():
    """This function checks how much time
    has elapsed since the timer has started"""
    endtime = time.time()
    elapsed = endtime - starttime
    return elapsed

def sendEmail(*msg):
    """This function sends an email to selected recipients with a custom
    message as well as the log file attached."""
    #enter the code that sends an email to the family with the log attached

    fromaddr = 'from@email.com'
    toaddrs = [to@email.com']
    msg = """Please see the Pi and the data log file for more details."""

    # Credentials (if needed)
    username = 'my_username'
    password = 'my_password'

    msg.attached()

    # The actual mail send
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username, password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()

if running is True:
    if floatSwitch is True:
        #Write the time and what happened to the file
        log.write(str(time.time() + "Float switch turned on")
        #Wait until switch is turned off

        while floatSwitch is True:
            startTime = time.time()
            if floatSwitch is False:
                log.write(str(now) + "Float switch turned off")
                break
        #if elapsedTime > 3 min (in the form of 180 seconds)
        elif elapsedTime() > 180:
            log.write(str(now) + "Sump Pump has been deemed broaken")
            sendEmail("The sump pump is now broken.")

else:
    log.write(str(time.time() + "The sctipt has stopped.")
    sendEmail("The script has been stopped.")

My problem is that on line 52 when it says
while floatSwitch is True:

There is an error in the code, and all it says is 'invalid syntax'
I am very new to Python, and this is my first real project with it. I am unfamiliar with a lot of the syntax, so this could be a very elementary mistake. Can anyone please help me fix the syntax of this statement so that I can get my code to work. I know that there are numerous other mistakes without the rest of the code, but I am planning to work out those bugs when I find them. I have searched around, but I cannot find another example like this. Any and all help is very appreciated!

A: Actually, your problem is with the line above the while-loop.  You are missing a parenthesis:
log.write(str(time.time() + "Float switch turned on"))
                                               here--^

Also, just a tip for the future, instead of doing this:
while floatSwitch is True:

it is cleaner to just do this:
while floatSwitch:

A: You have an unbalanced parenthesis on your previous line:
log.write(str(time.time() + "Float switch turned on"))  # Last parenthesis is missing

And also in sendEmail() method, you have a missing opening quote:
toaddrs = [to@email.com']  # Opening quote missing


text:
Q: IIS return 302 instead of 401 Hi guys i m having a problem with CustomErrors in web.config, i'm trying to show a custom page for the error 401, but when a user try to access the controller and haven't authorization.
In this case the return is 302 but must be 401, i tried to use the Application_EndRequest() in Global.asax to change the Response.Status Code :
void Application_EndRequest(object sender, EventArgs e)
{
    if (Context.Response.StatusCode == 302)
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
}

with this the error returned is the 401 but the page of custom errors is not displayed, just a default message of IIS

Unauthorized: Access is denied due to invalid credentials

how can i make the custom errors show the right page for 401 error ?

A: If you are using Forms Authentication, then 401 is handled internally by ASP.NET and used in the Challenge/Response mechanism for authentication.  When you use authentication, you specify a login page, and when a user is not authorized, they are redirect to that page to log in.
There is a difference between a 401, which unauthorized and 403, which is Forbidden.
If you're using Windows Authentication, Digest, or Basic then you will get a 401 Challenge popup.  ASP.NET intercepts 401 so that you don't get popups, and can instead deal with authentication errors in forms.

A: I found the solution for my problem here
Using a custom authorization attribute for redirect to the "AccessDenied" page

A: Take a look at the solution for custom errors in MVC answered on another question within stackoverflow at https://stackoverflow.com/a/620559/686674
You want to override Application_Error rather than Application_EndRequest.


text:
Q: Include SVG file in SVG I've got a linearGradient in the defs section of my SVG file, and reference it with fill="url(#myGradientName)".  That works great so far.
I think I should be able to put my whole defs section in its own SVG file, and then just reference that from all my SVG images.  That is, something like:
styles.svg:
<svg xmlns=...>
  <defs>
    <linearGradient id="myGradient" ...>
    </linearGradient>
  </defs>
</svg>

image.svg:
<svg xmlns=...>
  <rect width="100" height="100" fill="styles.svg#myGradient"/>
</svg>

But I can't seem to get the style to apply.  Do I have the wrong syntax for IDs external to this file (styles.svg#myGradient)?  Do I need to explicitly include the file first somehow?
I've been pouring over the SVG spec and it looks like this should be possible, but none of the examples actually show it being done.
Edit: The FOP FAQ suggests that the correct syntax is fill="url(grad.svg#PurpleToWhite)", but that doesn't work in Gecko or Webkit.  Is that correct and nobody supports it, or am I doing something else wrong?

A: It looks like this is only supported under Firefox 3.1.

A: You do need to say fill="url(styles.svg#myGradient)". That works in Firefox 4 beta 6 and I imagine it worked in Firefox 3.5. But Chrome (7.0.517.41 beta) and the IE9 beta (9.0.7930.16406) still do not support this. It looks like they both look for #myGradient in the current document instead of actually going to the specified URL. Gross.
Here are the complete files I used to test this:
styles.svg
<svg xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="myGradient">
      <stop offset="0" stop-color="red" />
      <stop offset="1" stop-color="black" />
    </linearGradient>
  </defs>
</svg>

image.svg
<svg xmlns="http://www.w3.org/2000/svg">
  <rect width="100" height="100" fill="url(styles.svg#myGradient)"/>
</svg>

A: Actually, the FOP FAQ is right, the correct syntax is embracing the URI with url(...). Just checked with my Firefox, and it handles fills only with surrounding url(). It would be a bug in Safari or Opera, if the'd handle it differently.
I coincidentally filed a similar question, but with similarly little success.
Cheers,