text:
Q: UISearchController in UITabBarController status bar issues I have been having this issue with the status bar and tab bar.

Here is my code:
self.searchResultsController = [BZDashboardSearchResultsController new];

self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchResultsController];
self.searchController.hidesBottomBarWhenPushed = YES;
self.searchController.searchResultsUpdater = self;
self.searchController.hidesNavigationBarDuringPresentation = YES;
self.definesPresentationContext = YES;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.view.backgroundColor = [UIColor whiteColor];

self.searchController.delegate = self;
self.searchController.searchBar.delegate = self;

[self presentViewController:self.searchController
                   animated:YES
                 completion:nil];

I want to hide the tab bar place the search bar under the status bar. My view controller hierarchy looks like this:
UITabBarController
   --UINavigationController
       ---View Controller where the above code is executed.

In my app delegate, I set my UITabBarController subclass as the root view controller:
self.window.rootViewController = tabBarViewController;

The init method of the subclass is this:
-(instancetype)init {
  self = [super init];

  if (self) {
    UINavigationController *workspaceNavigationController = [[UINavigationController alloc] initWithRootViewController:self.workspaceController];

    self.userProfileViewController.showLogoutButton = YES;
    UINavigationController *userProfileNavigationController = [[UINavigationController alloc] initWithRootViewController:self.userProfileViewController];

    self.viewControllers = @[workspaceNavigationController, userProfileNavigationController];
  }

  return self;
}

self.workspaceController has a search button in its navigation bar the code that presets UiSearchController.


text:
Q: Cannot parse date string containing three letter month I spent about hour to solve problem, but I couldn't...
My date string is "06 Jan 2016", and I want to parse it to object Date.
I tried next method
SimpleDateFormat frmt2 = new SimpleDateFormat("dd MMM yyyy");
Date date = frmt2.parse("06 Jan 2016");

And I got:
java.text.ParseException: Unparseable date: "06 Jan 2016" (at offset 3)

I tried Joda lib
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd MMM yyyy");
DateTime dt = formatter.parseDateTime("06 Jan 2016");

But I got same error:
Invalid format: "06 Jan 2016" is malformed at "Jan 2016"

Can you help me please to obtain the success in this simple problem.
Thank you very much.

A:   SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy  hh:mm", Locale.ENGLISH);

    Date theDate = format.parse("JAN 13,2014  09:15");

    Calendar myCal = new GregorianCalendar();
    myCal.setTime(theDate);

    System.out.println("Day: " + myCal.get(Calendar.DAY_OF_MONTH));
    System.out.println("Month: " + myCal.get(Calendar.MONTH) + 1);
    System.out.println("Year: " + myCal.get(Calendar.YEAR));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disabled row on Datagrid WPF getting selected when clicked with the Right Mouse Button I got some problems in Datagrid WPF
I have a datagrid, and I want to set the IsEnabled property of a single row to false whenever the user assign a value to the binding item of the datagrid itemSource
So I made it by datagrid Style triggers:
               <DataGrid AutoGenerateColumns="False" Margin="9,35,0,6" Name="dataGrid2" ItemsSource="{Binding}" SelectionChanged="dataGrid2_SelectionChanged" IsReadOnly="True" SelectionMode="Single">
                    <DataGrid.RowStyle>

                        <Style TargetType="{x:Type DataGridRow}">
                            <Style.Setters>
                                <Setter Property="IsEnabled" Value="False" />
                            </Style.Setters>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=Coluna}" Value="{x:Null}">
                                    <Setter Property="IsEnabled" Value="True"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>

                    </DataGrid.RowStyle>
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Campo" Binding="{Binding Path=Campo}" Width="1.4*" CanUserSort="False" />
                        <DataGridTextColumn Header="Coluna/Constante" Binding="{Binding Path=Coluna}" CanUserSort="False" Width="*" />
                    </DataGrid.Columns>
                </DataGrid>

Working fine, it disables the entire row when a value is assigned to the "Coluna" field of that row (different of null)
The problem is: I still can click and select the disabled row using the right mouse button... Does the "IsEnabled" property only blocks the left mouse button click on datagrid rows?? Do I need to set another property to disable the right mouse button click on that row?
Thank you!

A: This is a known bug of the DataGrid and it's reported on Connect here: DatagridRow gets selected on right click even if the datagrid is disabled. Looks like this will be fixed in WPF 4.5.
To workaround it you can bind IsHitTestVisible to IsEnabled
<DataGrid ...>
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="IsEnabled" Value="False" />
            <Setter Property="IsHitTestVisible"
                    Value="{Binding RelativeSource={RelativeSource Self},
                                    Path=IsEnabled}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Coluna}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
    <!-- ... -->
</DataGrid>


text:
Q: Progress indicator for git clone Is it possible to get a progress bar when doing a git clone? I'm wondering because I am currently doing a git clone that has taken a few minutes so far and would be curious to know if it is going to finish soon.

A: Not really. There are various stages to git clone:

*

*discover the objects that need to be sent ("Counting objects: nnn")

*compress and send those objects

*index the received pack

*check out received files

Stage 1 involves walking through the commit graph from each branch head finding all the commits and associated objects: since there is no idea beforehand of how many commits there are, the progress of this can't be gauged. Sadly this is often where a lot of the time in a clone operation is taken up.
Stage 2 does have a progress counter, although it counts objects rather than volume (so its rate varies, especially if the repo has large blobs)
Stages 3 and 4 have progress counters, although they are usually much faster than the previous two stages.

A: You might want to take a look at the folder
$project/.git/objects/pack

While cloning, there should be a file starting with tmp_pack_. It contains the currently downloading git pack.
With this information you might be able to eyeball the duration.

A: You can do:
   du -s .git

to monitor changes in the size of temporary content to get an idea.
   watch du -s .git

allows you to monitor without having to retype the command. Something like the one-liner below will give periodically you the data accumulation rate in kB per second:
    delay=5; prev=`du -sk .git/ | cut -f 1`; sleep $delay; while true; do  cur=`du -sk  .git/ | cut -f 1`; expr \( $cur - $prev \) / $delay ; prev=$cur; sleep $delay; done

A:
I am currently doing a git clone that has taken a few minutes so far and would be curious to know if it is going to finish soon.

With Git 2.10 (Q3 2016), git clone --progress will be more verbose.
See commit 38e590e by Jeff King (peff)
(Merged by Junio C Hamano in commit a58a8e3 Aug. 4th 2016)

clone: use a real progress meter for connectivity check
Because the initial connectivity check for a cloned
  repository can be slow, 0781aa4 (clone: let the user know
  when check_everything_connected is run, 2013-05-03) added a
  "fake" progress meter; we simply say "Checking connectivity"
  when it starts, and "done" at the end, with nothing between.
Since check_connected() now knows how to do a real progress
  meter, we can drop our fake one and use that one instead.

As noted by ks1322 in the comments

--progress is enabled by default when you run git clone from a terminal.  There is no need to write it explicitly for terminal.

A: How about git clone --progress ?


text:
Q: WPF OnRender not called on FrameworkElement I have the following custom framework element (which just draws a rectangle and some ellipses) with nested "visuals". Now I want to change some colors when the mouse enters or leaves the control. The code will be called but the color won't change even with InvalidVisual. Any idea what's wrong here:
public class Dummy : FrameworkElement
{
    #region Fields

    private Ellipse _bottomLeft = new Ellipse();
    private Ellipse _bottomRight = new Ellipse();
    private ContainerVisual _containerVisual = new ContainerVisual();

    private Rectangle _rect = new Rectangle();
    private Ellipse _topLeft = new Ellipse();
    private Ellipse _topRight = new Ellipse();

    #endregion Fields

    #region Constructors

    public Dummy()
    {
        Initialize();

        _containerVisual.Children.Add(_rect);
        _containerVisual.Children.Add(_topLeft);
        _containerVisual.Children.Add(_topRight);
        _containerVisual.Children.Add(_bottomLeft);
        _containerVisual.Children.Add(_bottomRight);
    }

    #endregion Constructors

    #region Properties

    protected override int VisualChildrenCount
    {
        get { return _containerVisual == null ? 0 : 1; }
    }

    #endregion Properties

    #region Methods

    private void Initialize()
    {
        // Rectangle
        _rect.Stroke = Brushes.Red;
        _rect.StrokeThickness = 1;
        _rect.Fill = new SolidColorBrush(Colors.Transparent);
        // Ellipses
        _topLeft.StrokeThickness = 1;
        _topLeft.Stroke = Brushes.Red;
        _topLeft.Fill = new SolidColorBrush(Colors.Orange);
        //----------------
        _topRight.StrokeThickness = 1;
        _topRight.Stroke = Brushes.Red;
        _topRight.Fill = new SolidColorBrush(Colors.Orange);
        //----------------
        _bottomLeft.StrokeThickness = 1;
        _bottomLeft.Stroke = Brushes.Red;
        _bottomLeft.Fill = new SolidColorBrush(Colors.Orange);
        //----------------
        _bottomRight.StrokeThickness = 1;
        _bottomRight.Stroke = Brushes.Red;
        _bottomRight.Fill = new SolidColorBrush(Colors.Orange);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        var diameter = 6;
        var radius = diameter / 2;
        var rectThicknessOffset = _rect.StrokeThickness / 2;

        var rect = new Rect(new Point(0, 0), finalSize);

        _rect.Arrange(rect);
        _topLeft.Arrange(new Rect(rect.TopLeft.X - radius + rectThicknessOffset,
            rect.TopLeft.Y - radius + rectThicknessOffset, diameter, diameter));
        _topRight.Arrange(new Rect(rect.TopRight.X - radius - rectThicknessOffset,
            rect.TopRight.Y - radius + rectThicknessOffset, diameter, diameter));
        _bottomRight.Arrange(new Rect(rect.BottomRight.X - radius - rectThicknessOffset,
            rect.BottomRight.Y - radius - rectThicknessOffset, diameter, diameter));
        _bottomLeft.Arrange(new Rect(rect.BottomLeft.X - radius + rectThicknessOffset,
            rect.BottomLeft.Y - radius - rectThicknessOffset, diameter, diameter));
        return base.ArrangeOverride(finalSize);
    }

    // Provide a required override for the GetVisualChild method.
    protected override Visual GetVisualChild(int index)
    {
        if (_containerVisual == null)
        {
            throw new ArgumentOutOfRangeException();
        }
        return _containerVisual;
    }

    protected override void OnMouseEnter(MouseEventArgs e)
    {
        base.OnMouseEnter(e);
        _rect.Stroke = new SolidColorBrush(Colors.Blue);
        InvalidateVisual();
        Debug.WriteLine("Mouse Enter");
    }

    protected override void OnMouseLeave(MouseEventArgs e)
    {
        base.OnMouseLeave(e);
        _rect.Stroke = new SolidColorBrush(Colors.Green);
        InvalidateVisual();
        Debug.WriteLine("Mouse Leave");
    }

    protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
    {
        return new PointHitTestResult(this, hitTestParameters.HitPoint);
    }

    #endregion Methods
}

A: Try to replace the call to InvalidateVisual with calls to Measure and Arrange:
protected override void OnMouseLeave(MouseEventArgs e)
{
    base.OnMouseLeave(e);
    _rect.Stroke = new SolidColorBrush(Colors.Green);
    Measure(Size.Empty);
    Arrange(new Rect(DesiredSize));
    Debug.WriteLine("Mouse Leave");
}


text:
Q: Binding static string in static class to textbox I want to make a static string to show feedback message.
Configuration.cs
namespace WpfApplication1
{
    public static class Configuration
    {
        public static string Message { get; set; }
    }
}

MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="69,92,0,0"
        TextWrapping="Wrap"
        Text="{Binding Source={x:Static s:Configuration.Message}}"
        VerticalAlignment="Top" Height="119" Width="366"/>
    </Grid>
</Window>

MainWindow.xaml.cs
namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Calc calculation = new Calc();

            int calc = calculation.add(1, 3);
        }
    }
}

Calc.cs
namespace WpfApplication1
{
    class Calc
    {
        public int add(int a, int b)
        {
            int c = 0;

            try
            {
                c = a + b;
            }
            catch (Exception ex)
            {
                Configuration.Message = ex.Message; // I want to show this message.
            }

            return c;
        }
    }
}

So if the program has error on Calc.cs, it changes the value in Configuration.Message.
I want to use data binding for that. Can you give me any advice or sample code?
Thanks.

A: Create your own event in the static class for handling the property changed as INPC doesn't work


text:
Q: webpack --process unknown argument I was using webpack --process -p on my old computer which had webpack 1.x installed to process my jsx files. On my new one, I installed webpack which currently points to 2.6.1 and now it's telling me that --process is an unknown argument.
How do I handle this issue?
Here's my webpack.config.js file:
var IS_DEV = false; // change to false if building production files

var webpack = require('webpack');
var path = require("path");

var _pluginsDev = [
        new webpack.ProvidePlugin({
            'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
            moment: 'moment',
            ps: 'perfect-scrollbar'
        }),

];
var _pluginsProd = [
        new webpack.ProvidePlugin({
            'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
            moment: 'moment',
            ps: 'perfect-scrollbar'
        }),
        new webpack.DefinePlugin({ // Minimizer, removing multiple occurances of imports et.c
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            minimize: true,
            compress: true,
            output: { comments: false }
        })
];

var _devtool = IS_DEV ? 'eval' : 'cheap-module-source-map';
var _plugins = IS_DEV ? _pluginsDev : _pluginsProd;
var _fileName = IS_DEV ? "./build/[name]-bundle.js" : "./dist/[name]-bundle.js";

var _bundles = {
    module1: './components/module1/module1.jsx',
    module2: './components/module2/index.jsx'
};

// Export for Project List
module.exports = {
    devtool: _devtool,
    entry: _bundles,
    plugins: _plugins,
    output: {
        path: path.resolve(__dirname, "wwwroot"),
        publicPath: "/",
        filename: _fileName

    },
    module: {
        loaders: [
          {
              test: /\.jsx?$/,
              exclude: /(node_modules|bower_components)/,
              loader: 'babel',
              query: {
                  presets: ['es2015', 'stage-2', 'react']
              }
          }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    }
};


text:
Q: XML parsing for windows phone 8 Cant we creat a object for XmlDocument in Visual studio 2012 for mobile,
The code is as shown
string url1 = "http://maps.googleapis.com/maps/api/geocode/xml?address=bangalore&sensor=false";
XmlDocument doc = new XmlDocument();
doc.Load(@url1);
XmlNode MyNode = doc.SelectSingleNode("GeocodeResponse/result/geometry/location/lat");
Console.WriteLine(String.Concat("lat: ", MyNode.InnerText));

A: It seems that XmlDocument is not supported in Windows Phone 8. But you can use the XDocument class instead.
I have updated your code to use the XDocument class and the extension method XPathSelectElement to get the required node. You will need to set the required namespaces in your code.
string url1 = "http://maps.googleapis.com/maps/api/geocode/xml?address=bangalore&sensor=false";
XDocument doc = XDocument.Load(url1);

XElement myNode = doc.XPathSelectElement("GeocodeResponse/result/geometry/location/lat");
Console.WriteLine(String.Concat("lat: ", myNode.Value));

If the XPathSelectElement-Extension method is not available you can use the Element()-Method on XElement.
XElement myNode = doc.Element("GeocodeResponse").Element("result").Element("geometry").Element("location").Element("lat");


text:
Q: Trying to learn @EnvironmentObject in SwiftUi I got this code from the SwiftUI by Example tutorial and it fails. The code compiles and runs ok but when any of the 2 button is tapped it crashes.
The error I get is: Thread 1: Fatal error: No ObservableObject of type UserSettings found. A View.environmentObject(_:) for UserSettings may be missing as an ancestor of this view. and it is attached to line settings.score += 1
class UserSettings: ObservableObject {
@Published var score = 0}

struct DetailView: View {
@EnvironmentObject var settings: UserSettings
var body: some View {
    Text("Score: \(settings.score)")
}}

struct ContentView: View {
@EnvironmentObject var settings: UserSettings
var body: some View {
    NavigationView {
        VStack {
            Button("Increase Score") {
                settings.score += 1
            }
            NavigationLink(destination: DetailView()) {
                Text("Show Detail View")
            }
        }
    }
}}

A: EnvironmentObjects must be supplied by anscestor views!
Edit your main to this down code:
  @main
struct Your_ App_ Name_Here: App {  // <<: your app name!

    var body: some Scene {

        WindowGroup {

            ContentView()
                .environmentObject(UserSettings())

        }

    }

}


text:
Q: Evidence for integer factorization is in $P$ Peter Sarnak believes that integer factorization is in $P$. It is a well-known open problem in TCS to identify the real complexity class of integer factorization. Take a look at this link for Peter Sarnak's lectures where he mentions that he does not believe factoring is not in $P$.
What evidence is there that integer factorization is in $P$ other than the fact that polynomial factorization is in $P$?

A: I don't think there is any compelling evidence that integer factorization can be done in polynomial time.  It's true that polynomial factoring can be, but lots of things are much easier for polynomials than for integers, and I see no reason to believe these rings must always have the same computational complexity.  (Strangely, if you do believe that, it means the shortest lattice vector problem should also be efficiently solvable, but it doesn't seem to tell you anything about discrete logarithms.  This puzzles me, since the parallels between factoring and discrete logs are also strong.)  It's also true that primality testing can be done in polynomial time, but that is a fundamentally different problem: when a modulus is prime, it has enormous consequences for modular arithmetic, and it is not difficult to test for primality by looking for those consequences, but the actual methods shed no light on factoring.
On the other hand, there is also no compelling evidence that factoring can't be done in polynomial time (see http://research.microsoft.com/~cohn/Thoughts/factoring.html for a little more detail about this).
At our current level of knowledge, I view the complexity of factoring as a matter of opinion, speculation, and wishful thinking, not principled arguments.  By contrast, there are exceedingly good reasons why the Riemann hypothesis should be true, and good reasons why P shouldn't equal NP.  I'm certainly open to arguments that fall far short of rigorous proof; I've just never heard a convincing one about the complexity of factoring.
My interpretation of Sarnak's belief isn't that he sees some good reasons other people don't appreciate.  Rather, it just feels plausible to him, and he's perhaps a little annoyed that lots of people firmly believe the opposite for no good reason, so he makes a point of stating a strong opinion.


text:
Q: jquery: load values from external html and populate many local  fields, with one read of the html I'm using this code now, works great except that it makes three requests to the webserver:
var refreshspeed=1000

        function moreSnow() {
    $("#uptimedynamic").load("index.html #uptimedynamic");
    $("#cpuloaddynamic").load("index.html #cpuloaddynamic");
    $("#meminfodynamic").load("index.html #meminfodynamic");
    setTimeout("moreSnow()", refreshspeed);
    }

Can someone tell me how to make it do the same thing, but with only one read of index.html? It needs to stay in the same repeating loop setup :)

A: This should do it
/* cache selectors in main page to avoid searching for them every second*/
var $upTime=$("#uptimedynamic"),  $cpuload = $("#cpuloaddynamic"), $meminfo=$("#meminfodynamic")

function moreSnow() {
    $.get("index.html", function(data){
        /* create a jQuery object from the retrieved page html that can then be traversed*/
        var $data=$(data);

        $upTime.html( $data.find('#uptimedynamic').html() );
        $cpuload.html( $data.find("#cpuloaddynamic").html() );
        $meminfo.html( $data.find("#meminfodynamic").html() );

    });
}

By retrieving only the contents of each element you alsoo avoid dupicating ID's in page and potential style issues


text:
Q: How to findout main method has called by JVM or existing process? Considering the following code
public static void main(String...arg){
//do something
if(<<the method has called by a new process>>){System.exit(0);}
else{System.setProperty("main_result","0");return;}
}

the main method would be called by a separated process by JVM or existing process, now how can I find it out?
Thanks in advance

A:
In java, every Java process runs in its own JVM. So, the "same" main
  method cannot be called by a different process under normal
  circumstances
Even if you run the same program twice, they will be running in their
  own JVMs.
You can try one thing.. Keep a static variable in your program, run it and
  make it sleep for a long period of time (process 1).. Now, run the same
  program again and update the static variable(runs in process 2).. See, whether it will be
  updated in the first process (No, it won't be updated as each process will have it's own
  set of variables..)

A: Let's clarify: there might be another class with a main that was started, or the main is somehow called again.
Normally you want to call System.exit(0) (or return;?) but when called from the program itself you want to end in System.setProperty("main_result","0");.
public static void otherMain(String[] args) {
    Main.main(args);
}

public static void main(String[] args) {

    ...

    StackTraceElement[] elems = Thread.currentThread().getStackTrace();
    //for (StackTraceElement elem : elems) {
    //    System.out.printf("%s%n", elem.getClassName());
    //}
    if (elems.length > 2) { // [0] Thread [1] main
        System.setProperty("main_result","0");
    }
}

A: Do you really need it? Just don't use System.exit(0); and refactor main method to finish gracefully.
Calling System.setProperty in both cases - when run as new process and also as a class on classpath, will not make any difference.
Edit: Finding out who is calling the method is not easy and definitely bad practice.

A: I would refactor the code as follows:
public static void main(String...arg){
  System.exit(doStuff(arg));
}

public static int doStuff(String... arg) {
  //do something
}

To access this logic within the same JVM you can now call MyClass.doStuff and get the return value directly.

A: It would be better to consider refactoring and get rid of such problem.
Otherwise the following code can help:
    if(Thread.currentThread().getStackTrace()[1].getClassName().equals(
            System.getProperty("sun.java.command"))){
        System.out.println("!");
    }

Will not work if there is no "sun.java.command" property (on not Sun/Oracle JVMs it may absent)


text:
Q: c: Struct type incompatiable error my code as follows:
here I declare the publicgroup that after "struct group":
When I try to use the method, there is an error"struct group is incompatible with parameters of type struct group". I am using VS2013.
The error is in "int value = isgroupCointainsPID(publicgroup, 300);"This is the screen shot in my VS:

The strang thing is that if I ust the commented "test", it works well.
I am not quite sure ,what's wrong about my code?
struct proNode{
    int pID;
    struct proNode *next;

};
char groups [3][128];
struct group{
    int gID;
    char *name;
    struct proNode *prolist;
    struct proNode *blacklist;
}publicgroup;

int isgroupCointainsPID(struct group _group, int pID){
    if (_group.prolist == NULL){
        printf("There is no process %d\n", pID);
        return 0;
    }
    struct proNode *pros = _group.prolist;
    while (pros != NULL){
        if (pros->pID == pID)
            return 1;
        pros = pros->next;

    }
    printf("There is no process %d\n", pID);

    return 0;
}

int main(){
    publicgroup.gID = -1;
    publicgroup.name = "public group";
    publicgroup.prolist = NULL;
    publicgroup.blacklist = NULL;
    publicgroup.gID = 2;
// there is an error :struct group is incompatible with parameters of type struct group
    int value = isgroupCointainsPID(publicgroup, 300);
    return 0;
}

A: Incompatible parameters error is possible when you miss the function prototype. So please check whether you written the function prototype or not

A: i guest you wrong when typing that method paramaters,
i never use VS so i cant give much advice,
i guest you want scan that usergroup, so you want pass it as pointer?
As i know when i use codeblocks, just try to change this
isgroupCointainsPID(struct group _group, int pID)

to
isgroupCointainsPID(group _group, int pID)

i hope its work


text:
Q: why is my code not accepting letters as user input my code runs without errors or anything but after I put in an "F" or "P" it skips to "click any button to continue" but if I use any numbers it goes through the code fine.
Here is my code:
#include <iostream>
#include <iomanip> // needed to use set precision

using namespace std;

void calcCost(double f_benefits, double F, double total_cost, double emp_salary)
{
    if (f_benefits == F)
        (total_cost += emp_salary * 1.5);
    else
        (total_cost += emp_salary * 1.25);   // calculating operating function

}

int main()
{

    double num_emp = 0; // employees
    double emp_salary = 0; // employees salary
    double f_benefits = 0; // are they full time or part time benifits
    double total_cost = 0;
    int F = 0;
    int P = 0;

    cout << setw(69) << "Cost of Operation\n\n";

    cout << "Please enter the number of employees to process: ";
    cin >> num_emp;
    cout << endl;

    for (int i = 1; i <= num_emp; i++)  // loop for each employees salary and benifits
    {
        cout << "Please enter the salary for employee " << i << ":";
        cin >> emp_salary;

        cout << "Is employee " << i << " receiving(F)ull or (P)artial benefits ? Please enter F or P : "; // Dont forget input validation for this step
        cin >> f_benefits;

    }

        return 0;
}

A: Shouldn't f_benefits be a string?

A: The "cin >> f_benefits" is trying to read a double value. You should read the response into a char or string. Reading into a string expects a newline before returning.
You should also check that you got an "F" or "P" .


text:
Q: How can I configure multiple default gateways on a CISCO Router? Does any one knows a way to configure a cisco router with multiple gateways - multiple gateways of last resort?
I've tried adding a gateway of last resort twice (with different metric) but only one is shown:
Router(config)# ip route 0.0.0.0 0.0.0.0 2.2.2.2 10
Router(config)# ip route 0.0.0.0 0.0.0.0 3.3.3.3 100

And the show ip route output was:
Router# show ip route
Gateway of last resort is 2.2.2.2 to network 0.0.0.0

     2.0.0.0/24 is subnetted, 1 subnets
C       2.2.2.0 is directly connected, FastEthernet0/0
     3.0.0.0/24 is subnetted, 1 subnets
C       3.3.3.0 is directly connected, FastEthernet0/1
     32.0.0.0/30 is subnetted, 1 subnets
C       32.2.2.0 is directly connected, Serial0/2/0
S*   0.0.0.0/0 [10/0] via 2.2.2.2

The point is that i cannot see the other route with higher distance metric?
Anyone has a sugestion?
I mean will this config work if the link on 2.2.2.2 fails? Will the router choose the other network 3.3.3.3, if the link 2.2.2.2 fails?

A: IIRC, if you put different metrics only the best route will be injected in the main routing table.
So you have three choices:
First choice, as @dkaragasidis said, don't put the metrics (to get per session load-balancig) but then the traffic will flow nearly 50% on both links
Second choice, use some sort of dynamic routing protocol (i suggest BGP) if possbile.
Third choice, use ip sla commands to costantly check for ip availability.
Keep in mind that if one FastEthernet interface (or the remote port with which is connected) fails (i.e. the status of the interface goes to down) then the router automatically injects the other default route, but NOT if the 2.2.2.2 router somehow doesn't work (in that case the ip sla commands will take care of this).
If BGP is not an option and you really don't wanto to balance the gateways, ip sla is your best solution. Take a look at this answer to a similar question for a link to some examples.

A: Consider checking out Cisco's Configuring a Gateway of Last Resort Using IP Commands.

If you use multiple ip route 0.0.0.0 0.0.0.0 commands to configure a
  default route, traffic is load-balanced over the multiple routes.

A: With having multiple default routes you can load-balance the traffic ( session lb ).
If you want to keep one of the paths as backup , then you need to play with metric. Give a higher metric to the path you wanna use as backup and smaller metric to the main one. This will solve your issue.
By the way because main default route will be there although the next hop is lost , you need to configure a tracker and ip sla to check the  availability. If Ip Sla is down and the route will be deleted and the backup route will be inserted to your routing table.
Another solution is to define the outgoing interface instead of next-hop. Here you dont need ip sla
 ip route 0.0.0.0 0.0.0.0 fa0/0 10  -->  main route
 ip route 0.0.0.0 0.0.0.0 fa0/1 100 -->  backup route

A: If you have a router/firewall and you are doing 'router on a stick' or have each subnet connected from the router via its own interface to the switch capable of Layer 3 also, then on the switch you can have multiple gateways of last resort.
Lets take a router with 2 x LAN Subnets of 10.0.1.0/24 and 10.0.2.0/24
Router LAN Interface is setup with:
Fa0/0.1 = 10.0.1.1 255.255.255.0

Fa0/0.2 = 10.0.2.1 255.255.255.0

Then you configure your first switch, which in a small business is often a L3 capable SB Cisco SG Series or a C1K switch, treated like a "Core".
Plug FastEthernet 0/0 from the Router/Firewall into your Switch, lets say Gi1/0/1:
On that switch, now you can configure interface Gi1/0/1 as:
switchport mode trunk

On the Switch, you will need to do the following
Switch> enable
Switch# conf t
Switch(config)#

interface vlan 1
ip address 10.0.1.10 255.255.255.0

interface vlan 2
ip address 10.0.2.10 255.255.255.0

ip routing
ip route 0.0.0.0 0.0.0.0 10.0.1.1
ip route 0.0.0.0 0.0.0.0 10.0.2.1

With the interfaces active and up, you will find that devices connected to their respective VLAN via Access ports on the switch will route just fine to the switch for inter-vlan routing, and for outside access or to move into another network or the Internet, the ip routes you set will permit that traffic to go to the firewall/router.


text:
Q: Segmentation faults in deque of user-defined pointers I have a deque<rect*> rects where rect is a user-defined class. When I try to insert a rect* into it, I get a segmentation fault. gdb traces the problem back to a function called __memmove_sse3() from my calling rects.insert(it,new rect([constructor parameters]));  where it is a deque<rect*>::iterator. What could cause this error?
EDIT:
here is a snippet of my code:
for(deque<rect*>::iterator it=rects.begin();it!=rects.end();++it)
        {
            rect r=*r1;
            rect r2=*(*it);
            if(!r2.there)
                continue;
            if(r.down>r2.up || r.up<r2.down || r.right<r2.left || r.left>r2.right)
                continue;
            if(r.left>r2.left)
                rects.insert(it,new rect(r2.left,r2.down,r.left,r2.up,r2.color));
            if(r.right<r2.right)
                rects.insert(it,new rect(r.right,r2.down,r2.right,r2.up,r2.color));
            if(r.up<r2.up)
                rects.insert(it,new rect(max(r.left,r2.left),r.up,min(r.right,r2.right),r2.up,r2.color));
            if(r.down>r2.down)
                rects.insert(it,new rect(max(r.left,r2.left),r2.down,min(r.right,r2.right),r.down,r2.color));
            r2.there=false;
        }

A: The problem is that you're inserting item to std::deque which invalidates the iterator which you're incrementing in the for loop:
The Standard (draft n3485) says in §23.3.3.4/1 (emphasize mine),

Effects: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque.

A: Segfaults can come from any number of sources, and don't always manifest immediately.  Chances are you're overflowing an array, using the stl containers in an invalid manner, or the like -- when you corrupt areas of memory you don't own that might be used for e.g. allocation accounting, it can make future allocations, frees, moves, or any other indirect accesses fail spectacularly.
Bringing out the big guns may help solve this quickly!  You can use valgrind's memcheck module if you're on a system that will run valgrind, or you can use something like Application Verifier on Windows.
Your compiler or libraries may have standard library / STL debugging functionality -- if you're in an IDE, poke around to see what options you have available.  For libstdc++ (often used with gcc/g++), you can look at the libstdc++ Debugging Support options.
Here's my earlier answer to a question about heap corruption which discusses such tools, and my list of reasons you might want to overload operator new and delete also has another list of tools.  (Shameless self-promotion, here, but I think these are pretty good lists!)

Based on your code I'd say you're invalidating the loop iterator.  From http://www.sgi.com/tech/stl/Deque.html:

The semantics of iterator invalidation for deque is as follows. Insert
  (including push_front and push_back) invalidates all iterators that
  refer to a deque. Erase in the middle of a deque invalidates all
  iterators that refer to the deque. Erase at the beginning or end of a
  deque (including pop_front and pop_back) invalidates an iterator only
  if it points to the erased element.


text:
Q: ASDoc ignores public function definitions? I've got a collection of ActionScript utility functions… But when I try to run asdoc over them, they don't appear in the list of 'package functions'.
For example, if I run:
asdoc -doc-sources+=src/utils/ -doc-sources+=src/utils/map.as -doc-sources+=src/utils/max.as -source-path+="src"

I don't see either the map function or the max function (in fact, only one function appears):
only one package appears http://img.skitch.com/20100202-dke3sw9bj55h6x6dc53un519su.png
Is there any way I can coax ASDoc into showing all my public definitions?

A: This is a bug in ASDoc prior to the version in the Flex 4 SDK.


text:
Q: XmlStartlet Namespace Issue Have issue with XmlStartlet and namespaces (using windows)
I am running this from command line and not using xslt
Please see sample Xml below;
<?xml version="1.0" encoding="UTF-8"?>
<BAMDefinition xmlns="http://schemas.microsoft.com/BizTalkServer/2004/10/BAM">
  <Activity xmlns="http://schemas.microsoft.com/BizTalkServer/2004/10/BAM" Name="TEST1" ID="ID85FB3D38A9CB4BF885C6A5BE7EBBE073">
    <Checkpoint Name="ReceivedDt" ID="IDE7FB8E0181894CB6A8F097C746837757" DataType="DATETIME"/>
  </Activity>
  <Activity xmlns="http://schemas.microsoft.com/BizTalkServer/2004/10/BAM" Name="TEST2" ID="ID85FB3D38A9CB4BF885C6A5BE7EBBE074">
    <Checkpoint Name="Filename" ID="IDA65B929E71704F7FA09044CD231044D4" DataType="NVARCHAR" DataLength="255"/>
  </Activity>
</BAMDefinition>

I want to either;
delete node that has a xmlns attribute with specific selector attribute @Name="TEST1" using the ed -N
or
Delete all namespaces to allow me to manipulate Xml
I have tried looking at http://xmlstar.sourceforge.net/doc/UG/ch05s01.html, but this did not work.
I have looked at the documentation;
http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html#idm47077139518336 (section 1.4 to no avail)
If anyone can suggest a link that would assist or any command line options, I would be obliged


text:
Q: Can you explain why this javascript is incorrect? I am expecting this script to return an alert if the Expiry Date is in the past, otherwise to show OK.
I was not expecting the script to fall into the Else "Error" statement.
Can anyone explain what is going on?
<!DOCTYPE HTML>

A: Date() returns a string. You can't compare it to a date.
Replace
var currentDate = Date();

with
var currentDate = new Date();

(fix also the obvious typo that was pointed in comment by Davin Tryon)


text:
Q: A word that describes an opportunity for significant influence on culture or society I am looking for a word that describes a significant opportunity to influence based on a unique confluence of events or timing.  More specifically to significantly influence culture or society.

A: Consider watershed:

an event or time when important changes happen in history or in your
  life

(Longman)
Example:

The 1932 election represented a watershed in American politics.

If a phrase is OK, critical juncture might work.

juncture: a point of time, esp. one made critical by a concurrence of
  circumstances

(http://www.thefreedictionary.com/juncture)
Example:

The 1930s was a crucial time of change in Latin America, a "critical
  juncture" in David Collier's and Ruth Berins Collier's terms.

(source on Google Books)

A: While the answers which preceded mine have made some good suggestions, I think the words paradigm shift describe quite aptly what you are describing.
In his seminal work, The Structure of Scientific Revolutions, Thomas Kuhn takes great pains to elucidate the phenomenon of a paradigm shift, which takes place when a confluence of events and timing create the possibility for culture and society to be influenced significantly for centuries.
The Copernican Revolution was one such paradigm shift. The invention of the atom bomb was another, as was the germ theory of disease.
Once Copernicus and his theory of the sun being the center of our solar system attracted a critical mass of people within the scientific community who agreed with his theory, the scientific revolution in astronomy received a powerful kick in the pants.
In essence, a paradigm shift is a novel and unfamiliar perspective for viewing a phenomenon, and most of the people in a given culture and society cannot appreciate that perspective, at least at first. With the right confluence of events and sometimes serendipitous timing, however, the new perspective (which came about primarily through "thinking outside the box," as we say today) begins to take hold, gather momentum, and sometimes takes off, paving the way for a magnitude of change, sometimes for the good and sometimes not.
I suggest the subsequent change is frequently a combination of both good and bad outcomes, with the ripple effects sometimes being nearly impossible to predict. I imagine the first scientists (and there must have been thousands of them) who worked at harnessing the power of the atom, for example, could not fully appreciate its potential for destroying life as we know it on plant Earth through the insanity of mutually assured destruction.

A: The culture or society is at a turning point or a crossroads.
Turning point:

a point at which a significant change occurs (MW)

Crossroads:

A crucial point: "At midlife, couples are at a crossroads of change, just as individuals are" (TFD)

At a crossroads typically implies that a decision must be made, while a turning point doesn't carry that connotation as strongly.


text:
Q: Formal Language syntax Here is the question:
Show that:
L = {0m1n, m > 1, n > 1, n < m } , where m & n are superscripts
is not regular.
I am not sure what superscripts mean in this situation? Does it mean something like this:
0^5 = 00000 or 1^7 = 1111111

P.S. How can I show superscripts in SO??


text:
Q: Slow import of data in mysql using mysqlimport in version 5.7.31 on Ubuntu 18.04 Slow import of data in mysql using mysqlimport in version 5.7.31 on Ubuntu 18.04
Im loading genetic data from Ensembl and following the directions here
https://m.ensembl.org/info/docs/webcode/mirror/install/ensembl-data.html.
this is the command I am using
/data/mysql/bin/mysqlimport -u mysqldba --fields-terminated-by='\t' --fields-escaped-by=\\ homo_sapiens_core_100_38 -L allele_synonyms.txt

A few of the tables are massive. 40GB, 90GB and ~300GB. I didn't expect this to go fast but it seems to be going way too slow. I can import 10GB tables in an hour but this 40GB one is killing me. I even used slice to make small chunks and load them but at 20GB it seems to get infinitely longer. Like days to load the data and that's when I add just one more 5GB chunk after 20GB is loaded.
I have followed other suggestions like this post here Improve performance of mysql LOAD DATA / mysqlimport?
I have turned off slow query logging in mysql.cnf and tried other suggestions found on Stack Overflow like increasing the buffers.
Im using a very large space for my temp files
I'm specifically using mysqlimport on a txt.file
The 40GB file has like 800,000,000 Rows so its a lot of data.
I have tried adding --num-threds=4
The machine has decent specs 4 cores and 14GB ram

A: Im not sure if this is the correct answer but this is what worked for me. My data was like 99.9% read so I was trying to us MyISAM for the massive tables. By simply changing the tables to InnoDB it worked. I did this for any table over 25GB and it worked.


text:
Q: When a country doesn't recognize another country diplomatically In my language, there is a political term which is used to indicate that in diplomatic relationships a country doesn't consider the other country as a legal or true country. The only translation I found for it is: "To recognize a country officially / diplomatically".
But, how shall one say it? Let me ask my question in another way; which one of the following sentences sounds more idiomatic:

A) (The country) X does not recognize (the country) Y.
B) (The country) X does not recognize (the country) Y officially.
C) (The country) X does not recognize (the country) Y diplomatically.

If there is a more natural way, then please let me know about it.

A: As TRomano points out in his comment, "does not recognize" is natural English for this context.  This is course, fairly formal and diplomatic language, and in general would not be used outside of government or politics.

The United States government did not formally recognize the Communist government of the People's Republic of China until 1979, although it still does not recognize their claim to Taiwan and various other islands in the South Pacific.

A: (The country) X does not have diplomatic relations with (the country) Y.


text:
Q: C# Inconsistent Security Group Membership I apologize for how open ended I'm sure this will end up. I'll try to break this up in manageable chunks.
I'm writing a program that deals with SCCM. This program is locked down by security groups.
If you are not a member of the 'Server Operators' group, you don't get in. Simple. I've been testing for awhile on my dev machine (a Dell that is on wireless) with no issues.
When I released a beta, I found that under certain circumstances the program will not pick up on the user's security group membership and therefore deny access.
I was able to reproduce the issue, it seems machines on wireless tend to have this issue. Though, it's more complicated than that.
-Freshly imaged machines seem to have this issue
-Not all wireless machines; my dev machine is wireless
-One desktop (no wireless) has this issue. (It's at a remote site, so I can't really pick that one apart) I think it's a fresh image as well. I did however test on another computer at the same site - worked fine.
-Connecting to ethernet seems to have an effect - 75% of the time it fixes the issue somehow - after a bit of a wait. (Works on both ethernet and wireless at that point)
I've been trying to get a breakpoint set on one of these machines so I can see what is going on. Problem is, by the time I get VS.net installed the problem solves itself. I know (very little) about remote debugging - currently looking into that. This scenario makes me wonder if it's update related (the image is fairly up to date, maybe a month or two out?)
I also wrote a small utility that tests the login procedure (using the same code) and it finds the security group every time. Wat.
Code for finding security group of a user:
(courtesy of Stack :) )
static bool IsUserMemberOf_(string user, string group)
{ // (I realize the user parameter is superfluous in this case)

    try
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + TC.act_Domain, TC.act_AD_User, TC.enc_GetADPassword());
        DirectorySearcher mySearcher = new DirectorySearcher(entry);
        mySearcher.Filter = "(&(objectClass=user)(|(cn=" + TC.act_AD_User + ")(sAMAccountName=" + TC.act_AD_User + ")))";
        SearchResult result = mySearcher.FindOne();

        foreach (string GroupPath in result.Properties["memberOf"])
        {

            if (GroupPath.Contains(group))
            {

                return true;
            }
        }
    }
    catch (DirectoryServicesCOMException)
    {

    }
    return false;
}

I've also tried another method (using Principal.IsMemberOf() ), which had the same result. I've also investigated DNS/Network problems. Not ruling it out, but doesn't seem to be a factor in the testing I've done.
I'm at a loss. If anyone has any thoughts, by all means please lay them on me.
Thanks

A: Yeah, it was the .net version. Our image starts with .net 4.0. Throwing 4.5.2 at it clears it right up. I would have expected an error at runtime, but I guess not.
... I'll show myself out


text:
Q: failed to converted raw H264 to mp4 wiht FFMPEG and playback it I am trying to convert raw video file captured from Cisco EX60 to valid MP4 file.
I use the following command
ffmpeg -f rawvideo -pix_fmt yuv420p -s:v 1920x1080 -r 25 -i input2 -vcodec libx264 output2.mp4
and get
libpostproc    54.  0.100 / 54.  0.100
[rawvideo @ 0000000000703920] Estimating duration from bitrate, this may be inac
curate
Input #0, rawvideo, from 'input2':
  Duration: 00:00:00.20, start: 0.000000, bitrate: 630883 kb/s
    Stream #0:0: Video: rawvideo (I420 / 0x30323449), yuv420p, 1920x1080, 622080
 kb/s, 25 tbr, 25 tbn, 25 tbc

File 'output2.mp4' already exists. Overwrite ? [y/N] y
[libx264 @ 00000000007115e0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2
AVX FMA3 AVX2 LZCNT BMI2
[libx264 @ 00000000007115e0] profile High, level 4.0
[libx264 @ 00000000007115e0] 264 - core 148 r2638 7599210 - H.264/MPEG-4 AVC cod
ec - Copyleft 2003-2015 - http://www.videolan.org/x264.html - options: cabac=1 r
ef=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed
_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pski
p=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 deci
mate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_
adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=2
5 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.6
0 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'output2.mp4':
  Metadata:
    encoder         : Lavf57.18.100
    Stream #0:0: Video: h264 (libx264) ([33][0][0][0] / 0x0021), yuv420p, 1920x1
080, q=-1--1, 25 fps, 12800 tbn, 25 tbc
    Metadata:
      encoder         : Lavc57.15.100 libx264
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> h264 (libx264))
Press [q] to stop, [?] for help
[rawvideo @ 00000000007101c0] ****Invalid buffer size, packet size 220075 < expected
 frame_size 3110400
Error while decoding stream #0:0: Invalid argument****
frame=    5 fps=2.5 q=-1.0 Lsize=    6514kB time=00:00:00.12 bitrate=444706.9kbi
ts/s
video:6513kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing
overhead: 0.013209%
[libx264 @ 00000000007115e0] frame I:1     Avg QP:35.99  size:1334571
[libx264 @ 00000000007115e0] frame P:4     Avg QP:35.00  size:1333616
[libx264 @ 00000000007115e0] mb I  I16..4:  0.0%  0.0% 100.0%
[libx264 @ 00000000007115e0] mb P  I16..4: 98.7%  0.0%  1.3%  P16..4:  0.0%  0.0
%  0.0%  0.0%  0.0%    skip: 0.0%

with
Invalid buffer size, packet size 220075 < expected
     frame_size 3110400
    Error while decoding stream #0:0: Invalid argument**

inside
When I use just
ffmpeg -f h264 -i input -vcodec copy -r 25 outfile.mp4
It replace initial IFrame with B-frames so I cannot playback it. I can view it with VCL, but not with Windows Media player, for example.
What is wrong with the command?
Thanks
Efim

A: Stream #0:0: Video: h264 (libx264)

This is the source video stream, which is already encoded with h264. So it's unlikely that rawvideo will work. You actually have to decode the stream in order to encode it again.
As for why you can't play it back in Windows Media Player, please check the H.264 encoding guide. By default the highest profile is used when encoding as h264 which is not compatible with every device and player. For maximum compatibility, add the following options:
-profile:v baseline -level 3.0


text:
Q: Language stored in Useprofile.language field applied on user log in I need to set language for user in 2 cases:

*

*User logs in (django checks his UserProfile field for language field value and sets the proper lang)

*Users chenges lang in "user preferences" page.

I've tried with "user_logged_in" signal receiver
from django.utils import translation
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in

@receiver(user_logged_in)
def setlang(sender, **kwargs):
    translation.activate(kwargs['user'].get_profile().language)
    kwargs['request'].session['django_language'] = translation.get_language()

This works fine until I restart my django instance. Though session is alive (no need to log in again) website is being displayed in language specified in settings.LANGUAGE
I think the same applies to situation #2 (on user preferences form save())

A: Following up to Timmy's answer you can find an already published middleware that does the job for you!
The translation of a Django app with the preferred language selected by a registered user can be done with the middleware django-user-language-middleware. This allows easy translation of your Django app by looking at the selected language in the user.language field.
Usage:

*

*Add a language field to your user model:
class User(auth_base.AbstractBaseUser, auth.PermissionsMixin):
    # ...
    language = models.CharField(max_length=10,
                                choices=settings.LANGUAGES,
                                default=settings.LANGUAGE_CODE)

*Install the middleware from pip:
pip install django-user-language-middleware

*Add it to your middleware class list in settings to listen to requests:
MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'user_language_middleware.UserLanguageMiddleware',
    ...
]

I hope this may help people landing on this question in the future.

A: I think it's better if you use middleware to achieve this. Django provides a way to add in hooks at various places throughout a request so that you can add custom code.
In your case: check on every request if there is a language variable in the session, if not, fetch the users language preference from the database and save it to the session variable. Check on a save signal whether or not the user has changed their preference; if so, update the session variable (you might have problems getting access to the request from the model level so it might be better to do this in the view).

A: I've used this snippet, but it conflicts with the Regular LocaleMiddleware, and thus I can't add a multilingual content farm.
http://django-hotclub.googlecode.com/svn-history/r708/trunk/pinax/profiles/middleware.py


text:
Q: How to specify parse query to get parse objects only if they have been updated? [Android] We are using parse server and mongodb. Users request ParseObjects and store them locally on their device with realm. Later on users have to check for updates from that objects. ParseObject offers the updatedAt attribute, so we would request for objects where the updatedAt has been changed. For a single object the query would look something like:
ParseObject object = new ParseObject();
ParseQuery<ParseObject> query = new ParseQuery<>(ParseObject.getQuery());
query.whereEqualTo("objectId", "9jK7lGt7U").whereGreaterThan("updatedAt", object.getUpdatedAt());
ParseObject queriedObject = query.findInBackground();

We have modified the model of the query for this post. ParseObject is the pseudo of our model.
As said before, the query has to be modified to work with many objects. The objectIds and updatedAts are known. How does the query must look like?

A: You can make a query fromLocalDatastore,
ParseObject queriedObject = query.findInBackground();
query.fromLocalDatastore();

And after the query on each object, you can call on each object fetchIfNeeded
On each object that you recieve you can do that:
object.fetchIfNeededInBackground(new GetCallback<ParseObject>() {
  public void done(ParseObject object, ParseException e) {
    // all fields of the object will now be available here.
  }
});

With your code you can write this:
ParseQuery<ParseObject> query = new ParseQuery<>(ParseObject.getQuery());
query.whereEqualTo("objectId", "9jK7lGt7U").whereGreaterThan("updatedAt", object.getUpdatedAt());
query.fromLocalDatastore();
ParseObject queriedObject = query.findInBackground();

for( int i=0; i < queriedObject.length-1; i++)
{
    queriedObject[i].fetchIfNeededInBackground();
}

I hope my answer solve your problem


text:
Q: ELMAH Exceptions in 3-layer application In a 3-layer application working on, I have the business layer talking to DB, validating data, and sending back results to Controllers.
Calls to DB are wrapped inside a try/catch. Is it recommend to throw exceptions at that layer? Will ELMAH catch it?
Thanks

A: Yes, if the situation is exceptional (ie. cannot connect to DB). If the exception propagates up then ELMAH will catch it.
Do not use exception for 'business' errors, like couldn't find a certain record in the table. Returning null in this situation is probably better.


text:
Q: Quiero guardar datos en un vector de tipo char, pero no me deja guardarlo en sus posiciones. Como podria hacer? Quiero guardar datos en un vector de tipo char, pero no me deja guardarlo en sus posiciones.
Como podria hacer ?

char *E[3];

for(i=0;i<2;i++){
printf("INDRUCUCE VALOR PARA ARRAY CHAR \n");
scanf("%s",E[i]);}

E[1]="SI FUNCIONA";

/*si asigno esto si imprime bien pero quiero guardar y despues imprimir */
printf("EL ARRAY 2 ES (%s)\n",E[1]);

A: Tiene muchos errores tu código, una cadena de caracteres en C en un ARRAY de caracteres, con cada letra en una posicion y terminando en '\0' como último elemento. Te paso un ejemplo de como declaro una cadena ( un char[] ), escaneo letra por letra e imprimo la cadena completa o alguna letra que quiera:
int main (){

  char E[3]; // ARRAY de caracteres (o cadena)
  int i; // hay que declarar i antes de usar el for

  for (i = 0; i <= 2; i++){
    printf ("INDRUCUCE VALOR PARA ARRAY CHAR \n");
    scanf ("%s", &E[i]); // leyendo caracter por caracter
  }

  printf ("El el array de chars es: %s\n", E); // imprimo la cadena
  printf ("La ultima posicion es: %s", &E[2]); // imprimo el ultimo caracter
}

A: Recuerda que una cadena de caracteres es un arreglo de caracteres (char[]) o si lo prefieres un puntero a caracteres contiguos en memoria (char*).
En el primer caso, un arreglo es una variable. A toda variable le corresponde un espacio en la memoria.
Por lo tanto, puedes ejecutar el siguiente código:
char buffer[20];
scanf("%s", buffer);

En el segundo caso (char*), no puedes simplemente hacerlo así:
char *cadena;
scanf("%s", cadena);

Porque un puntero es una variable que solo guarda una dirección de memoria.
Necesitas que el puntero apunte a una región de memoria válida. Bien podría apuntar a un arreglo (en el stack), a un literal o a una parte del heap.
// Memoria en el stack
char buffer[20];

char *cadena = buffer;
scanf("%s", cadena);
...

// Reservas memoria del heap
cadena = malloc(20 * sizeof(char));
scanf("%s", cadena);
...
// Cuando no la usas más debes liberarla
free(cadena);

Ahora podrás entender el problema más fácilmente.
char *E[3] es un arreglo de 3 punteros y lo explicado en la sección anterior también aplica aquí.
Los 3 punteros están sin inicializar. Por lo tanto apuntan a direcciones indeterminadas.
Así que nuevamente, necesitas un lugar donde guardar las cadenas.
Puedes hacerlo así:
// No es necesario que sean todas del mismo tamaño
char cadena1[20];
char cadena2[20];
char cadena3[20];

// Al declarar el arreglo lo puedes inicializar así
char *E[3] = { cadena1, cadena2, cadena3 };

for(i=0;i<2;i++){
    printf("INDRUCUCE VALOR PARA ARREGLO CHAR \n");
    scanf("%s",E[i]);
}


text:
Q: Is it possible to find previous saved times used 'datetime.datetime.now()' to save in Python? I am reading some data and save it into the .xlsx files using following code:
name_file = path + str(datetime.datetime.now()).replace(':','-').replace(' ','_')
point_index = name_file.find('.')
name_file = name_file[:point_index ] + '.xlsx'
link = 'http://...'
resp = requests.get(link)
output = open(name_file, 'wb')
output.write(resp.content)
output.close()

What I want to do is to load last 2 or 3 or any number of saved files and compare them together. if we consider name_file = path + str(datetime.datetime.now()).replace(':','-').replace(' ','_') consist the name of the last saved file, how is it possible to load the previous file of this file?
I also must mention that the name of the files don't have regular distances. They look like below:
2020-08-02_10-23-46.xlsx
2020-08-02_10-23-58.xlsx
2020-08-02_10-24-09.xlsx
2020-08-02_10-24-49.xlsx
2020-08-02_10-25-00.xlsx

A: If all xlsx files under the current directory are generated from the process you described, then I suggest you simply sort the files by their name (which will also put them in chronological order due to the way you named them), then select the last 2 or whatever number of files you want.
For example:
import os
selected = sorted(filename for filename in os.listdir('.') if filename.endswith('.xlsx'))[-2:]

A: You can try something like
return sorted(os.listdir(path), key=lambda x: os.path.getctime(os.path.join(path, x)))[-3:]
where -3: is amount of files from tail (latest 3). You can use any other sort of slicing as well.


text:
Q: How to mock up a virtual display on a Windows 10 VM Running from an amazon VM with windows 10, I want to mirror the screen with an application through a web interface.
Ideally I would like to Mock up a custom screen that mirrors the clients resolution, in order to send a picture that would result in a full screen web page.
There is a basic default VGA monitor available with the VM, but this is not configurable. And is useless in regards to color resolution and dimmensions.
It looks like the normal solution to mock up a fake screen is to buy a fake plug an put into the screen card, which I obiously cannot do an a virtual Amazon server. 1 2
My question is:
Are there any good software in existance for mocking up a screen or an entire graphics card virtually. Or a native trick in windows 10 that can do it without having physical display ports available?

A: The following free products create a virtual screen and could perhaps be a solution.
You will need to see if they work under this particular environment.

*

*spacedesk
A primary machine runs a Windows service and the WDDM driver that appears
as an additional graphics adapter to Windows 10 whose contents
are captured, compressed and transmitted over the LAN to the spacedesk
secondary machine(s).

*ZoneScreen
ZoneScreen consists of two parts: kernel-mode ZoneScreen Virtual Display Driver
emulating a video card with monitor attached to it, and user-mode ZoneScreen Wizard
running server side and responsible for capturing the image, transmitting it over
the network, and drawing it at another computer (called client).
The client machine has only the ZoneScreen Wizard running in client mode.


text:
Q: Python Dash without using external URLs for js I am interested in using Dash to make some web applications for displaying data. I want to run this entirely locally without the references to unpkg.com/[...].  I realize that there is a relative package path  (pointing to local files) and an external package path (pointing to external locations), but I don't understand how I can switch from external to relative.
Where is this documented and/or does anyone have a solution for running Dash without the references to these packages?
Thanks.

A: From the dash docs:

Rendering dash apps offline
The JavaScript and CSS bundles that are included in Dash component
  libraries are hosted on the web (on the unpkg CDN) and in the Python
  packages that you install. By default, dash serves the JavaScript and
  CSS resources from the online CDNs. This is usually much faster than
  loading the resources from the file system. However, if you are
  working in an offline or firewalled environment or if the CDN is
  unavailable, then your dash app itself can serve these files. These
  files are stored as part of the component's site-packages folder.
  Here's how to enable this option:
from dash import Dash

app = Dash()

app.css.config.serve_locally = True
app.scripts.config.serve_locally = True


text:
Q: Assigning memory for contiguous 2D array I am trying to create a generic function which when called allocated contiguous memory for a dimensional array. Goal is to achieve something like below

so to achieve it - equation I am using is
Type **pArray;
int total_elements = ((rows * cols) + rows);
pArray = (Type **) malloc(total_elements * sizeof(Type));

I am also confused with respect to accessing elements part. I am finding it hard to visualize how below code will fill the elements of above array
for (row = 0; row < dim0; ++row)
   {
      for (col = 0; col < dim1; ++col)
      {
         /* For this to work Type must be a 1D array type. */
         for (ix = 0; ix < (int)(sizeof(item)/sizeof(item[0])); ++ix)
         {
            /*            printf("%4d\n", testValue); */
            ppObj[row][col][ix] = testValue;
            if (testValue == SCHAR_MAX)
               testValue = SCHAR_MIN;
            else
               ++testValue;
         }
      }
   }

Goal is not to create below array format

A: This won't work. You assume your Type * has the same size as your Type which is most of the time not true. But, what do you need the row pointers for, anyway? My first implementation idea would be something like this:
typedef struct TypeArray
{
    size_t cols;
    Type element[];
} TypeArray;

TypeArray *TypeArray_create(size_t rows, size_t cols)
{
    TypeArray *self = calloc(1, sizeof(TypeArray) + rows * cols * sizeof(Type));
    self->cols = cols;
    return self;
}

write getter and setter using e.g. self->element[row * self->cols + row].
[edit]: Following this discussion here it is doable like this:
typedef long long Type;

Type **createArray(size_t rows, size_t cols)
{
    size_t r;

    /* allocate chunk: rows times the pointer, rows * cols times the value */
    Type **array = malloc(rows * sizeof(Type *) + rows * cols * sizeof(Type));

    /* calculate pointer to first row: point directly behind the pointers,
     * then cast */
    Type *row = (Type *) (array + rows);

    /* set all row pointers */
    for (r = 0; r < rows; ++r)
    {
        array[r] = row;
        row += cols;
    }

    return array;
}

Usage could look like this:
int main()
{
    Type **array = createArray(3, 4);

    for (int r = 0; r < 3; ++r)
    {
        for (int c = 0; c < 4; ++c)
        {
            array[r][c] = (r+1) * (c+1);
        }
    }
    for (int r = 0; r < 3; ++r)
    {
        for (int c = 0; c < 4; ++c)
        {
            printf("array[%d][%d] = %lld\n", r, c, array[r][c]);
        }
    }

    free(array);
    return 0;
}

This assumes that no type needs a bigger alignment than a data pointer, otherwise you would have to calculate an amount of padding bytes to insert after your pointers. To be safe, you could use the sizeof(Type) and some modulo calculation for that (inserting the padding bytes using a char * pointer), but that would waste a lot of memory if your Type is for example a big struct.
All in all, this assignment is written by a really really clueless teacher.


text:
Q: Binding in C# (MVVM + WPF) I want to show a list box with an image and a string as list box items.
To do so I bind a list of ThemeLayer as ItemsSource and defined an ItemTemplate.
XAML
<ListBox x:Name="DataLayerList" SelectionMode="Extended"
         ItemsSource="{Binding LayersFiltered, Mode=OneWay}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Path=ImagePath}" Height="16"/>
                <TextBlock Text="{Binding Path=Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ThemeLayer are defined as such:
C#
public class ThemeLayer
{
    public readonly string Name;
    public readonly string Id;
    public readonly string Type;
    public readonly string ImagePath;

    public override string ToString()
    {
        return Name;
    }

    public ThemeLayer(string name, string id, string type, string image)
    {
        Name = name;
        Id = id;
        Type = type;
        ImagePath = image;
    }
}

and the list LayersFiltered contains object of ThemeLayer similar to this:
 new ThemeLayer("Place","eb760ca1bb494d2887c5d8c51ccc417a", "image", "ImageLayer16.png")

When I run my project then I am getting the list box filled with items, but I cannot see a single one. I only know because hovering over the list reveals the different lines of the list box items.
Looking at XAML Binding Failures I get back that ImagePath and Name (defined in the ItemTemplate) cannot be found on object of type ThemeLayer, even though the objects in LayersFiltered certainly are of type ThemeLayer and each of them has a property Name and ImagePath.
The ThemeLayer class and the class defining the list of ThemeLayer are both in my Models folder, and LayersFiltered is a list object within my ViewModel.
How do I have to define the XAML that I get images and names shown?
One more thing:
The images to be shown in the list box are situated within the project, at a folder Images. Is it okay to simply reference the image by its name, as shown above, or does that need to be something along the line of "/Images/filename.png"?

A: You need to bind to properties rather than fields. Change this...
public readonly string Name;
public readonly string Id;
public readonly string Type;
public readonly string ImagePath;

to be
public string Name { get; }
public string Id { get; }
public string Type { get; }
public string ImagePath { get; }

These properties are read only, just like the fields they replace.


text:
Q: Irregular DIV shape, cross browser platform support I'm trying to make a irregular shaped DIV, but the only method that I found out to accomplish this is by using the polygon() function. Unfortunately, IE and FF don't support it. I don't need all versions to be supported, but at least the latest, of IE, FF and Chrome.
What I'm trying to accomplish is basically this - with a black border between the white and the red:

The white part would be the navigation menu (home, contact, about, etc) and the red portion would be the content, however, I need ALL the red part to be clickable (meaning: I can put a link anywhere and the user can click with ease...)
The end result should look something like this:

Also, the white div needs to maintain the angle independent of the size of the viewport, because the site will be responsive.
How could I achieve this?

A: Let's make the sloped sidebar with a transform:

*

*The sidebar is given position: fixed and will stay in one place relative to the viewport

*The sidebar is given transform: rotate(20deg) to rotate it and create a sloped shape

*transform-origin: 100% 0% helps position the sidebars shape where we want it (read more on transform-origin here)

*The nav inside the sidebar is given transform: rotate(-20deg) to cancel out the rotation for the text

*Max width / height is used to keep the size of the sidebar flexible but not too large or small
Example

html,
body {
  margin: 0;
  background: #EEE;
}
.sidebar {
  height: 200%;
  width: 100%;
  max-width: 400px;
  min-width: 250px;
  display: block;
  background: #FFF;
  transform: rotate(20deg);
  transform-origin: 100% 0%;
  position: fixed;
  left: 0;
  top: 0;
  border-right: solid 2px #000;
}
/*Demo purposes*/

.sidebar > nav {
  position: absolute;
  top: 100px;
  left: 30%;
  width: 300px;
  transform: rotate(-20deg);
}
.sidebar > nav > a {
  display: block;
}
.content {
  background: #CCC;
  text-align: right;
}

    Link
    Link
    Link
    Link
    Link
    Link

  I am covered by the sidebar!

A: I would probably do this with SVG, which is widely supported. You could also achieve the angled effect with CSS transformations. I'm afraid your question is not specific enough to invite a more detailed answer, but hopefully those links will help you get started.

A: I'm not sure this is the solution you want but you could easily achieve this by simply overlaying a png with an opaque angled white area like the one attached.  It's only 1.8k at 300 x 800px and I don't see why you couldn't scale it or make it responsive with a little effort.
http://zuma-design.com/shared/angle.png


text:
Q: How to read number of rows and columns in a CSV file using VBA I have more than 100 CSV/text files (vary in size between 1MB to 1GB). I Just need to create a excel sheet for each csv file, presenting:

*

*name of columns

*types of column i.e. numeric or string

*number of records in each column

*min & max values & length of each column

so the output on a sheet would be something like this (I can not paste table image here as I am new on this site, so please consider below dummy table as excel sheet):
         A           B         C             D           E          F           G

1   Column_name    Type     #records     min_value   max_value  min_length  max_length
2   Name           string   123456       Alis        Zomby          4         30
3   Age            numeric  123456       10          80             2          2

Is is possible to create any vba code for this? I am at very beginner stage so if any expert can help me out on code side, would be really helpful.
thanks!!!

A: You could try writing complex VBA file- and string-handling code for this; my advice is: don't.
A better approach is to ask: "What other tools can read a csv file?"
This is tabulated data, and the files are quite large. Larger, really, than you should be reading using a spreadsheet: it's database work, and your best toolkit will be SQL queries with MIN() MAX() and COUNT() functions to aggregate the data.
Microsoft Access has a good set of 'external data' tools that will read fixed-width files, and if you use 'linked data' rather than 'import table' you'll be able to read the files using SQL queries without importing all those gigabytes into an Access .mdb or .accdb file.
Outside MS-Access, you're looking at intermediate-to-advanced VBA using the ADODB database objects (Microsoft Active-X Data Objects) and a schema.ini file.
Your link  for text file schema.ini files is here:
http://msdn.microsoft.com/en-us/library/ms709353%28v=vs.85%29.aspx

...And you'll then be left with the work of creating an ADODB database 'connection' object that sees text files in a folder as 'tables', and writing code to scan the file names and build the SQL queries. All fairly straightforward for an experienced developer who's used the ADO text file driver.
I can't offer anything more concrete than these general hints - and nothing like a code sample - because this is quite a complex task, and it's not really an Excel-VBA task; it's a programming task best undertaken with database tools, except for the very last step of displaying your results in a spreadsheet.
This is not a task I'd give a beginner as a teaching exercise, it demands so many unfamiliar concepts and techniques that they'd get nowhere until it was broken down  into a structured series of separate tutorials.


text:
Q: CumulusCI: Connect to org by specifying username and password right in command line According to CumulusCI docs it is possible to connect to persistent org, but this requires opening web browser and typing your creds in SF log-in form.
Is there any way to provide username and password right into cci command line (despite how insecure it might seem at first glance)? E.g. I want to call cci command from our scheduled ci pipeline by providing creds from secret variables to trigger some data load into test sandbox over night.
Any help would be appreciated. Thanks

A:
Is there any way to provide username and password right into cci command line (despite how insecure it might seem at first glance)?

No, there isn't. CumulusCI does not implement the Username-Password OAuth flow, and we won't implement it because it's completely insecure.
To connect to a persistent org, we recommend using the JWT flow with a certificate. This is the same approach used by Salesforce DX. It is secure, and while it's a bit of a pain to setup, it works reliably and indefinitely with no user interaction after that setup process.


text:
Q: Accessing assemblies in directory other than bin from razor view pages I have a simple ASP.NET MVC 4 Project. I want to load assembly from 'lib' folder in root of my project instead of 'bin' folder.
I add <probing privatePath="lib" /> to my web.config. I have custom.dll in 'lib' folder.
Now i can write using custom.namespace in my classes and it works fine but i cannot add this namespace in razor view pages.
In other words @using custom.namespace in my razor view does not work. If i place above dll in 'bin' folder (not 'lib' folder), I can use it in view pages.
How can i load assembly in razor view page when i use probing in web.config?


text:
Q: DocuSign "View Documents" button does not reflect branding - company name We are a third party service provider that relies on the branding feature of DocuSign to appear that all documents come from our clients.  For the most part, this works very well.  The only issue we are struggling with is the loss of branding when a signer clicks on the 'view documents' button in an email.  The landing page picks up the name of our firm instead of our client's company name.
For example, the emails we send look like:
Sender = John Smith at "ABC Company" (our client)
However when the sender clicks the "View Documents" button, the landing page request for signature dialog box reads
Sender = John Smith at "XYZ Company" (our company's name)
DocuSign has directed us to the Master Resource Files to implement this correction.  We have downloaded the files, but it is unclear where we need edit to affect this change.  Before we resort to the "trial and error" method, we thought someone here may be able to advise us.
Thanks,
Steve

A: I'm not sure if it's possible to have that 'landing page' display the Sender's company name instead of the Account's company name. However, you could remove the 'sender' information from that 'landing page' altogether, by setting the value of DocuSign_HideIntroductionSender to true in the DocuSign_SignResources.xml file.


text:
Q: How to get json data from rails to react js? I have tried using ajax call to get data from rails to react but the state was not updating. When I tried to call state it's giving me an error that it is undefined. I have referred other questions in stack overflow but couldn't solve my problem. Here is my my ajax request.
fetchData: function(){
      $.ajax({
        url: '/orders',
        dataType: 'json',
        type: 'GET',
        success: function(result) {
          this.setState({orders: result});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    }

Click this link to view the error

<button  onClick={this.fetchData}>Filter</button>

              {
                Object.keys(this.state.orders).map(function(key){
                  return
{this.state.orders[key]}

                }, this)
              }

A: You are trying to render the order object as a string. React doesn't like that. Try only rendering a value, not the whole order object, for example like this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { orders: {
      first: { id: 311, name: 'Eric' },
      second: { id: 420, name: 'Andre' },
    }};
  }
  render() {
    return(

      {
        Object.keys(this.state.orders).map(function(key){
          return
{this.state.orders[key].id}

        }, this)
      }

    );
  }
}

ReactDOM.render(<Example />, document.getElementById('View'));

A: The error says that you are trying to render something that is an object, which is not possible. The problem can be found here:
return
{this.state.orders[key]}

If you want to render this, then this.state.orders[key] should be either a JSX element or a value (a string for example), and it doesn't seem to be the case. I don't know what do you assign to orders with this.setState({orders: result});. If you show us the value of result we might be able to help more, but right now the problem is that this.state.orders[key] is an object.


text:
Q: Oracle: Need to calculate rolling average for past 3 months where we have more than one submission per month I've seen many examples of rolling averages in oracle but done do quite what I desire.
This is my raw data
DATE            SCORE   AREA
----------------------------
01-JUL-14       60      A
01-AUG-14       45      A
01-SEP-14       45      A
02-SEP-14       50      A
01-OCT-14       30      A
02-OCT-14       45      A
03-OCT-14       50      A
01-JUL-14       60      B
01-AUG-14       45      B
01-SEP-14       45      B
02-SEP-14       50      B
01-OCT-14       30      B
02-OCT-14       45      B
03-OCT-14       50      B

This is the desired result for my rolling average
MMYY        AVG     AREA
-------------------------
JUL-14      60      A
AUG-14      52.5    A
SEP-14      50      A
OCT-14      44      A
JUL-14      60      B
AUG-14      52.5    B
SEP-14      50      B
OCT-14      44      B

The way I need it to work is that for each MMYY, I need to look back 3 months, and AVG the scores per dept. So for example,
For Area A in OCT, in the last 3 months from oct, there were 6 studies, (45+45+50+30+45+50)/6 = 44.1
Normally I would write the query like so
SELECT
  AREA,
  TO_CHAR(T.DT,'MMYY') MMYY,
  ROUND(AVG(SCORE)
    OVER (PARTITION BY AREA ORDER BY TO_CHAR(T.DT,'MMYY') ROWS BETWEEN 2 PRECEDING AND CURRENT ROW),1)
    AS AVG
    FROM T

This will look over the last 3 enteries not the last 3 months

A: One way to do this is to mix aggregation functions with analytic functions.  The key idea for average is to avoid using avg() and instead do a sum() divided by a count(*).
  SELECT AREA, TO_CHAR(T.DT, 'MMYY') AS MMYY,
         SUM(SCORE) / COUNT(*) as AvgScore,
         SUM(SUM(SCORE)) OVER (PARTITION BY AREA ORDER BY MAX(T.DT) ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) / SUM(COUNT(*)) OVER (PARTITION BY AREA ORDER BY MAX(T.DT) ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
  FROM t
  GROUP BY AREA, TO_CHAR(T.DT, 'MMYY') ;

Note the order by clause.  If your data spans years, then using the MMYY format poses problems.  It is better to use a format such as YYYY-MM for months, because the alphabetical ordering is the same as the natural ordering.

A: You can specify also ranges, not only rows.
SELECT
  AREA,
  TO_CHAR(T.DT,'MMYY') MMYY,
  ROUND(AVG(SCORE)
    OVER (PARTITION BY AREA
      ORDER BY DT RANGE BETWEEN INTERVAL '3' MONTH PRECEDING AND CURRENT ROW))
    AS AVG
    FROM T

Since CURRENT ROW is the default, just ORDER BY DT RANGE INTERVAL '3' MONTH PRECEDING should work as well. Perhaps you have to do some fine-tuning, I did not test the behaviour regarding the 28/29/30/31 days per month issue.
Check the Oracle Windowing Clause for further details.

A: SQL> WITH DATA AS(
  2  SELECT to_date('01-JUL-14','DD-MON-RR')  dt,     60   score,    'A' area FROM dual UNION ALL
  3  SELECT to_date('01-AUG-14','DD-MON-RR')  dt,       45      score,    'A' area FROM dual UNION ALL
  4  SELECT to_date('01-SEP-14','DD-MON-RR')  dt,       45      score,    'A' area FROM dual UNION ALL
  5  SELECT to_date('02-SEP-14','DD-MON-RR')  dt,       50      score,    'A' area FROM dual UNION ALL
  6  SELECT to_date('01-OCT-14','DD-MON-RR')  dt,       30      score,    'A' area FROM dual UNION ALL
  7  SELECT to_date('02-OCT-14','DD-MON-RR')  dt,       45      score,    'A' area FROM dual UNION ALL
  8  SELECT to_date('03-OCT-14','DD-MON-RR')  dt,      50      score,    'A' area FROM dual UNION ALL
  9  SELECT to_date('01-JUL-14','DD-MON-RR')  dt,       60      score,    'B' area FROM dual UNION ALL
 10  SELECT to_date('01-AUG-14','DD-MON-RR')  dt,       45      score,    'B' area FROM dual UNION ALL
 11  SELECT to_date('01-SEP-14','DD-MON-RR')  dt,       45      score,    'B' area FROM dual UNION ALL
 12  SELECT to_date('02-SEP-14','DD-MON-RR')  dt,       50      score,    'B' area FROM dual UNION ALL
 13  SELECT to_date('01-OCT-14','DD-MON-RR')  dt,       30      score,    'B' area FROM dual UNION ALL
 14  SELECT to_date('02-OCT-14','DD-MON-RR')  dt,       45      score,    'B' area FROM dual UNION ALL
 15  SELECT to_date('03-OCT-14','DD-MON-RR')  dt,       50      score,    'B' area FROM dual)
 16  SELECT   TO_CHAR(T.DT, 'MON-RR') AS MMYY,
 17           round(
 18           SUM(SUM(SCORE)) OVER (PARTITION BY AREA ORDER BY MAX(T.DT) ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)/
 19           SUM(COUNT(*)) OVER (PARTITION BY AREA ORDER BY MAX(T.DT) ROWS BETWEEN 2 PRECEDING AND CURRENT ROW),1)
 20           AS avg_score,
 21           AREA
 22    FROM data t
 23    GROUP BY AREA, TO_CHAR(T.DT, 'MON-RR')
 24  /

MMYY    AVG_SCORE A
------ ---------- -
JUL-14         60 A
AUG-14       52.5 A
SEP-14         50 A
OCT-14       44.2 A
JUL-14         60 B
AUG-14       52.5 B
SEP-14         50 B
OCT-14       44.2 B

8 rows selected.

SQL>

From next time, I would expect you to provide the create and insert statements so that we don't have to spend time on preparing a test case.
And, why YY format? Haven't you seen the Y2K bug? Please use YYYY format.


text:
Q: What are the tradeoffs in executing DMLs as in Test code so that tests can be run in parallel We have some classes that do not have the @isTest(isParallel=true) notation, because we are upserting Users, Group Members, etc.
What are the tradeoffs in annoting the class as @isTest(isParallel=true), and performing the upserts in System.runAs(new User(Id = UserInfo.getUserId()){....}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_data_access.htm


text:
Q: I can't define functions in Octave It says that 'x' is not defined and I don't know what to do about it since 'x' is supposed to be an user-defined variable.
I'm new to coding and even newer to Octave and I'm aware that it's an extremely simple, basic question - foolish, even. But even so, if someone could please tell me how to code this, I'd be glad.
function value = sqrmat (x)
  % returns true if x is a square matrix and false otherwise
  if rows(x)==columns(x)
    value=true;
  else
    value=false;
  endif
end

A: Octave has "script files" and "function files". To create a "script file", use a command (or statement) that has no effect.
Put this command at the top of the file, before all defined functions. Examples:
Declare any number...
In this case, the program assigns this number to the variable "ans".
% script
1;

function value = sqrmat (x)
  % returns true if x is a square matrix and false otherwise
  if rows(x)==columns(x)
    value=true;
  else
    value=false;
  endif
end

A simple message...
It could be a notification, a greeting, and so on.
% script
printf("File accessed\n")


text:
Q: Planarize tool in ArcPy? Is there a way to use the Planarize Tool (Editing tool) in a ArcPy script.
I want to create a script for a question I posted and with the help of the community resolved that problem. Please see the link:
Populate cross street name at intersections
I would like to automate this process but using the Planarize tool is a necessity in the process.

A: You can accomplish this function with the Feature to Line (Data Management) geoprocessing tool which will split lines when they intersect each other:
"Where input lines or polygon boundaries touch, cross, or overlap each other at locations other than their start and end vertices, they will be split at those intersections"
[Desktop Help Feature to Line][1]
http://resources.arcgis.com/en/help/main/10.2/index.html#//001700000039000000


text:
Q: Number of binary search tree of height $6$ The number of ways in which the numbers $1, 2, 3, 4, 5, 6, 7$ can be inserted in an empty binary search tree, such that the resulting tree has height $6$, is______ .
Note: The height of a tree with a single node is $0$.

My attempt :
As we need height of tree is $6$, and we have seven distinct number. Other than root node we have $2$ option at each level either node is left node or right node only.
Therefore, total number of BSTs $= 1\times2\times2\times2\times2\times2\times2 =1\times2^6=1\times64=64$ Answer.

Can you explain in formal way or alternative way, please?

A: I think the best way to go is to prove a more general property by induction.
Let $P(n)$ be:
The number of ways in which $n$ numbers $x_1<x_2<\dots<x_n$
can be inserted in an empty binary search tree, such that the resulting tree has height $n-1$ is $2^{n-1}$
$P(1)$ is easy to prove.
Assume that $P(n)$ hold for some $n$ and show that $P(n+1)$ is true.
small hint:

 To do this notice that the root can only be $x_1$ or $x_{n+1}$, then apply the induction hypothesis and it should give you $P(n+1)$.

Then to prove your statement you use $P(7)$.
I hope it helps.

A: You get the maximum height $h=6$ with $7$ nodes, at degenerate cases, that is when the numbers inserted are in ascending or descending order. So, only the insertion orders $(1,2,3,4,5,6,7)$ and $(7,6,5,4,3,2,1)$ will give height $6$. So the answer is $2$.


text:
Q: Можно ли использовать Tor вместо Proxy на php? Задача банальна, есть "зеркало" иностранного сайта, которое в реальном времени берет с него данные, переводит их на русский и выводит пользователю.
Иностранный сайт особо не банит запросы, но иногда все же часть запросов к одному из разделов сайта банится.
Обойти это дело можно через proxy, но, понятное дело, что это не бесплатно.
Можно ли отправлять запросы на этот сайт из своего php скрипта как через tor браузер? Цель одна - избежать блокировок по ip. Я не очень знаком с технологией tor, потому вопрос может быть корявым.

A: С точки зрения скрипта Tor это тот же прокси, соединение с ним ничем не отличается от любого другого соединения через прокси-сервер.
Просто устанавливаете и настраиваете Tor, после чего в качестве SOCKS5-прокси указываете тому, кто делает запросы, адрес 127.0.0.1:9050 (если ничего не меняли в настройках дополнительно). В случае curl это будет выглядеть так:
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:9050');

или так:
curl_setopt($ch, CURLOPT_PROXY, 'socks5://127.0.0.1:9050');

A: Все не так радужно, потому что Тор очень сильно лагает.
Если у сайта к которому идут обращение есть IPv6, то прокси будут очень дешевые.
Еще есть вариант прикинутся гугл-ботом - вдруг его не банят.


text:
Q: Apply configuration to base class without creating a table I am making an application, following the principles of Entity Framework code first, using the Migrations feature.
To avoid having the same code in every class, I have made a base class called AuditableEntity which contains the basic properties that all (auditable) entities must contain:
public abstract class AuditableEntity
{
    public int Id { get; private set; }
    public string CreatedBy { get; private set; }
    public DateTime CreatedDtm { get; private set; }
}

Now the field CreatedBy should have a default SQL value of CURRENT_USER.
And the field CreatedDtm should have a default SQL value of GETDATE().
Normally I would make a configuration file for the table, in which this is done, like this:
public class AuditableEntityConfiguration : IEntityTypeConfiguration<AuditableEntity>
{
    public void Configure(EntityTypeBuilder<AuditableEntity> builder)
    {
        builder.Property(e => e.CreatedBy).HasDefaultValueSql("USER_NAME()");
        builder.Property(e => e.CreatedDtm).HasDefaultValueSql("GETDATE()");
    }
}

But if I do this, Entity Framework wants to create a table called AuditableEntity. This is (obviously) not my intention. I want AuditableEntity to be an abstract base, not an actual entity. Or in other words, I want it to provide some very basic shared functionality for my actual entities.
Is there any way I can do something similar, which allows all classes inheriting from AuditableEntity to get the default SQL values described above?
I would like it done in a way, so that the logic applies on database level, so it is not as simple as setting the values in the C# code.

A: You can create a generic class, that will avoid to create a config class for each type but you will need to register the config for each type:
public class AuditableEntityConfiguration<T> : IEntityTypeConfiguration<T> where T : AuditableEntity
{
    public void Configure(EntityTypeBuilder<T> builder)
    {
        builder.Property(e => e.CreatedBy).HasDefaultValueSql("USER_NAME()");
        builder.Property(e => e.CreatedDtm).HasDefaultValueSql("GETDATE()");
    }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new AuditableEntityConfiguration<DerivedClass1>());
    modelBuilder.ApplyConfiguration(new AuditableEntityConfiguration<DerivedClass2>());
}

If speed is not important then you can always use reflection to get all types that derive from AuditableEntity and register the configurations dynamically.


text:
Q: Nagios - CRITICAL - unable to connect to Kubernetes via kubectl The Nagios monitoring system shows my this and I am not really good in Kubernetes so if someone can explain it to me what is the problem and how to fix it will be really nice for me. Thanks in advance!
I did not  try anything  for now


text:
Q: dhcpd not processing broadcast DHCPDISCOVER My DHCP server is handling two subnets. The first subnet is all host -> fixed-address sets for known hardware. The second subnet has a pool set up to handle virtual machines in a vCenter.
Now, if I've done this right, dhcpd matches the first three octets of the normal vCenter assigned MAC address, and assigns an address out of the subnet for virtual hosts, right?
Unfortunately, all I get is
Nov 15 12:42:44 dhcpserv dhcpd: DHCPDISCOVER from 00:50:56:aa:bb:cc via eth0: network XXX.YYY.22/23: no free leases

So, I know my dhcpd server is receiving the DHCPDISCOVER. I know I'm looking for the right three octets. (Do I know this?)
What I can't figure out is why my DHCP server isn't serving up an IP address out of the second subnet. What am I missing?

A: It turns out that I needed to do three things. Here are some snips from the final /etc/dhcpd.conf file:
class "virtual-hosts"
{
  match if substring(binary-to-ascii(16,8,":",hardware),2,7) = "0:50:56";
  log(info, "Hit for class virtual-hosts");
}

subnet XXX.YYY.22.0 netmask 255.255.254.0
{
}

subnet XXX.YYY.24.0 netmask 255.255.255.0
{
  option routers XXX.YYY.24.254;
  option domain-name-servers XXX.YYY.22.168, XXX.YYY.22.169;
  option ntp-servers XXX.YYY.22.168,XXX.YYY.22.169;
  default-lease-time 86400; # 1 day
  max-lease-time 604800;    # 7 days
  use-host-decl-names on;
  allow unknown-clients;

  option domain-name "example.com sub1.example.com sub2.example.com";
  next-server XXX.YYY.22.159;
  filename "pxelinux.0";

  pool
  {
    allow members of "virtual-hosts";
    get-lease-hostnames true;
    one-lease-per-client true;
    ping-check true;
    range XXX.YYY.24.11 XXX.YYY.24.60;
  }
}

First, look at that ugly string match in the class statement. The binary value hardware's first element is the hardware type and the second element is the address. I have to run hardware through binary-to-ascii to turn it into a searchable string, and then match the substring. The substring match starts at 2 to avoid the 1: that binary-to-string writes for the hardware type. And, the substring match is only 7 characters long because binary-to-string only uses a single digit for binary values less than 16.
Second, I have to declare allow unknown-clients; somewhere before dhcpd will even try to match an unspecified hardware address. Otherwise, I have to explicitly define the full MAC address in a host{} statement. But, I don't want allow unknown-clients; in the pool itself, because that's limited by ...
Third, the declaration allow members of "virtual-hosts"; in the pool statement.
So, the solution comes down to accurate parsing of binary-to-text and allowing unknown clients in the subnet statement, just to restrict them in the pool sub-statement.


text:
Q: Generating an activation key from a large set of serial numbers and activation keys I have a bunch of serial numbers and their corresponding activation keys for some old software. Since installing them originally I have lost a number of the activation keys (but still have the serial number). I still have a data set of about 20 keys and even eyeballing it I can tell there is a method to the madness in determining the the activation keys. Given my large data set is there a way I can backsolve to figure out the activation keys for the information I lost.
example of serial #: 14051 Activation Key: E9E9F-9993432-45543

A: What you're trying to do is come up with a function that maps serial numbers to activation keys. Without knowing more about the nature of the function, this could be anywhere from very easy (a polynomial with only a few terms) to very hard (a multi-tiered function involving lots of block XORs, substitution tables, complicated key schedules, ...).
If you have access to the key verifier routine (e.g. by disassembly - which is almost always against the EULAs of commercial software), then you have a routine that returns whether or not a given activation key is correct for a given serial number. If this was done by computing an activation key for a serial number, then you are practically done. If this was done by computing the inverse function on the key, then your task is a little harder: you need to invert that function to retrieve the key derivation algorithm, which may not be so easy. If you end up having to solve some hard mathematical problems (e.g. the discrete logarithm problem) because the scheme depends on public-key cryptography, then you're hoping that the values you're dealing with are small enough that you can brute-force or use a known algorithm (e.g. Pollard's rho algorithm) in computationally feasible time.
In any case, you'll need to get comfortable with disassembly and debugging, and hope that there are no anti-debugger measures in place.
Otherwise, the problem is much harder - you'd need to make some educated guesses and try them (e.g. by trying to do a polynomial fit), and hope for the best. Because of the very large variety of different possible functions that can fit any set of inputs and outputs (mathematically uncountable, though in practice limited by source code size), trying to do a known-plaintext attack on the algorithm itself is generally infeasible.

A: It depends on how dumb the scheme was in the first place, but my guess would be that it's not likely.  There's no fixed methodology, but the general domain is the same as codebreaking.