text:
Q: Interpret G-code into motor control signals I'm not sure that this is the right place to post this question, but I figured it was a good start since it deals with code... if not, please point me to the right forum, thanks.
I'm looking to create a G-Code interpreter on a C/C++/FPGA embedded system and I'm not quite sure of how to translate G-code into motor movement signals. This is a project for a proprietary system so there's a lot of extras I don't need like variable gearing ratios, etc. Does anyone know where I can find this info, or know if there's an open source interpreter that I can view as an aid?
Thanks all!

A: There are many open source implementations of G-code interpreters for 3D printers and home-made CNC machines. Even though there is no universal standard (as Hans mentions in comments), the open source community arrived at a consensus that seems to be generally accepted (description can be found on reprap wiki).
Reprap website also provides a list of open source firmwares and interpreters used in 3D printers and CNC machines, which you can use as a start. I am not sure if there is an open source implementation on an FPGA, though, as most open source projects use an Arduino or similar mainstream controllers.
Personally, for CNC machines, I have successfully used the grbl firmware, which many other firmware implementations derive from (e.g., Marlin).


text:
Q: Will Axis2 continue to grow in a healthy pace? I am in the process of selecting a open source ESB product for our integration projects.  My current top two choices are: WSO2 and Servicemix. I've be trying out WSO2 and I like it so far.  It has very nice development and monitor tools with statics tracing. But I heard that the development for Axis2, which WSO2 sits on, is slowing down. And hence a concern over whether it is being phased out slowly.
Does anyone have some insights and/or thoughts on this concern?
Warm regards

A: WSO2 products are not based on regular releases of Apache products, but on forks of these products. In particular their fork of Apache Axis2 is based on Axis2 1.6.1 and Axiom 1.2.11. The corresponding Apache releases date back to 2011. It therefore doesn't really matter whether Apache Axis2 is growing or not, since you will be stuck with forks of old versions anyway.
Moreover, since WSO2 does modifications to these forks while the corresponding Apache products also continue to evolve (Axis2 is at version 1.7.2 and Axiom at 1.2.19), they will actually diverge from each other. In fact, you will find Java packages under org.apache.axis2 in WSO2 products with code that was added by WSO2 and that has never been part of the Apache Axis2 product.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handling a click event in an Ember View I want to make a ol element expand when a link below it is clicked. I know how to make it expand when the ol itself is clicked.
App.MemberListingView = Ember.View.extend({
  isExpanded: false,
  classNameBindings: ['isExpanded'],
  click: function() {
    return this.toggleProperty('isExpanded');
  }
});

The template:
{{#view 'App.MemberListingView'}}

        {{#each}}
          {{user-card user=this}}
        {{/each}}

    Click here to see all
{{/view}}

I want my anchor element to be the click trigger, not the ol itself. How do I do this? Do I have to write a separate view for the link?

A: I am still very new to Ember as well but this should work -
{{#view 'App.MemberListingView'}}

        {{#each}}
          {{user-card user=this}}
        {{/each}}

    Click here to see all
{{/view}}

And in your view (or controller) -
App.MemberListingController = Ember.Controller.extend({
  isExpanded: false,
  classNameBindings: ['isExpanded'],
  actions: {
    expandIt: function() {
        return this.toggleProperty('isExpanded');
    }
  }
});


text:
Q: How can I find the volume of a cone in terms of theta? I have been given these instructions:

*

*Cut out sector from a circle having central angle $\theta$ and radius r

*Form a cone from what's left of the circle (I thought of it as taking a circular piece of paper, cutting a pizza shape out of it, then push the rest of the paper together to make a cone)

*Then find volume of the cone in terms of $\theta$

These are the things I've done so far:

*

*Found the circumference of the cone by subtracting r $\theta$ from 2$\pi$r

*Subtracted the area of the cut sector from the area of a whole circle

Now I am lost, I have a feeling that finding the radius in terms of $\theta$ is the next step I should take.
How can I do this?

A: The angle of the sector not taken is $2\pi-\theta$. The length of the circular arc with central angle $2\pi-\theta$ radians and radius $r$ is $r(2\pi-\theta)=2\pi r-\theta r$ (by the definition of radian measure). When you form the cone, this will be the circumference of the circle at the base of the cone. The radius of that circle is $\frac{2\pi r-\theta r}{2\pi}=r\left(1-\frac{\theta}{2\pi}\right)$ (call it $R$).
The "slant height" of the cone is the radius of the original circle, $r$, and is the hypotenuse of a right triangle with base $R=r\left(1-\frac{\theta}{2\pi}\right)$ and height $h$ (let's say). Therefore
$$h=\sqrt{r^2-\left[ r\left(1-\frac{\theta}{2\pi}\right) \right]^2}$$
$$=r\sqrt{\frac{\theta}{\pi}-\frac{\theta^2}{4\pi^2}}$$
Therefore the volume of the cone will be
$$V=\frac 13\pi R^2h=\frac 13\pi\left[r\left(1-\frac{\theta}{2\pi}\right)\right]^2\left[r\sqrt{\frac{\theta}{\pi}-\frac{\theta^2}{4\pi^2}}\right]$$
$$=\frac 13\pi r^3\left(1-\frac{\theta}{2\pi}\right)^2\left(\sqrt{\frac{\theta}{\pi}-\frac{\theta^2}{4\pi^2}}\right)$$
You could simplify that further, as you like.
Note that the answer would have been significantly easier if you defined $\theta$ to be the central angle of the sector left after cutting rather than of the sector that was cut. If we define $\Theta$ as that central angle that was left, we end up with
$$V=\frac 13\pi r^3\left(\frac{\Theta}{2\pi}\right)^2
\sqrt{1-\left(\frac{\Theta}{2\pi}\right)^2}$$

A: The radius $R$ of the cone is given as
$$2\pi R=(2\pi-\theta)r$$$$ \implies R=\frac{(2\pi-\theta)r}{2\pi}\tag 1$$ & the slant height of the cone will be $r$ hence its vertical height $H$ is given as $$H=\sqrt{(\text{slant height})^2-(\text{radius})^2}$$ $$=\sqrt{(r)^2-\left(\frac{(2\pi-\theta)r}{2\pi} \right)^2}$$ Hence, the volume of the cone $$=\frac{1}{3}\times (\pi R^2)(H)$$ $$=\frac{1}{3}\times \left(\pi \left(\frac{(2\pi-\theta)r}{2\pi}\right)^2\right)\left(\sqrt{(r)^2-\left(\frac{(2\pi-\theta)r}{2\pi} \right)^2}\right)$$ $$=\color{blue}{\frac{1}{3}\pi r^3 \left(1-\frac{\theta}{2\pi }\right)^2\sqrt{1-\left(1-\frac{\theta}{2\pi }\right)^2}}$$

A: in your sector, we have $\theta=\frac{l}{r}$ where $l$ is sector's arc length. so $l=r\theta$.
$l$ will become the cone's base perimeter. so if we call the base's radius as $R$, we have $r\theta=2\pi R$. now we can find $R$ to be $\frac{r\theta}{2\pi}$.
there is a right triangle in our cone which its smallest side is $\frac{r\theta}{2\pi}$, its vertical side is the cone's height and its hypotenuse (cone's lateral side) is $r$ (sector's radius).
use the Pythagorean rule to find the height. It will be $\frac{r}{2\pi} \sqrt{4\pi^2-\theta^2}$.
now you can find the volume: $V=\frac{1}{3} \pi R^2 h$ which will be $\frac{r^3\theta^2}{24\pi^2}\sqrt{4\pi^2-\theta^2}$.
note that $\theta$ is in radians here. so if you want to put it in degrees, you should write $180$ instead of $\pi$.


text:
Q: Evaluate expression in parentheses, in String In Java, if I have a string like "(3+5)x + x^(6/2)", how could I replace all expressions in parentheses with their evaluations, to get the string "8x + x^3"?

A: It depends on what you are trying to do. For more complex cases, you could/should use a parser generator like ANTLR. If the expressions are not more complex then your examples (simple arithmetics), you could just try to analyze the expressions with JavaScript/Nashorn.
Using the solution of Use the backreference in a regex to replace a text dynamically you could do:
public static void main(String[] args) throws ScriptException {

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    String x = "(3+5)x + x^(6/2)";

    // can also be extended to expressions like 3+5*5 with
    // Pattern.compile("\\(\\d+([+/*-]\\d+)+\\)")
    Pattern simpleArithmeticExpr = Pattern.compile("\\(\\d+[+/]\\d+\\)");
    Matcher matcher = simpleArithmeticExpr.matcher(x);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String expr = matcher.group();
        String evaluatedExpr = String.valueOf(engine.eval(expr));
        matcher.appendReplacement(sb, evaluatedExpr );
    }
    matcher.appendTail(sb);
    System.out.println(sb); // 8x + x^3

}

If the Javascript solution is to slow/heavyweight, you could also parse it yourself.


text:
Q: MS Bot composer custom action sample returns null reference exception I've tried to implement the custom action sample (multiply) for the MS bot composer as seen here. I followed all the steps and copied the code, but when I try to execute the action on the bot, I get a System.NullReferenceException with the following stack trace:
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ReplaceDialog.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.OnNextActionAsync(DialogContext dc, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.ResumeDialogAsync(DialogContext dc, DialogReason reason, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.EndDialogAsync(Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.SetProperty.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.OnNextActionAsync(DialogContext dc, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.ResumeDialogAsync(DialogContext dc, DialogReason reason, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.EndDialogAsync(Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.SendActivity.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.ContinueActionsAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.ReplaceDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ReplaceDialog.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.OnNextActionAsync(DialogContext dc, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.ResumeDialogAsync(DialogContext dc, DialogReason reason, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.EndDialogAsync(Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.SetProperty.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.OnNextActionAsync(DialogContext dc, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.ResumeDialogAsync(DialogContext dc, DialogReason reason, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.EndDialogAsync(Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.SendActivity.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.ContinueActionsAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.ReplaceDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ReplaceDialog.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.OnNextActionAsync(DialogContext dc, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.ResumeDialogAsync(DialogContext dc, DialogReason reason, Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.EndDialogAsync(Object result, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.SetProperty.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.ReplaceDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.IfCondition.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginActionAsync(DialogContext dc, Int32 offset, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.Actions.ActionScope.BeginDialogAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.BeginDialogAsync(String dialogId, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.ContinueActionsAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.ContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.ContinueDialogAsync(CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.ContinueActionsAsync(DialogContext dc, Object options, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialog.ContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogContext.ContinueDialogAsync(CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogExtensions.InnerRunAsync(ITurnContext turnContext, String dialogId, DialogContext dialogContext, CancellationToken cancellationToken)
   at Microsoft.Bot.Builder.Dialogs.DialogExtensions.InternalRunAsync(ITurnContext turnContext, String dialogId, DialogContext dialogContext, DialogStateManagerConfiguration stateConfiguration, CancellationToken cancellationToken)

Does somebody know what went wrong here? As far as I know, I followed the tutorial as close as possible.

A: Check that you didn't forget to add component to appsettings.json
"components": [
  {
    "name": "YourCustomActionName"
  }
]

A: Please follow these steps to solve this error System.NullReferenceException
Add the following additional packages to your project file
<PackageReference Include="Microsoft.Bot.Builder.Dialogs.Adaptive" Version="4.9.1"/>

<PackageReference Include="Microsoft.Bot.Builder.Dialogs.Declarative" Version="4.9.1"/>

Update DefaultActivityHandler

Declare two new local variables
protected readonly DialogManager _dialogManager;
protected readonly ResourceExplorer _resourceExplorer;

Update the constructor to includes the following lines
_resourceExplorer = serviceProvider.GetService<ResourceExplorer>();
_dialogManager = new DialogManager(dialog);
_dialogManager.UseResourceExplorer(_resourceExplorer);
_dialogManager.UseLanguageGeneration();

Update the OnTurnAsync handler to use _dialogManager in place of _dialog
await _dialogManager.OnTurnAsync(turnContext, cancellationToken: cancellationToken);

Reference:
https://microsoft.github.io/botframeworksolutions/skills/handbook/experimental-add-composer/
https://www.youtube.com/watch?v=QZJRtyYP0hY
https://github.com/rvinothrajendran/BotTutorialSample


text:
Q: Remove invalid entry from Windows 10 start menu I download Eclipse and ran the installer - at some point in time this was created in my start menu, and I can not simply search for Eclipse to launch it.

The actual installer this references had been deleted, and I can not primary, nor secondary click on the entry. It does absolutely nothing.
I have made sure that nothing exists in either

%AppData%\Microsoft\Windows\Start Menu
  C:\ProgramData\Microsoft\Windows\Start Menu

Despite all attempts to even search the registry, I can not figure out where this is coming from.
How can I remove this entry from my start menu so that when I search for Eclipse, the real entry, Eclipse Jee Oxygen, is the one recommended?


text:
Q: Problem with passing folder path string to web service function via jQuery.ajax I need to perform asp.net web-service function call via jQuery and pass asp.net application path to it. That's the way I'm trying to do it (code is located within asp.net page, e.g. aspx file):
    var d = "{'str':'<%=System.DateTime.Now.ToString() %>', 'applicationPath':'<%=GetApplicationPath() %>'}";

    $.ajax({ type: "POST",
        url: "http://localhost/testwebsite/TestWebService.asmx/Test",
        data: d,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        },
        success: function (msg) {

        }
    });

That's what GetApplicationPath method looks like:
protected string GetApplicationPath()
{
    return HttpUtility.HtmlEncode(Request.PhysicalApplicationPath);
}

And here is a header of web-service function which I'm trying to call:
public void Test(string str, string applicationPath)

Function call works well, but applicationPath parameter doesn't passed correctly. When I debug it I see that backslashes are removed, function gets "C:ProjectsSamplesmytestwebsite" instead of "'C:\Projects\Samples\mytestwebsite\'".
How can I overcome this?

A: OK give this a shot, I tried it (works on my machine).
protected string GetApplicationPath()
{
    return Request.PhysicalApplicationPath.Replace(@"\", @"\\");
}

Then for the javascript stuff. Here I'm using the JSON JavaScript library to make escaping things easier.
// construct object literal to be JSON-stringified
var d = {
    str: "<%=System.DateTime.Now.ToString() %>",
    applicationPath: "<%=GetApplicationPath() %>"
};

$.ajax({ type: "POST",
    url: "http://localhost/testwebsite/TestWebService.asmx/Test",
    data: JSON.stringify(d),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    error: function (xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
    },
    success: function (msg) {

    }
});

A: Backslashes need to be escaped in JavaScript.  Try doing a replace of "\" with double backslashes "\ \" (minus the space):
protected string GetApplicationPath()
{
    return Request.PhysicalApplicationPath.Replace("\", "\\");
}

I don't think you need the HTMLEncode part.


text:
Q: Do declared properties require a corresponding instance variable? Do properties in Objective-C 2.0 require a corresponding instance variable to be declared? For example, I'm used to doing something like this:
MyObject.h
@interface MyObject : NSObject {
NSString *name;
}
@property (nonatomic, retain) NSString *name;
@end

MyObject.m
@implementation
@synthesize name;
@end

However, what if I did this instead:
MyObject.h
@interface MyObject : NSObject {
}
@property (nonatomic, retain) NSString *name;
@end

Is this still valid? And is it in any way different to my previous example?

A: If you are using the Modern Objective-C Runtime (that's either iOS 3.x or greater, or 64-bit Snow Leopard or greater) then you do not need to define ivars for your properties in cases like this.
When you @synthesize the property, the ivar will in effect be synthesized also for you. This gets around the "fragile-ivar" scenario. You can read more about it on Cocoa with Love

A: it works both ways but if you don't declare them in the curly braces, you won't see their values in the debugger in xcode.

A: In your interface, you can formally declare an instance variable between the braces, or via @property outside the braces, or both. Either way, they become attributes of the class. The difference is that if you declare @property, then you can implement using @synthesize, which auto-codes your getter/setter for you. The auto-coder setter initializes integers and floats to zero, for example. IF you declare an instance variable, and DO NOT specify a corresponding @property, then you cannot use @synthesize and must write your own getter/setter.
You can always override the auto-coded getter/setter by specifying your own. This is commonly done with the managedObjectContext property which is lazily loaded. Thus, you declare your managedObjectContext as a property, but then also write a -(NSManagedObjectContext *)managedObjectContext method. Recall that a method, which has the same name as an instance variable/property is the "getter" method.
The @property declaration method also allows you other options, such as retain and readonly, which the instance variable declaration method does not. Basically, ivar is the old way, and @property extends it and makes it fancier/easier. You can refer to either using the self. prefix, or not, it doesn't matter as long as the name is unique to that class. Otherwise, if your superclass has the same name of a property as you, then you have to say either like self.name or super.name in order to specify which name you are talking about.
Thus, you will see fewer and fewer people declare ivars between the braces, and instead shift toward just specifying @property, and then doing @synthesize. You cannot do @synthesize in your implementation without a corresponding @property. The Synthesizer only knows what type of attribute it is from the @property specification. The synthesize statement also allows you to rename properties, so that you can refer to a property by one name (shorthand) inside your code, but outside in the .h file use the full name. However, with the really cool autocomplete that XCode now has, this is less of an advantage, but is still there.
Hope this helps clear up all the confusion and misinformation that is floating around out there.

A: From the documentation:
In general the behavior of properties is identical on both modern and legacy runtimes (see "Runtime Versions and Platforms" in Objective-C Runtime Programming Guide). There is one key difference: the modern runtime supports instance variable synthesis whereas the legacy runtime does not.
For @synthesize to work in the legacy runtime, you must either provide an instance variable with the same name and compatible type of the property or specify another existing instance variable in the @synthesize statement. With the modern runtime, if you do not provide an instance variable, the compiler adds one for you.

A: If you are using XCode 4.4 or later it will generate instance variable synthesizing code for you.
You just have to declare properties like below; it will generate synthesizing code and instance variable declaring code for you.
@property (nonatomic, strong) NSString *name;

it will generate synthesizing code as
@synthesize name = _name;

and you can access instance variable using _name
it is similar to declare
NSString* _name

but if you declare read-only property it like
@property (nonatomic, strong, readonly) NSString *name;

it will generate code
@synthesize name;

or
@synthesize name = name;

So you should access instant variable name with out prefix "_"
any way you can write your own synthesizing code then compiler will generate code for you.
you can write
@synthesize name = _name;

A: The Objective-C Programming Language: Property Implementation Directives

There are differences in the behavior of accessor synthesis that depend on the runtime (see also "Runtime Difference"):

*

*For the legacy runtimes, instance variables must already be declared in the @interface block of the current class. If an instance variable of the same name as the property exists, and if its type is compatible with the property's type, it is used—otherwise, you get a compiler error.

*For the modern runtimes (see "Runtime Versions and Platforms" in Objective-C Runtime Programming Guide), instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.


text:
Q: SQL запрос для простой рекомендательной системы. Каждая запись в таблице movies имеет:
user - пользователь
movie    - фильм
rating - рейтинг данного пользователя для данного фильма
Пользователь 1 хочет получить рекомендации (то есть список фильмов) от группы пользователей 2,3,4,5,6,7.
Полученные фильмы НЕ должны встречаться среди фильмов пользователя 1 и
  должны иметь средний рейтинг в данной группе пользователей не меньше чем 3. При этом фильмы, которые посмотрело менее 3-х человек из группы, не могут быть рекомендованы.
Вот мой вариант, но он не отражает последнего требования:
SELECT t2.movie
FROM movies t1 INNER JOIN movies t2
     ON t1.user = 1
     AND t2.user IN(2,3,4,5,6,7)
     AND t2.movie NOT IN ( SELECT movie
                           FROM movies
                           WHERE user = 1 )
  GROUP BY(t2.movie)
  HAVING AVG(t2.rating)>=3

Пробовал добавлять перед группировкой вот это:
AND COUNT(DISTINCT t2.user, t2.movie)>3

Пишет, что неправильно использую группы.
           Как же отфильтровать результаты, которые встречаются в группе менее 3-х раз?

A: SELECT t2.movie
FROM movies t1 INNER JOIN movies t2
     ON t1.user = 1
     AND t2.user IN(2,3,4,5,6,7)
     AND t2.movie NOT IN ( SELECT movie
                           FROM movies
                           WHERE user = 1 )
GROUP BY(t2.movie)
HAVING AVG(t2.rating)>=3
AND  COUNT(DISTINCT t2.user) >= 3


text:
Q: How can I change my IP using selenium WebDriver Chrome I am parsing one site, but when I go in lately it gives the following: your IP is blocked or you send requests too often. I work with Selenium and WebDriver Chrome. Can I somehow change my IP to get around this limitation?

A: Selenium have no abilities to change your IP address.
This can be done with other tools / libraries.


text:
Q: How to hide the _cts folder in all document libraries? In one existing site collection all document libraries are suddenly showing the _cts folder.
Any idea how to fix it?

A: -cts folder belongs to so-called hidden URL structure of a sharepoint web site.
By default only users that (or who) are members of the Site Owners group and Designers group see it (as well as All Files tab in Sharepoint Designer 2010).
In Sharepoint Foundation the Designers group is not created by default at all.
Site collection administrators also can be limited but at the site collection but web app level.
At site collection level
these settings are configured, in browser, at top level site of site collection (navigate to root site of site collection) > Site Actions > Site Settings > Allow Site Owners and Designers to See the Hidden URL structure of their Web Site .
At web app level
it is configured in Windows Start > All Programs > Microsoft Sharepoint 2010 Products > Sharepoint 2010 Central Administration > Manage Web Applications under Application Management section > choose a specific web application > on ribbon, the Web Applications tab (under Manager group section)

A: For others searching for an answer to this problem, we eventually fixed the issue like this:
In the list definition where you define the content types, in the targetName attribute we were specifying the content type name like this: "_cts/MyContentType"
We've changed it to exclude the "_cts" part and now the issue no longer shows up (and functionality still works as expected)
<ContentTypes>
     <ContentTypeRef ID="0x010060000000000000000000000000">
         <Folder TargetName="MyContentType" />
     </ContentTypeRef>
</ContentTypes>

EDIT: This fixes the issue on newly created sites, to remove it on existing sites you need to remove them manually (or use a PowerShell script).

A: I thought that _cts virtual directory is for site only, maybe you activate new content type or document set via feature for whole site. Is it accessible for users? Is it empty?

A: Try using Request Filtering in IIS, click the hidden segments tab, and add _cts.
HTH


text:
Q: Fill ArrayList from Text file with multiple element types Java I want to fill an Arraylist from a .txt file however, the ArrayList contains objects (items) with multiple 'variables'.
The class Item 'variables' are String & boolean.
public Item(String aName, String aDescription, boolean canTake) {

This is what I have in a different class to create/fill the ArrayList
public List<Item> loadItems() throws FileNotFoundException{
    File f = new File("Item.txt");
      Scanner sn = new Scanner(f);
         while (sn.hasNext()){
            String itm = sn.nextLine();
            Scanner sc = new Scanner(itm);
            sc.useDelimiter("#");
            String aName = sc.next();
            String aDescription=sc.next();
            Boolean canTake = sc.nextBoolean();
            addItem(aName, aDescription, canTake);
                }
                return items;
            }

In a third class I create another ArrayList and call the loadItems() method so that I can reference specific item objects (i.e. item objects at element 0 of the list).
    public Actions() throws FileNotFoundException {
        loadItems();
        this.itemSlist = loadItems();

ItemList HomeList = new ItemList();
        HomeList.add(itemSlist.get(0));
        HomeList.add(itemSlist.get(1));

The problem is this doesn't actually fill the ArrayList & my output is: [] [] [] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 0
I know with ArrayLists you would generally just list.add(); but there a multiple variables for each object - not just a string or boolean value.
I've tried moving the loadItems method to different classes and tried using a basic scanner with the txtfile and can access single word item objects but not the multi variable ones.

A: Try the following approach:
public class Main{

    public static void main(String[] args) {

        ArrayList<Item> listItem = new List().getList();
        System.out.println("Name: " + listItem.get(0).getaName());
        System.out.println("Description: " + listItem.get(0).getaDescription());
        System.out.println("CanTake: " + listItem.get(0).isCanTake());

    }
}

Class List:
public class List {

           public ArrayList<Item> getList(){

                ArrayList<Item> listItems = new ArrayList<>();
                    listItems.add(new Item("Name 1", "Description 1", true));
                    listItems.add(new Item("Name 2", "Description 2", false));
                    listItems.add(new Item("Name 3", "Description 3", true));
                    listItems.add(new Item("Name 4", "Description 4", false));
                    listItems.add(new Item("Name 5", "Description 5", false));
                return listItems;
            }
    }

Class Item:
public class Item {

    private String Name;
    private String Description;
    private boolean CanTake;

    public Item(String Name, String Description, boolean CanTake) {
        this.Name = Name;
        this.Description = Description;
        this.CanTake = CanTake;
    }

    public String getaName() {
        return Name;
    }

    public void setaName(String aName) {
        this.Name = aName;
    }

    public String getaDescription() {
        return Description;
    }

    public void setaDescription(String aDescription) {
        this.Description = aDescription;
    }

    public boolean isCanTake() {
        return CanTake;
    }

    public void setCanTake(boolean canTake) {
        this.CanTake = canTake;
    }

}

Results:
run:
Name: Name 1
Description: Description 1
CanTake: true
BUILD SUCCESSFUL (total time: 0 seconds)

I haven't checked the import of the txt file
Steffi


text:
Q: Maximo anywhere - how to install certificate for applicationcenter in order to install apps on iOS? I'm sure that someone must have done this and I hope they can share their solution here.
I have successfully installed Maximo 7.6 and built and deployed Maximo Anywhere 7.5.2 apps on mac. I can see my apps when i type the URL to the applicationcenter on my iPad. The last step, according to IBM, is: "To install applications on iOS devices, you must first configure the Application Center server with SSL".
I'm using Websphere 8.5.5 and Maximo is accessible on port 9080 (or 80, using webserver) and MobileFirst is on 9081.
If i get the certificate and install it somehow (following IBM instructions did not get me far, but that is not important, yet) - what would be the the url where i can find my applicationcenter?
At the moment i can access it on http://mycomputer:9081/applicationcenter but i can't install apps.
So, I have the following 2 questions:
1. If i secure it via SSL will it be on the same port only with https instead of http, i.e. https:/mycomputer:9081/applicationcenter?
2. Can you get the certificate from any CA at all for "mycomputer"? (tried CAcert since they are not charging, but they try to validate the name by sending email to admin@mycomputer which obviously is not going to work)
Thank you in advance.
Cheers,
Pierre

A: *

*No, it will be on a different port.  There should be lots of information out there on how to configure WebSphere securely that you can follow.

*No, you actually have to use a certificate that has a valid common name built into it that matches the hostname that you're deploying to.

If you're just looking to run some development unit tests of the application, you can push the ipa to your device using ITunes or XCode instead of using the application center to install the application on your device.

A: We've had similar issues.
Created Self Signed CA via openSSL but really need one from a CA so that the certificate doesn't have to be installed onto iOS devices.
Making 9081 secure is easy enough by going into the server ports and making default secure 9081 instead of 9443 for the worklight/mobile first server
We found https://www.diawi.com/ a good way of quickly deploying the ipa to devices since its https secured rather than applicationcenter/installers.html


text:
Q: checkbox return only false even it is checked in Jquery I submit the form while change dropdown option.After submit the form i redirect in to same page.
I submit the form Using below function:
function submitform(){
    //Below variables are checkbox value
    var addresscheck = $('#addressmatchedCheck').is(':checked');
    var rcnumbercheck =  $('#rcnumbermatched').is(':checked');
    var phonenumbercheck = $('#phonenumbercheck').is(':checked');
    var idproofcheck = $('#idproofcheck').is(':checked');
    var guarantoraddresscheck = $('#guarantoraddressmatchedCheck').is(':checked');
    var guarantoridcheck = $('#guarantoridproofcheck').is(':checked');
    var guarantorrelationcheck = $('#guarantorrelationshipCheck').is(':checked');
    if( addresscheck &  rcnumbercheck & phonenumbercheck & idproofcheck  & guarantoraddresscheck & guarantoridcheck & guarantorrelationcheck) {
                $('#statusid').val(1);
                alert($('#statusid').val() + "if");
    }
    else{
        $('#statusid').val(2);
        alert($('#statusid').val() + "else");
    }
    $('#fieldVerificationFormID').attr('method', 'POST');
    $('#fieldVerificationFormID').attr('action', '/mfi/api/1.0/client/ci/groups/member/fieldverification/insert');
    $('#fieldVerificationFormID').submit();
}

My problem is checkbox return only false even it is checked?
First time i.e before form submit it works exactly.Issue is after form submission.
can anyone sove my issue?

A: This is what I use. I have a function that extends JQuery with an isChecked() function. I made this ages ago before the :checked was available in the selectors. But it's pretty bulletproof.
jQuery.fn.isChecked = function() {
    var isChecked = false;
    this.each(function(){
        if (this.checked) {
            isChecked = true;
            return;
        }
    });
    return isChecked;
}

function check() {
    var addressCheck = $('#addressmatchedCheck').isChecked();
}

A: If you name your checkboxes like this, it works:
<input type="checkbox" id="addressmatchedCheck" checked="checked" />
<input type="checkbox" id="rcnumbermatched" checked="checked" />
<input type="checkbox" id="phonenumbercheck" checked="checked" />
<input type="checkbox" id="idproofcheck" checked="checked" />
<input type="checkbox" id="guarantoraddressmatchedCheck" checked="checked" />
<input type="checkbox" id="guarantoridproofcheck" checked="checked" />
<input type="checkbox" id="guarantorrelationshipCheck" checked="checked" />

Demo: http://jsfiddle.net/Guffa/DqdgC/


text:
Q: GCM push notification not working in Android Phonegap application Am working in HTML5 Phonegap android GCM push notification application.
But I tried several times but not getting any results :-(
Please help me.. Am trying this to work from last three days.
Am using Push plugin : com.phonegap.plugins.PushPlugin
** My Js code:
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady()
{
    alert('deviceready');

// result contains any message sent from the plugin call
    var app = {
    successHandler: function(result) {
        alert('Callback Success! Result = '+result)
    },
    errorHandler:function(error) {
        alert(error);
    },
    onNotificationGCM: function(e) {
        alert('onNotificationGCM');
            switch( e.event )
            {
                case 'registered':
                    if ( e.regid.length > 0 )
                    {
                        console.log("Regid " + e.regid);
                        alert('registration id = '+e.regid);
                    }
                break;

                case 'message':
                  // this is the actual push notification. its format depends on the data model from the push server
                  alert('message = '+e.message+' msgcnt = '+e.msgcnt);
                break;

                case 'error':
                  alert('GCM error = '+e.msg);
                break;

                default:
                  alert('An unknown GCM event has occurred');
                  break;
            }
        }
    }
    setTimeout(function(){
        var pushNotification = window.plugins.pushNotification;
        pushNotification.register(app.successHandler, app.errorHandler,{"senderID":"236728063055","ecb":"app.onNotificationGCM"});
    },2000);

}

** Manifest file
<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="com.test.pushDummy" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="CordovaApp" android:theme="@android:style/Theme.Black.NoTitleBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:exported="true" android:name="com.plugin.gcm.PushHandlerActivity" />
        <receiver android:name="com.plugin.gcm.CordovaGCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.test.pushDummy" />
            </intent-filter>
        </receiver>
        <service android:name="com.plugin.gcm.GCMIntentService" />
    </application>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.test.pushDummy.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.test.pushDummy.permission.C2D_MESSAGE" />
</manifest>

A: Try moving that var app functions outside device ready. It will work.


text:
Q: Oauth Spotify API with PHP I have been working with the Spotify API. I want to perform some actions on playlists, these require a user to login. I want to execute the following url so as I can get an authorization bearer:
https://accounts.spotify.com/authorize/?client_id=CLIENT_ID&response_type=token&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback&scope=user-read-private%20playlist-modify-public&state=34fFs29kd09
When I execute this in a browser URL field, it works fine and will return an authorization token. I f i try to execute this from an index.php file however I run into problems.
<?php
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
$output = curl_exec($curl);
curl_close($curl);
?>

When i run the file, the spotify login page will appear. However, after I enter my login details and hit enter nothing happens.
The console in the browser reports the following error:
POST http://localhost:8888/api/login 404 (Not Found)
TypeError: Cannot create property 'error' on string '

<title>404 Not Found</title>

Not Found

The requested URL /api/login was not found on this server.

I have added a .htaccess to the folder as well as change the Directory AllowOverride to All in the httpd.conf file in my mamps server. There are multiple AllowOverrides and I am not 100% sure which one to change.
If it isn't obvious by now, I am copmletly lost when it comes to this so any help would be gratefully appreciated.

A: Are your sure that page on localhost exists on that port? Is that page white listed on your dev-account on spotify?
You can also try this package from jwilsson, this way you don't have to fight whith the whole oauth process.


text:
Q: recaptcha show blank space in bootstrap 3 bottom page I work with bootstrap 3 login page and add recaptcha too this. now before load complete my page i see blank page in bottom for load recaptcha.
Recaptcha:

                            reCAPTCHA

Incorrect please try again

                            Enter the words above:
                            Enter the numbers you hear:

                                    <input type="text" id="recaptcha_response_field" name="recaptcha_response_field" class="input-recaptcha" />

                        <iframe src="<?php echo $recaptcha_noscript_url; ?>" height="300" width="500" frameborder="0">

                        <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
                        <input type="hidden" name="recaptcha_response_field" value="manual_challenge">

        </form>

            <iframe src="<?php echo $recaptcha_noscript_url; ?>" height="300" width="500" frameborder="0">

            <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
            <input type="hidden" name="recaptcha_response_field" value="manual_challenge">

how do fix this ?
DEMO (click in run and see problem) Fiddle
Pic:

A: This can happen if you don't acquire and add your RECAPTCHA API Key.


text:
Q: Is passing the _setTitle method with the props the way to go? want to update the title present in the Header
    everytime we navigate to a new page.
    Is passing the _setTitle method with the props the way to go?
import React, { Component } from 'react';
import PropTypes from 'prop-types';

Main App component
export class App extends Component {
  constructor() {
    super();

    this.state = { pageTitle: 'My app' };
    this._setTitle = this._setTitle.bind(this);
  }

  _setTitle(title) {
    this.setState({ pageTitle: title });
  }

  render() {
    const { pageTitle } = this.state.pageTitle;

    return (

        {React.cloneElement(children, { setTitle: this._setTitle })}

    );
  }
}

Header and Footer Components
export class Header extends Component {
  static propTypes = {
    title: PropTypes.string
  };
  // ...
  render() {
    const { title } = this.props;

    return
{title}
;
  }
}

export class Footer extends Component {
  // Footer code
}

Following are the different page Components:
export class Profile extends Component {
  static propTypes = {
    setTitle: PropTypes.func.isRequired
  };
  componentWillMount() {
    this.props.setTitle('Profile');
  }
}

export class Projects extends Component {
  static propTypes = {
    setTitle: PropTypes.func.isRequired
  };
  componentWillMount() {
    this.props.setTitle('Projects');
  }
  // ...
}

export class ProjectForm extends Component {
  static propTypes = {
    setTitle: PropTypes.func.isRequired
  };
  componentWillMount() {
    this.props.setTitle('New Project');
  }
  // ...
}

export class Translators extends Component {
  static propTypes = {
    setTitle: PropTypes.func.isRequired
  };
  componentWillMount() {
    this.props.setTitle('Translators');
  }
  // ...
}

// ...

How can I improve upon this. I'm new to react so pls suggest If you have any ideas, I'll implement it. Thank you.

A: You can make use of Context and pass the setTitle method as a Context value, then you can create a Component that has the logic of setting the Title, A simple implementation would look like
const TitleContext = React.createContext();

export class App extends Component {
  constructor() {
    super();

    this.state = { pageTitle: 'My app' };
    this._setTitle = this._setTitle.bind(this);
  }

  _setTitle(title) {
    this.setState({ pageTitle: title });
  }

  render() {
    const { pageTitle } = this.state.pageTitle;

    return (
      <TitleContext.Provider value={{setTitle: this._setTitle}}

          {this.props.children}

     </TitleContext.Provider>
    );
  }
}

class TitleSetter extends React.Component {
    static propTypes = {
        title: PropTypes.string.isRequired
    }
    componentDidMount() {
        this.context.setTitle(this.props.title)
    }
}

TitleSetter.contextTypes = TitleContext;

Now in any component you can simply render the TitleSetter like
export class Profile extends Component {
  render() {
    return (

              <TitleSetter title="Profile" />
              {/* other context */}

    )
  }
}

Also while looking into context, please look at the this question on how to access context outside of render


text: Q: MS SQL Server when record insert how to give push notification in android app through Soap API in C#.net My Database in MS SQL Server when Record insert or data Updated how to give Push notification in android app, i don't know. SOAP API Create in Visual Studio C#.net. SOAP API through Data give in JSON From MS SQL Server Database. This JSON Data Used in android app.


text:
Q: bash script copying lines from multiple files with some additional conditions I have multiple files which have the same structure but not the same data. The names are 20140101.log, 20140102.log,… Each of these files contains at the end lines like:
**# observed meteors       : 60**

Perseids (PER)           : #=54  b=-1.0 mag  ECA=1608.3 km^2*h  FLX=33.6 /(10^3*km^2*h)

Sporadics (SPO)          : #=3  b=-0.8 mag  ECA=171.6 km^2*h  FLX=17.5 /(10^3*km^2*h)

S-delta-Aquarids (SDA)   : #=2  b=-0.7 mag  ECA=69.3 km^2*h  FLX=28.9 /(10^3*km^2*h)

kappa-Cygnids (KCG)      : #=1  b=-1.2 mag  ECA=369.8 km^2*h  FLX=2.7 /(10^3*km^2*h)

From each of these files I would like to extract all lines followed by line "# observed meteors       : " to another file. In addition I would like to append to each of these line data taken from filename. So target file should contain only lines like these:
20140101    Perseids (PER)           : #=54  b=-1.0 mag  ECA=1608.3 km^2*h  FLX=33.6 /(10^3*km^2*h)

20140101    Sporadics (SPO)          : #=3  b=-0.8 mag  ECA=171.6 km^2*h  FLX=17.5 /(10^3*km^2*h)

Stepping further. I have 2 variables in my script:
$katalog=pav13 and $katalog_daty=20140101.

What I would like to get is the line like this:
pav13 20140101    Perseids (PER)           : #=54  b=-1.0 mag  ECA=1608.3 km^2*h  FLX=33.6 /(10^3*km^2*h)

Using
awk '/^# observed meteors/{s=1;i=1;next} i{print '$katalog_daty', $0;next}' 20140101.log

gives
20140101    Perseids (PER)           : #=54  b=-1.0 mag  ECA=1608.3 km^2*h  FLX=33.6 /(10^3*km^2*h)

but I cannot find out how to include $katalog to the beginning of line. This doesn't work
awk '/^# observed meteors/{s=1;i=1;next} i{print '$katalog' '$katalog_daty', $0;next}' 20140101.log

A: Using awk you can do:
awk '/^# observed meteors/{s=1;i=1;next} i{print FILENAME, $0;next}' 20140101
20140101 Perseids (PER)           : #=54  b=-1.0 mag  ECA=1608.3 km^2*h  FLX=33.6 /(10^3*km^2*h)
20140101 Sporadics (SPO)          : #=3  b=-0.8 mag  ECA=171.6 km^2*h  FLX=17.5 /(10^3*km^2*h)
20140101 S-delta-Aquarids (SDA)   : #=2  b=-0.7 mag  ECA=69.3 km^2*h  FLX=28.9 /(10^3*km^2*h)
20140101 kappa-Cygnids (KCG)      : #=1  b=-1.2 mag  ECA=369.8 km^2*h  FLX=2.7 /(10^3*km^2*h)
20140101 Antihelion (ANT)         : #=0  b=--- mag  ECA=164.1 km^2*h  FLX=0.0 /(10^3*km^2*h)
20140101 alpha-Capricornids (CAP) : #=0  b=--- mag  ECA=572.8 km^2*h  FLX=0.0 /(10^3*km^2*h)

UPDATE: To pass variables to awk from shelL;
awk -v katalog="$katalog" -v katalog_daty="$katalog_daty" '/^# observed meteors/{
   s=1;i=1;next} i{print katalog, katalog_daty, $0; next}' 20140101.log


text:
Q: Use mini-frames in sidebar outer theme after a little bit working, I found that Singapore style is preferable for my needs. Anyway the problem is still there.
I tried to include the mini-frame bullets in the sidebar using
\useoutertheme[subsection=false]{miniframes}
I added it to the preamble of my swp, which now looks like:
\newenvironment{stepenumerate}{\begin{enumerate}[<+->]}{\end{enumerate}}
\newenvironment{stepenumerate}{\begin{enumerate}[<+->]}{\end{enumerate}}
\newenvironment{stepitemize}{\begin{itemize}[<+->]}{\end{itemize} }
\newenvironment{stepenumeratewithalert}{\begin{enumerate}[<+-| alert@+>]}{\end{enumerate}}
\newenvironment{stepitemizewithalert}{\begin{itemize}[<+-| alert@+>]}{\end{itemize}}
\usetheme{Singapore}
\definecolor{unime}{rgb}{.93,.9,.0}
\usecolortheme[named=unime]{structure}
\setbeamerfont{footnote}{size=\tiny}
\useoutertheme{split}
\setbeamertemplate { items } [ball]
\definecolor{lside}{rgb}{.7,.0,.0}
\definecolor{leftFootlineColor}{rgb}{.54,.17, .89}
\useoutertheme{sidebar}
\setbeamercolor{frametitle}{bg=unime}
\setbeamercolor{section in head/foot}{bg=leftFootlineColor}
\logo {\includegraphics[scale=0.35]{uni}}
\setbeamertemplate{sidebar canvas left} [vertical shading]
[top=lside, bottom=lside]
\useoutertheme[subsection=false]{miniframes}
\DeclareGraphicsExtensions{.pdf,.png,.jpg}
\graphicspath{ {c:/} }
\input{tcilatex}

The output looks like this:

What I would like is to have the mini-frames bullets in the sidebar on the left instead of the name of each subsection. This would be more convenient if each section contains many subsections.
I hope I explained my case better now.
Thanks
Dario


text:
Q: Компиляция файла в коде Как можно скомпилировать .cs файл в коде?
Не используя командную строку.

A: Нужно воспользоваться классом CSharpCodeProvider, а также типами из пространства имен System.CodeDom.Compiler:
using Microsoft.CSharp;
using System.CodeDom.Compiler;

...

// компилятор
var codeProvider = new CSharpCodeProvider();
ICodeCompiler compiler = codeProvider.CreateCompiler();

// параметры компиляции
var parameters = new CompilerParameters()
{
    // указываем, что генерируем исполняемый файл (exe)
    GenerateExecutable = true,
    // если хотим сохранить на диск
    OutputAssembly = "...",
    // если хотим сохранить в памяти
    // (хотя файл все равно cгенерируется во временной директории)
    //GenerateInMemory = true
};

// компилируем
var source = File.ReadAll("SomeFile.cs");
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, source);

// проверяем, есть ли ошибки
if (results.Errors.Count > 0)
{
    foreach (CompilerError error in results.Errors)
    {
        Console.WriteLine($"Line number {error.Line}, error number {error.ErrorNumber}: {error.ErrorText}");
    }
}

// если нужно обратиться к скомпилированной сборке,
// используйте свойство results.CompiledAssembly

A: Очень удобно использовать Roslyn https://github.com/dotnet/roslyn
Примеры можно посмотреть здесь
https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples#exprstrong
и здесь
Как программно откомпилировать класс и вызвать его метод?


text:
Q: Setting thesis margins My university requires theses to be bound and printed with the following specification:
There should be a margin of at least 1.5 inches, preferably 2 inches (5cm),
on the left side of the page,
both for typescript and diagrams, to allow for binding. Other margins should
be of at least 1 inch (2.5 cm).

If I plan to double-side print on A4, how can I ensure this in latex?
Would the following in the preamble suffice?
\setlength{\oddsidemargin}{16mm}
\setlength{\textwidth}{140mm}
\setlength{\textheight}{200mm}
\setlength{\topmargin}{8mm}

I found this in someone else's thesis. My understanding is that oddsidemarin sets the left margin for odd-numbered pages, minus 1 inch, so this gives 1 inch(25.5mm)+16mm: 1.63inches on the left side of the odd-numbered pages. Then A4 dimensions are 210mm w x 297mm so
\setlength{\textwidth}{140mm} along with my oddsidemargin means there will be 210-41.5-140=28.5mm=1.11inch left for the right margin of odd-sided pages. Similarly, \setlength{\textheight}{200mm} means there is 297-200=97mm=3.8inches left for both the top and bottom margins, so 1.9inches each. Not sure what \topmargin is doing here.
Do I need to set evensidemargin too? Are the above settings correct to match the university specifications?

A: If you define inner and outer margins instead of left/right or even/odd and use the attributes of the documentclass to switch between oneside and twoside it will be all right. The example below works for me just fine.
\documentclass[oneside]{book}%

\usepackage{geometry}
\usepackage{lipsum}

\newgeometry{
    top=1in,
    bottom=1in,
    outer=1in,
    inner=2in,
}

\begin{document}

\lipsum[1-20]

\end{document}


text:
Q: Unable to add SAML signing option of an Enterprise application in Azure AD through MS Graph API using Java SDK List definitionList = new LinkedList<>();
definitionList.add(
"{ "TokenIssuancePolicy":{"TokenResponseSigningPolicy":"ResponseAndToken","SamlTokenVersion":"2.0","SigningAlgorithm":"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256","Version":1}}");
    TokenIssuancePolicy newPolicy = new TokenIssuancePolicy();
    newPolicy.definition = definitionList;
    newPolicy.displayName = "sample-app";
    newPolicy = serviceClient.policies().tokenIssuancePolicies().buildRequest().post(newPolicy);

    System.out.println("https://graph.microsoft.com/v1.0/policies/tokenIssuancePolicies/"+newPolicy.id);

    TokenIssuancePolicyCollectionWithReferencesPage policyPage = serviceClient.servicePrincipals(principal.id).tokenIssuancePolicies().buildRequest().get();
    List<TokenIssuancePolicy> policyList = policyPage.getCurrentPage();

    System.out.println(policyPage.getCount());
    if (Objects.isNull(policyList) || policyList.isEmpty()) {
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }
    policyList.forEach(app1 -> System.out.println(app1.displayName + "         :  " + app1.id));

    TokenIssuancePolicy policy = new TokenIssuancePolicy();
    policy.additionalDataManager().put("@odata.id", new JsonPrimitivenew JsonPrimitive("https://graph.microsoft.com/v1.0/policies/tokenIssuancePolicies/" + newPolicy.id));
    System.out.println(policy.additionalDataManager());
    serviceClient.servicePrincipals(principal.id).tokenIssuancePolicies().references().buildRequest().post(policy);

Above is the code which Iam trying to update the policy of an Enterprise application but ending up with an Invalid object identifier 'null'.
Could anyone help me on this.
Thanks in advance.
enter image description here

A: According to my test, we cannot use the code TokenIssuancePolicy policy = new TokenIssuancePolicy(); policy.additionalDataManager().put("@odata.id", new JsonPrimitivenew JsonPrimitive("https://graph.microsoft.com/v1.0/policies/tokenIssuancePolicies/" + newPolicy.id)); to create a new policy. We need to update code as below
TokenIssuancePolicy policy = new TokenIssuancePolicy(); policy.id=tokenIssuancePolicy.id;
For example
 TokenIssuancePolicy tokenIssuancePolicy = new TokenIssuancePolicy();
        LinkedList<String> definitionList = new LinkedList<String>();
        definitionList.add("{\r\n  \"TokenIssuancePolicy\": {\r\n    \"Version\": 1,\r\n    \"SigningAlgorithm\": \"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256\",\r\n    \"TokenResponseSigningPolicy\": \"ResponseAndToken\",\r\n    \"SamlTokenVersion\": \"2.0\"\r\n  }\r\n}");
        tokenIssuancePolicy.definition = definitionList;
        tokenIssuancePolicy.displayName = "mytest";

        tokenIssuancePolicy= graphClient.policies().tokenIssuancePolicies()
            .buildRequest()
            .post(tokenIssuancePolicy);
        System.out.println("https://graph.microsoft.com/v1.0/policies/tokenIssuancePolicies/"+tokenIssuancePolicy.id);

        TokenIssuancePolicy policy = new TokenIssuancePolicy();
        policy.id=tokenIssuancePolicy.id;

         policy =graphClient.servicePrincipals("00964c82-a7c2-4675-bbed-54bcf16328b3").tokenIssuancePolicies().references()
                .buildRequest()
                .post(policy);
        System.out.println("-----------"+policy.id);


text:
Q: Two sum algorithm variant - Optimization I need to compute the number of target values t in the interval [-10000,10000] (inclusive) such that there are distinct numbers x,y in the input file that satisfy x+y=t. I have the code which does work and would like to optimize it to run it faster.
Also, we'll count the sum t only once. If there are two x,y pairs that add to 55, you will only increment the result once. Input numbers could be both positive and negative integers.
public static int Calculate(int start, int finish, HashSet<long> numbers)
{
    int result = 0;
    for (int sum = start; sum <= finish; sum++)
    {
        foreach (long n in numbers)
        {
            if (numbers.Contains(sum - n) && n != (sum - n))
            {
                result++;
                break;
            }
        }
    }

    return result;
}

This is an assignment and I completed it with full marks. My code is taking like 30 minutes to run against the data set of 1 Million numbers. I tried to think a way to optimize my code, but couldn't get to the right thought and would appreciate some help.

A: There's a classic linear-time algorithm for finding two numbers in a sorted array A that sum to a specified target. Initialize i to the first index and j to the last. If A[i] + A[j] is less than the target, increase i. If it's less than the target, decrease j. Stop when i >= j.
Sorting the array with a comparison sort is asymptotically costlier than hashing, but this setup cost is negligible, and the improved memory layout of the array will yield a significant performance increase.
To optimize further, you can invert the loop structure and, for each number in the array, figure out what combinations it makes.
To optimize further still (at least asymptotically), use a Fourier transform to convolve (sections of) the array with each other. Since your numbers are distinct, I'm not convinced that this will be an improvement in practice.

A: Please have a look following solution:
    public static int Calculate(int start, int finish, List<long> numbers)
    {
        HashSet<long> resultSet = new HashSet<long>();
        for (int indexA = 0; indexA < numbers.Count - 1; indexA++)
        {
            for (int indexB = indexA+1; indexB < numbers.Count; indexB++)
            {
                long tempSum = numbers[indexA] + numbers[indexB];
                if ((tempSum >= start) && (tempSum <= finish))
                {
                    resultSet.Add(tempSum);
                }
            }
        }
        return resultSet.Count();
    }

A: This code can be optimized a lot simply by using a better datastructure. Use a SortedSet instead of a HashSet. Now the code can easily be optimized:
public static int calculate(int start , int finish , SortedSet<long> numbers){
    int count = 0;

    for(long l in numbers){
        SortedSet<long> sub = numbers.GetViewBetween(l - start , l - finish);
        count += sub.Count() - (sub.Contains(l) ? 1 : 0);
    }

    return count;
}

Note that this code might not compile, since i haven't used c# since quite some time. You can even further optimize this code by simply ignoring values, which fulfill number.min() + n > finish or number.max() + n < start.

A: With credits to David Eisenstat, putting it all together into action for the concrete case:
public static int Calculate(this IEnumerable<long> input, int minSum, int maxSum)
{
    var sortedSet = input.AsParallel().Distinct().OrderBy(n => n).ToArray();
    for (int lo = 0, hi = sortedSet.Length - 1; lo < hi;)
    {
        var sum = sortedSet[lo] + sortedSet[hi];
        if (sum < minSum) lo++;
        else if (sum > maxSum) hi--;
        else return 1 + Calculate(sortedSet, lo, hi, minSum, (int)sum - 1) + Calculate(sortedSet, lo, hi, (int)sum + 1, maxSum);
    }
    return 0;
}
private static int Calculate(long[] sortedSet, int lo, int hi, int minSum, int maxSum)
{
    int count = 0;
    for (int targetSum = minSum; targetSum <= maxSum; targetSum++)
    {
        for (int i = lo, j = hi; i < j;)
        {
            var sum = sortedSet[i] + sortedSet[j];
            if (sum < targetSum) i++;
            else if (sum > targetSum) j--;
            else { count++; break; }
        }
    }
    return count;
}

EDIT even better:
public static int Calculate(this IEnumerable<long> input, int minSum, int maxSum)
{
    if (minSum > maxSum) return 0;
    var sortedSet = input.AsParallel().Distinct().OrderBy(n => n).ToArray();
    return CalculateCore(sortedSet, 0, sortedSet.Length - 1, minSum, maxSum);
}
private static int CalculateCore(long[] sortedSet, int lo, int hi, int minSum, int maxSum)
{
    if (minSum > maxSum) return 0;
    int count = 0;
    while (lo < hi)
    {
        var sum = sortedSet[lo] + sortedSet[hi];
        if (sum < minSum) lo++;
        else if (sum > maxSum) hi--;
        else
        {
            count++;
            if (minSum == maxSum) break;
            if (sum - minSum <= maxSum - sum)
            {
                count += CalculateCore(sortedSet, lo, hi - 1, minSum, (int)sum - 1);
                minSum = (int)sum + 1;
                lo++;
            }
            else
            {
                count += CalculateCore(sortedSet, lo + 1, hi, (int)sum + 1, maxSum);
                maxSum = (int)sum - 1;
                hi--;
            }
        };
    }
    return count;
}

A: I believe it can essentially be done in O(NlogN), where N is the number of points to construct the sums with, and assuming M, the range of sums-to-find is small in comparison.
private int CalcSlide(int first, int last, HashSet<long> numbers)
{
  if (last < first)
    return 0;

  // Strategy:
  // running over the input numbers, in ordered fashion from below, we'll scan an "appropriate" sliding window
  // in that same collection to see if we find any sums that we didn't find before.
  // We start out with the lowest number as an "anchor" and determine the HIGHEST number that might be relevant,
  // i.e. that will not sum to beyond "last".
  // Saving that separately, for later use, we scan down until we sum (always with the "anchor") to below "first".
  //
  // We maintain the sums-to-be-found in a hash.
  // As soon as our scan hits a yet-to-be-found sum, we remove it from the hash and update first/last as appropriate.
  // Having completed this cycle we increase the anchor, redetermine the hightest relevant number to start a new scan,
  // (this redetermination starts at the saved previous value, walking down), and then we scan again.
  // Exits occur whever the obvious conditions are fullfilled: there's nothing left to search for, we've nothing left to scan.
  //
  // Time-complexity:
  // Given an input hash set we first construct a sorted array from that: O(nLogn)
  // The subsequent sliding-window-scan procedure is O(N) if we look at scnario's with N (the number of input points) being much larger
  // than the range of sums-to-find. More precisely the worst-case behaviour is O(N M logM), where M is the range of sums to find.
  // (It would be somewhat difficult to construct an scenario where we really have such "worst case behaviour").
  // 1. Obviously, the "outer loop" over the anchor is just "from 1 to N".
  // 2. Computing the upperbound of the scan, for each anchor again, is also linear: it just runs from N-1 down to the anchor
  //    (in separate strides for each anchor).
  // 3. The scan, at each round, is somewhat more complicated. It is potentially long - over all numbers down to the anchor.
  //    However, since all numbers are different (coming from a hashset), the scanwindow can never be larger than the range of sums (yet) to find.
  //    The worst-case behaviour is then O(N*MlogM), where the logM factor arises from having to search for a sum in the hashSet of sums.
  //    Of course, as we find "some" sums on the way, both the search-in-sumHashSet diminishes and the scanwindow gets smaller whenever we find
  //    the current "first" or "last".

  int sumCountOriginal = last - first + 1;

  // Get a sorted array from the provided numbers.
  long[] sortedSet = new long[this.HNumbers.Count];
  int j = 0;
  foreach (long value in HNumbers)
    sortedSet[j++] = value;
  Array.Sort(sortedSet);

  // Create a (relatively small) HashSet from the sums sought.
  // This serves to easily remove items that we find, and then verify if there are any left.
  HashSet<int> HSums = new HashSet<int>();
  for (int sum = first; sum <= last; ++sum)
    HSums.Add(sum);

  int N = sortedSet.Length;

  int jLow = 0;
  int jScanStart = sortedSet.Length - 1;

  while (HSums.Count > 0)
  {
    long xLow = sortedSet[jLow];
    long xScan = sortedSet[jScanStart];

    // decrease jScanStart to get maxSum or less.
    while (jScanStart > jLow + 1 && xScan + xLow > last)
      xScan = sortedSet[--jScanStart];

    // scan until we get below minSum.
    int jScan = jScanStart;
    while (jScan > jLow && xLow + xScan >= first)
    {
      int sum = (int)(xLow + xScan);
      if (HSums.Contains(sum))
      {
        HSums.Remove(sum);

        if (sum == last)
          while (last >= first && !HSums.Contains(last))
            last--;

        if (sum == first)
          while (first <= last && !HSums.Contains(first))
            first++;

        if (last < first)
          return sumCountOriginal;
      }

      xScan = sortedSet[--jScan];
    } // scan

    // next xLow.
    if (++jLow == N - 1 || jScanStart <= jLow)
      return sumCountOriginal - HSums.Count;

  } // there are still unresolved sums.

  // unexpected fall-thru - we should never get here.
  return sumCountOriginal - HSums.Count;
}


text:
Q: GTK3: Mouse vanishes when using drag and drop Im trying to use the inter-widget drag-and-drop functionalities in GTK3 with gtkmm. Im using Windows 7 x64 (msys2) and gcc 5.3.0.
When i start dragging, the mouse cursor vanishes and the DnD icon is shown at the upper left corner of the screen. Is this a bug or is there something wrong in my code?
Here you can see a very small test application with Gtk::CheckButton as drag source and drag destination.
#include <iostream>
#include <gtkmm-3.0/gtkmm.h>

struct DragButton : Gtk::CheckButton{
    DragButton(){
        this->signal_drag_begin().connect([](const Glib::RefPtr<Gdk::DragContext>& ctx){
            ctx->set_icon();
        });
        this->drag_source_set({Gtk::TargetEntry("testdata")});
        this->drag_dest_set({Gtk::TargetEntry("testdata")});

        this->signal_drag_data_get().connect(
            [this](const Glib::RefPtr<Gdk::DragContext>&,Gtk::SelectionData& s,guint,guint ){
                std::cout << "sending data." << std::endl;
            }
        );
        this->signal_drag_data_received().connect(
            [](const Glib::RefPtr<Gdk::DragContext>& c,int,int,const Gtk::SelectionData&,guint,guint time){
                std::cout << "receiving data" << std::endl;
                c->drop_finish(true,time);
            }
        );
    }
};

int main(){
    auto app = Gtk::Application::create("test");
    auto settings = Gtk::Settings::get_default();
    settings->set_property<Glib::ustring>("gtk-font-name","Sans 10");

    Gtk::Window window;
    window.set_default_size(100,50);
    Gtk::Box box;

    for(int i = 0; i < 3; i++){
        box.pack_end(*Gtk::manage(new DragButton));
    }

    window.add(box);
    window.show_all();

    app->run(window);
}

This screenshot shows the output:

A: I noticed the same behaviour here. Even with "official" gnome/gtk applications. For example, let's try to drag&drop widgets in Glade: you will have the same "strange" effect.
I think it's a bug of gtk libraries in Windows, but I can't imagine why this isn't solved yet, considering drag&drop is a very useful and used operation.

A: I found the problem. I found out here that the adwait-icon-theme that is used as a default was not fully windows-compatible. The cursors .cur format were missing. This commit fixed the problem, I had to install the new version of the theme.


text:
Q: How to record a video of a running iOS app for promotional use? I need to know how to record a video of an iOS app running for promotional use. Could anybody please help me with this?

A: Now, with OSX Yosemite, Quick Time Player has a build-in feature that records your iPhone screen.

*

*Connect your phone with your Lightning cable to your mac

*Open Quick Time

*File > New Record

*This will open your webcam stream, but you can select the source on the right of the record button: just choose your iPhone.

*Record.

A: There are two ways you can do this.  If you want to run your app using the iOS Simulator, then you can use audio/video screen capture software such as http://camstudio.org/ or http://www.techsmith.com/camtasia.html.
If you need to record a video of the app running on the iOS device, then that would require a slightly more complicated setup.  You will need Apple TV http://www.apple.com/appletv/ and a DVR.  You would connect the Apple TV to a DVR, then from the DVR you would run an output cable to a TV or monitor.  The iPhone and Apple TV needs to be configured for mirroring.  Afterwards, you should be able to project and see your iOS app running on the screen (over Wi-Fi) while you are recording the running iOS app on the DVR.

A: I suggest this app http://soundstageapp.com/
It captures the app operation in video and provides tools for entire production of the promo video.

A: As far as I know, you can only do this on a jailbroken iOS device. Google for ScreenRecorder.


text:
Q: How to read Firebase document with auto generated document id using Javascript I am trying to read a single document from a Firebase collection using a variable that is populated with the document id. The document id is correct and the document exists in the collection.
When I initiate the code using variable it seems that the read was successful but there is no data in the field I am interested in. (See Code below).

db.collection("Pswref").doc(clpdocid).get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data());
            console.log('yyyyyy - Title from database = >', SingleRecord.title);
            console.log('yyyyyy - Doc id ', clpdocid);
        })
        .catch((error) => {
            console.error('yyyyyy - Error getting document ', error);
        });

However when I hard-code the document id in the get statement all is well and I can access the information needed. (See code below).

db.collection("Pswref").doc("NoA6EBijcgsBIIOZCsWC").get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('xxxxxx - Great document found using fixed id for doc id ',docRef.data());
            console.log('xxxxxx - Title from database = >', SingleRecord.title);
        })
        .catch((error) => {
            console.error('xxxxxx - Error getting document ', error);
        });

The image shows the console.log output as per the script.
NB: You will note that the above queries are exactly the same accept for the doc id reference used and I get a different result as per the output generated via the console.

Can someone help me to understand why this might happen and what the solution might be?
I have commented on the line out giving the error and rerun so that the output in the console can show that the clpdocid is actually correctly populated.(see snipped below)and then output on the new image.

        db.collection("Pswref").doc(clpdocid).get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data());
            //console.log('yyyyyy - Title from database = >', SingleRecord.title);
            console.log('yyyyyy - Doc id ', clpdocid);
        })
        .catch((error) => {
            console.error('yyyyyy - Error getting document ', error);
        });

A: It's certainly the case that clpdocid doesn't actually contain the value you expect.  The undefined that you're printing from docRer.data() is proof that you've requested a document that doesn't exist, since the API documentation for data() says to expect undefined if the document was not found.
Try logging the value of clpdocid before the query to make sure you have the document ID you want.


text:
Q: Cast as Int only when character is a number on Firebird 2.5 I have a query that I use on a MySQL database that orders the result, casting a char database field to integer when possible (when the char string is numeric), so for example the ORDER BY clause that I use on MySQL is:
ORDER BY
   CASE
   WHEN CONVERT(charfield, SIGNED INTEGER) IS NOT NULL THEN
        CAST(charfield AS SIGNED INTEGER)
   ELSE 9999999999 END

Where charfield is a database field character(25).
How can I translate this ORDER BY clause for Firebird 2.5?

A: You could use SIMILAR TO operator, ie
ORDER BY
   CASE
      WHEN charfield SIMILAR TO '[0-9]+' THEN CAST(charfield AS INTEGER)
      ELSE 9999999
   END

If the field has leading or trailing spaces then you have to use TRIM() function to get rid of those before test, ie
WHEN TRIM(charfield) SIMILAR TO ...

And to allow negative numbers you have to modify the pattern to include -, ie the clause would became
ORDER BY
   CASE
      WHEN TRIM(charfield) SIMILAR TO '\-?[0-9]+' ESCAPE '\' THEN CAST(charfield AS INTEGER)
      ELSE 9999999
   END


text:
Q: extract predicted values from Partial least square regression in R I have following:
library(pls)
pcr(price ~ X, 6, data=cars, validation="CV")

it works, but because I have a small dataset, I cannot divide in into training and test and therefore I want to perform cross-validation and then extract predicted data for AUC and accuracy. But I could not find how I can extract the predicted data.Which parameter is it?

A: When you fit a cross-validated principal component regression model with pcr() and the validation= argument, one of the components of the output list is called validation. This contains the results of the cross validation. This in turn is a list and it has a component called pred, which contains the cross-validated predictions.
An example adapted from example("pcr"):
sens.pcr <- pcr(sensory ~ chemical, data = oliveoil, validation = "CV")

sens.pcr$validation$pred

As an aside, it's generally a good idea to set your random seed immediately prior to performing cross validation to ensure reproducibility of your results.


text:
Q: Dispatcher.BeginInvoke(new...ProgressBarProcess.Value = 1 not showing? This is for Windows 10, Windows Application WPF .NET framework 4.7.2
I have code from an older windows form project (vs 2017 community) for a ProgressBar that worked fine (Windows Forms project). I have a wpf windows project now that works fine but I wanted to add a progress bar to the two buttons (Proccess and Insert buttons) click event because they take several seconds to complete and I want to see some progress. This project is for me only and it always runs inside visual studio (community 2019). I copied the old code to the new project but the progressbar does not show up or show progress. The code is in the buttonclick event in the old project as in the new one but no luck....I maybe missing something from the old project but I don't see what. I know about the "can not modify the UI from the calling thread" but I thought I used a different thread with Task.Factory.StartNew. There are a lot of posts/threads here for Dispatcher.BeginInvoke but I couldn't find one similar to mine ... one of them said  that this approach was the wrong way to do it. I don't do MVVM stuff. I don't do windows programming C# very often so don't assume that I know what I'm doing....LOL. Any help to show the progressbar would be appreciated. A pointer on how to do it "right" also appreciated.Thanks. Here is the code for one of the buttons (ProcessButton_Click) its progressbar is named "ProgressBarProcess":
 private void ProcessButton_Click(object sender, RoutedEventArgs e)
    {
        if (targetBOMTextBox.Text.Length != 11)
        {
            MessageBox.Show("Target BOM part number missing or incorrect format.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        Task.Factory.StartNew(() => ProcessButtonFunction());
    }

 private void ProcessButtonFunction()
        {
            ProgressBarProcess.Minimum = 1;
            ProgressBarProcess.Maximum = 5;
            Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Visibility = Visibility.Visible; }));

            Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 1; }));
            fillExcelLists();
            Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 2; }));
            convertTofloatList();
            Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 3; }));
            splitDesignatorList();
            Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 4; }));
            fillRecordsList();
            Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 5; }));

            insertButton.IsEnabled = true;
            clearButton.IsEnabled = true;

        }

private void fillExcelLists()
    {
        ExcelAccess ExcelAccessOBJ = new ExcelAccess();

        //get part numbers from excel column to GlobalData.excelPartNoList
        ExcelAccessOBJ.ExcelReadColumn(partNoComboBox.SelectedItem.ToString(), Convert.ToInt16(dataStartRowTextBox.Text), Convert.ToInt16(dataEndRowTextBox.Text), GlobalData.excelPartNoList);

        //get quantities from excel column to GlobalData.excelQuantityList
        ExcelAccessOBJ.ExcelReadColumn(quantityComboBox.SelectedItem.ToString(), Convert.ToInt16(dataStartRowTextBox.Text), Convert.ToInt16(dataEndRowTextBox.Text), GlobalData.excelQuantityList);

        //get designators from excel column to GlobalData.excelDesignatorList
        ExcelAccessOBJ.ExcelReadColumn(designatorsComboBox.SelectedItem.ToString(), Convert.ToInt16(dataStartRowTextBox.Text), Convert.ToInt16(dataEndRowTextBox.Text), GlobalData.excelDesignatorList);

    }

 public class ExcelAccess
{
    public void ExcelReadColumn(string column, int rowStart, int rowEnd, List<String> saveData)
    {
        //set up excel stuff
        Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(GlobalData.excelFilenameAndPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
        Microsoft.Office.Interop.Excel.Range data_range;

        Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);      //first sheet

        //Read column
        for (int i = rowStart; i <= rowEnd; i++)
        {
            data_range = sheet.get_Range(column + i.ToString(), column + i.ToString());     //read part number from excel sheet

            //Convert cell value to string
            string tempString = Convert.ToString(data_range.Cells.Value2);
            if (tempString != string.Empty)
            {
                saveData.Add(tempString);
            }

        }

        theWorkbook.Close();
        ExcelObj.Quit();

    }

}

A: Stay on the dispatcher thread and await tasks that execute the long-running methods on background threads:
private async void ProcessButton_Click(object sender, RoutedEventArgs e)
{
    if (targetBOMTextBox.Text.Length != 11)
    {
        MessageBox.Show("Target BOM part number missing or incorrect format.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        return;
    }

    ProgressBarProcess.Visibility = Visibility.Visible;
    ProgressBarProcess.Minimum = 1;
    ProgressBarProcess.Maximum = 5;
    ProgressBarProcess.Value = 1;
    await Task.Run(() => fillExcelLists());
    ProgressBarProcess.Value = 2;
    await Task.Run(() => convertTofloatList());
    ProgressBarProcess.Value = 3;
    await Task.Run(() => splitDesignatorList());
    ProgressBarProcess.Value = 4;
    await Task.Run(() => fillRecordsList());
    ProgressBarProcess.Value = 5;

    insertButton.IsEnabled = true;
    clearButton.IsEnabled = true;
}

No need to involve the dispatcher really.

A: Here is what I end up doing and works. I wanna thanks everyone for their help. The main issue I had seems to be that I was accessing UI from where I wasn't supposed to. Also ProgressBarProcess.Minimum and ProgressBarProcess.Maximum don't seem to work as I read (Link), probably something I missed. Thanks again:
 private void ProcessButton_Click(object sender, RoutedEventArgs e)
    {
        if (targetBOMTextBox.Text.Length == 11)
        {
            GlobalData.TargetBOMpartNo = targetBOMTextBox.Text;

            GlobalData.partNoColumn = partNoComboBox.SelectedItem.ToString();
            GlobalData.quantityColumn = quantityComboBox.SelectedItem.ToString();
            GlobalData.designatorColumn = designatorsComboBox.SelectedItem.ToString();

            GlobalData.dataRowStart = Convert.ToInt16(dataStartRowTextBox.Text);
            GlobalData.dataRowEnd = Convert.ToInt16(dataEndRowTextBox.Text);

        }
        else
        {
            MessageBox.Show("Target BOM part number missing or incorrect format.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        ProcessButton.IsEnabled = false;

        Task.Factory.StartNew(() => ProcessButtonFunction());

    }

 private void ProcessButtonFunction()
    {
        Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Visibility = Visibility.Visible; }));

        Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 10; }));
        fillExcelLists();
        convertTofloatList();
        splitDesignatorList();
        fillRecordsList();
        Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 100; }));

        //insertButton.IsEnabled = true;    //this generates an exception do it like below
        Dispatcher.BeginInvoke(new Action(delegate () { insertButton.IsEnabled = true; }));

        //clearButton.IsEnabled = true;  //this generates an exception do it like below
        Dispatcher.BeginInvoke(new Action(delegate () { clearButton.IsEnabled = true; }));

        Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Visibility = Visibility.Hidden; }));

    }

 private void fillExcelLists()
    {
        ExcelAccess ExcelAccessOBJ = new ExcelAccess();

        //get part numbers from excel column to GlobalData.excelPartNoList
        ExcelAccessOBJ.ExcelReadColumn(GlobalData.partNoColumn, GlobalData.dataRowStart, GlobalData.dataRowEnd, GlobalData.excelPartNoList);
        Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 30; }));

        //get quantities from excel column to GlobalData.excelQuantityList
        ExcelAccessOBJ.ExcelReadColumn(GlobalData.quantityColumn, GlobalData.dataRowStart, GlobalData.dataRowEnd, GlobalData.excelQuantityList);
        Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 60; }));

        //get designators from excel column to GlobalData.excelDesignatorList
        ExcelAccessOBJ.ExcelReadColumn(GlobalData.designatorColumn, GlobalData.dataRowStart, GlobalData.dataRowEnd, GlobalData.excelDesignatorList);
        Dispatcher.BeginInvoke(new Action(delegate () { ProgressBarProcess.Value = 90; }));

    }


text:
Q: OnScroll Event not firing inside a mat-drawer-container I have a bunch of content inside of a mat-drawer-container and I would like to listen for scroll events on it. I have tried window.onscroll() and it did not work. I removed the mat-drawer-container and window.onscroll() worked. I think the mat-drawer-container is the issue.

A: It should work if you listen to the scroll event on the mat-drawer-content class.
document.getElementsByClassName('mat-drawer-content').item(0)!.addEventListener('scroll', () => {
    console.log('It works!')
  })


text:
Q: Как увеличить скорость поиска на сайте? Как увеличить скорость формы поиска на сайте ? На данный момент использую в запросе sql "like "искомый текст" ". База большая и нужно искать по описанию всех страниц, т.е. каждая страница имеет текст ~ 2000 символов , и количество страниц 150 000. Наблюдается медленный поиск который отрабатывает около 10 и более секунд. Как можно увеличить скорость запроса sql.? Либо это зависит только от скорости сервера?

A: Если mysql и база myisam то https://habrahabr.ru/post/40218/
Если postgreSQL то http://www.sai.msu.su/~megera/postgres/talks/fts_pgsql_intro.html
Так же есть ElasticSearch и Sphinx, но эти штуки для более сложных вещей, чем полнотекстовый поиск по 1 полю.


text:
Q: Inverse Laplace Transform With Dead Time Here is the transfer function that needs to be transformed back into the time domain:
$$Y(s)=\frac{K_{2}e^{-\theta s}}{s(\tau_{1} s + 1)(\tau_{2} s + 1)}$$
Then would the response be:
$$y(t) = K_{2}(t-\theta ) \Bigg(1-\frac{\tau_{1}e^{\frac{-(t-\theta)}{\tau_{1}}}-\tau_{2}e^{\frac{-(t-\theta)}{\tau_{2}}}}{\tau_{1}-\tau_{2}}\Bigg)$$
EDIT:
Ok, I'm pretty sure I am right now, but how the hell do I put something like this into matlab?

A: $$\mathcal{L}^{-1}(e^{-\theta s}) = \delta(t-\theta)$$ also known as the Dirac Delta function. The rest is pretty easy to solve as it appears to be a second order of a Type 1 oscillator.


text:
Q: Using distinct in Spring data over multiple columns My domain model is like this:
CollectedData {
  String name;
  String description;
  int count;
  int xAxis,
  int yAxis
}

Using Spring data repository query, I would like to retrieve all the unique rows (unique with name, xAxis, yAxis)
I am trying something like this
@Query("select distinct a.name, a.xAxis, a.yAxis from CollectedData a")
List<CollectedData> findAllDistinctData();

So, when I do
List<CollectedData> records= findAllDistinctData();
for (CollectedData record : records) { //Exception on this line
 }

Exception
[Ljava.lang.Object; cannot be cast to CollectedData.
Is there any other way to write query for this ?

A: @Query return ArrayList of Object(s) instead of specific type of object. so you have to define some thing like
@Query("select distinct a.name, a.xAxis, a.yAxis from CollectedData a")
List<Object> findAllDistinctData();

then cast according to your requirement,
List<Object> cdataList=findAllDistinctData();
for (Object cdata:cdataList) {
   Object[] obj= (Object[]) cdata;
     String name = (String)obj[0];
    String description = (String)obj[1];;
 ...
  }

A: Instead of returning an object you can use JPA's constructor expression feature to return a more specific object holding only the columns you're interested in. See also following answer:
JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped
According to your example you could create a new Object with only the columns you are interested in:
SELECT DISTINCT new com.mypackage.MyInterestingCollectedData(a.name, a.xAxis, a.yAxis) from CollectedData a

A: If you want to select complete object based on distinct values of multiple columns,
In that case the native query would be the option.
e.g.
@Query(
        value = "select distinct on (column1, column2, column3) * From my_table where someId=: order by column1 asc,column2 desc,column3 desc,column4 desc",
        nativeQuery = true
    )
    fun finalAllDistinctBy(containerId: String): List<MyTable>


text:
Q: rake db:migrate alter table name I wanted to change the name of a table I creted with rake db:migrate from financialss to financials. I created a file in my migrate directory called changeme.rb that looks like this.
 class CreateFinancials < ActiveRecord::Migration
        def self.up
             rename_table :financials, :financialss
        end

        def self.down
              rename_table :financialss, :financials
        end
   end

I tried to run the following:
rake db:migrate:up changeme.rb
and got the following error:
rake aborted!
Don't know how to build task 'db:migrate:changeme.rb'
All help appreciated

A: Use the rails generator
rails g migration MigrationName

The rails do not understand when you come out of the convention. So try to use the default generator.


text:
Q: Incomplete "able to" in next sentence Consider the following two sentences (from this SO answer):

So the fact that you can now reference pygame.display is an accident
  of implementation details. You may not be able to in future versions
  (if the project no longer needs to import pygame.display to load
  pygame.joystick, for example).

The sentence "You may not be able to in future versions" seems incomplete to me. I think it is missing something and "You may not be able to do it in future versions" will be more complete. So, my question, is the first form without do it correct and complete?

A: Yes, it is correct and complete. You may omit the verb phrase when its meaning can be understood from the context. In linguistics, this phenomenon is known as ellipsis.
In your example:

So the fact that you can now reference pygame.display is an accident
  of implementation details. You may not be able to [reference
  pygame.display] in future versions.

One could also say

You may not be able to do that in future versions.

Other examples of verb phrase ellipsis:

A: Do you want me to go with you?
B: Oh, you don't have to [go with me].

or

He says that I should become an astronaut, but I don't want to
  [become an astronaut].

Here's a similar question — Omitting verbs, is it correct?