Q:

Error showing Values of fields msds-memberOfTransitive and msds-memberTransitive

We are trying to return all user information from a LDAP query made to a Microsoft Active Directory 2012 server.
First, we get all attributes from the schema (including msds-memberOfTransitive and msds-memberTransitive), then we make a query requesting all attributes.
We have narrowed down this problem to executing a LDAP search with the following parameters:
 - Scope: Next level (if there are elements inside the container) or Subtree
 - msds-memberOfTransitive or msds-memberTransitive attributes are requested
Sample query reproducing the error:
ldapsearch -D "CN=Administrator,CN=Users,DC=my,DC=dom" -W -b "CN=Users,DC=my,DC=dom" -h 10.0.1.100 -p 389 msds-memberTransitive

Sample query avoiding the error:
ldapsearch -D "CN=Administrator,CN=Users,DC=my,DC=dom" -W -b "CN=Administrator,CN=Users,DC=my,DC=dom" -h 10.0.1.100 -p 389 msds-memberTransitive -s one

I assume this is some mechanism to avoid excessive calculations of "transitive" attributes, but I have not found anything .
How could I make this search (appart from removing these attributes from the search)?

A:

Looks like the msds-memberOfTransitive and msds-memberTransitive have Search Flags of searchFlags: 2048 set that limit the search to a base Scope.
If we look at msds-memberOfTransitive, we see the setting searchFlags: fBASEONLY. Lookin at Search Flags, we see:
(fBASEONLY, 0x00000800): Specifies that the attribute is not to be returned by search operations that are not scoped to a single object. Read operations that would otherwise return an attribute that has this search flag set instead fail with operationsError / ERROR_DS_NON_BASE_SEARCH.
(Same is true for msds-memberTransitive)
So these attributes will only be return when the scope of the search is BASE.
The only method around this condition would be to loop through each result with one of the attributes and do a second search which would be a baseDN of the entry and a scope of BASE.


Q:

Is it possible to declare different stack size for different process in SimGrid

I can define a stack size of msg_process_t by flag --cfg=contexts/stack-size=10 at the beginning of simulation.
But is it possible to define a different stack size for different processes, because at most my processes use small size of stack, but a master process needs a lot more kilobytes?

A:

This feature is currently not implemented. This bug requests it:
https://gforge.inria.fr/tracker/index.php?func=detail&aid=18137&group_id=12&atid=165


Q:

xlsxwriter chart grid spacing

I'm currently trying to create charts in excel via the xlsxwriter python module. I've gotten it to graph just fine, however I'm trying to get it to look nice. I've been able to add major and minor gridlines, change their line width, and dash type, but I can't figure out how to modify their spacing. (e.g., minor lines on every unit with major lines on every 5 units)
As far as I can tell, it's not an option, but I thought I'd throw this out there to see if an expert had a trick (I've just started using this module) and/or put this out there for people looking for this option in the future.
Here's the code I'm working with right now:
chart = wb.add_chart({'type': 'line'})
chart.add_series({
    'name': 'Sheet1!{:}'.format(xlsxwriter.utility.xl_rowcol_to_cell(0, data_column)),
    'categories': ['Sheet1', 1, time_column, num_of_data_pts, time_column],
    'values': ['Sheet1', 1, i, num_of_data_pts, data_column],
    'line': {'color': 'blue'},
})
chart.set_x_axis({
    'num_font': {'italic': True},
    'major_gridlines': {
        'visible': True,
        'line': {'width': 1}
    },
    'minor_gridlines': {
        'visible': True,
        'line': {'width': 1, 'dash_type': 'dash'}
    },
})
chart.set_legend({'position': 'none'})
ws.insert_chart(5, 5, chart)

Also I've tried using the 'major_unit' attribute, but it appears that is something to do with if the x axis is a date only.

A:

I can't figure out how to modify their spacing. (e.g., minor lines on every unit with major lines on every 5 units

I'm not sure if that is possible in Excel.
As explained in the XlsxWriter docs Excel treats Category and Values chart axes differently. The X axis for a line chart is a category axis and for text and numbers it is only possible to change the interval between the labels/ticks. You can verify that yourself in Excel.
That feature is also supported in XlsxWriter using the axis interval_unit.
Probably you need to format the chart as a scatter chart which has value axes for X and Y and which allows you to control the spacing


Q:

Every cycle in a knot has odd length

Consider the projection of a knot on to the plane. Consider following the knot, starting from a crossing, until we get back to that crossing (on the opposite strand). Why must this cycle have odd length?

A:

There's a theorem that the regions cut off by the knot projection can be two-colored. Actually this theorem is about a closed curve in the plane having each intersection with only two curves crossing (no triple or higher crossings at a point). But it is the same as your projected knot onto the plane. Imagine the regions have been colored black or white.
Now as you go around the curve starting at a given crossing, the colors on your left alternate black, white, black, white, etc. When you first rearrive back to your starting point, you'll have just crossed the opposite color (on your left) from the starting color. This makes for the odd length phenomenon you refer to.


Q:

JavaScript function declarations in Native browser and Node.js, get differnt results

The code below will get different in Browser and Node.js.
Result of browser is a.
Result of Node.js is b.
if (1) {
    function foo() { return 'a'; }
} else {
    function foo() { return 'b'; }
}

console.log(foo());

Although this code style is anti-pattern, the code still can be run in environment.
How to explain it?

FYI.

Node.js environment Link:
https://repl.it/CgWh
Native Browser environment Link:
https://repl.it/CgWj

These links maybe not permanent.

A:

Javascript engines are not hoisting javascript function the same way, so you can expect different behavior between browser/node.
One exemple of this: http://statichtml.com/2011/spidermonkey-function-hoisting.html


Q:

Getting android.app.RemoteServiceException: Bad notification posted from package in custom notification

I am trying to create a custom notification using the remote view.
Steps Followed:
1. Created a layout and placed in the res/layout folder
2. Extended the RemoteViews class and implemented some helper methods.
3. Instantiated an object of the Extended class and I am supplying this as Content by using setContent() in the Notification.Builder.
4. Cached the instantiated Extended class.
Now most of the times when I do an operation even before supplying the extended class object to the Notification.Builder its crashing.
E/AndroidRuntime(10194): android.app.RemoteServiceException: Bad notification posted from
package com.motorolasolutions.ptt.mpttclient: Couldn't expand RemoteViews for:
StatusBarNotification

I have tried following functions
setBoolean(R.id.textview1, "setEnabled", false);

Please let me know how can I call the functions on the remote view.
I tried so many functions which have @android.view.RemotableViewMethod tag in the source code of Android.

A:

Eventhough "setEnabled" function has the @RemotableViewMethod  tag in the base class (View.java). This is being overridden in the derived class and doesn't have the @RemotableViewMethod tag. We have to check the tag of the child class if its being overridden.


Q:

What does apt-get update do actually

Previously I had visited this discussion and I am still not getting a full answer. As was mentioned in the accepted answer of the above link:

apt-get update downloads the package lists from the repositories
and "updates" them to get information on the newest versions of
packages and their dependencies. It will do this for all repositories
and PPAs.

What actually is meant by "downloads the package lists"?. If I'm not wrong, the package lists are already stored in my local computer. I mean, the packages (maybe old versions of them) are already in my computer and of source there is also the list in /var/apt/lists.
Even if it needs to download the package lists, then that must be a .txt or similar file. Then why is this indicated?
fetching 17.6 mb from https://..mirror...

I mean, how can the package list be so large, if there are few hundreds packages in total only, including all modules and libs?
Can someone make it more clear for me?

A:

I maintain a local mirror of Ubuntu Bionic so I can show you the size of the files.
This is the baseline 18.04 release from 4/2018. As you can see, the zipped 'Contents' files are ~37 MiB each.

the security and updates contents list are roughly twice as large (this is bionic-updates).

The unzipped Contents-amd64.gz from the baseline is nearly 600 MiB and contains 6,552,333 lines. It starts like this:
bin/afio                            multiverse/utils/afio
bin/archdetect                          utils/archdetect-deb
bin/ash                             universe/shells/ash
bin/autopartition                       admin/ubiquity
bin/autopartition-crypto                    admin/ubiquity
bin/autopartition-loop                      admin/ubiquity
bin/autopartition-lvm                       admin/ubiquity
bin/bash                            shells/bash
bin/bash-static                         universe/shells/bash-static
bin/block-attr                          admin/ubiquity


Q:

How to set AID for JADE Agent?

I'm just starting with JADE agent based modeling. My hello world example looks like this -
public class HelloWorldAgent extends Agent {
 protected void setup() {
  System.out.println("Hello World! My AID is "+this.getAID());
 }
}

And I call this outside like this -
public class Main {
  public static void main(String[] args) {
    HelloWorldAgent helloWorldAgent = new HelloWorldAgent();
    helloWorldAgent.setup();
  }
}

And the output I'm seeing is -
Hello World! My AID is null

Now, my question is how do I set AID as there is only get method and no "set" method. As it's not available, I suspect there AID is something that's automatically assigned. Is it so? If yes, how do I make sure that Agent gets an AID? Thanks.

A:

I suggest you, firstly, to create a container. You can try this way in your main method:
public static void main(String[] args) throws Exception {
    ProfileImpl p = new ProfileImpl();
    p.setParameter(Profile.MAIN_HOST, "localhost");
    p.setParameter(Profile.GUI, "true");

    ContainerController cc = Runtime.instance().createMainContainer(p);

    AgentController ac = cc.createNewAgent("myAgent", "HelloWorldAgent", new Object[] { });
    ac.start();
}

getAID().getLocalName() will return "myAgent" in this case.


Q:

msbuild - Is it possible to share items defined in a child project to its parent without using Import?

Question
How do I get items defined in a child project to its parent without using the <Import> element?
The reason I want to avoid <Import> is because it also imports targets which execute at the parent project, which is not desired.
Example
Say I have the following child.csproj:
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <MyItem Include="some.file" />
    </ItemGroup>

    <Target Name="MyChildPreBuild" BeforeTargets="Build">
        <Message Text="MyChildPreBuild" Importance="high" />
        <Message Text="%(MyItem.FullPath)" Importance="high" />
    </Target>
</Project>

And this is referenced by a parent.csproj:
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <MyItem Include="some.other.file" />
    </ItemGroup>

    <ItemGroup>
        <ProjectReference Include="..\child\child.csproj" />
    </ItemGroup>

    <Target Name="MyPreBuild" BeforeTargets="Build">
        <Message Text="MyPreBuild" Importance="high" />
        <Message Text="%(MyItem.FullPath)" Importance="high" />
    </Target>
</Project>

Building parent.csproj, I get the following build output message:
1>------ Rebuild All started: Project: child, Configuration: Debug Any CPU ------
1>child -> C:\Users\dan\test\child\bin\Debug\netstandard2.0\child.dll
2>------ Rebuild All started: Project: parent, Configuration: Debug Any CPU ------
2>parent -> C:\Users\dan\test\parent\bin\Debug\netstandard2.0\parent.dll
2>C:\Users\dan\test\parent\some.other.file
========== Rebuild All: 2 succeeded, 0 failed, 0 skipped ==========

As can be seen, only the parent.csproj MyItem items are printed.
Adding <Import Project="..\child\child.csproj" /> to parent.csproj does print all of the MyItems but the child's target is executed as well:
1>------ Rebuild All started: Project: child, Configuration: Debug Any CPU ------
1>child -> C:\Users\dan\test\child\bin\Debug\netstandard2.0\child.dll
1>MyChildPreBuild
1>C:\Users\dan\test\child\some.file
2>------ Rebuild All started: Project: parent, Configuration: Debug Any CPU ------
2>C:\Users\dan\test\child\child.csproj : warning MSB4011: "C:\Program Files\dotnet\sdk\2.1.403\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props" cannot be imported again. It was already imported at "C:\Users\dan\test\parent\parent.csproj". This is most likely a build authoring error. This subsequent import will be ignored.
2>C:\Users\dan\test\parent\parent.csproj : warning MSB4011: "C:\Program Files\dotnet\sdk\2.1.403\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.targets" cannot be imported again. It was already imported at "C:\Users\dan\test\child\child.csproj". This is most likely a build authoring error. This subsequent import will be ignored.
2>parent -> C:\Users\dan\test\parent\bin\Debug\netstandard2.0\parent.dll
2>MyChildPreBuild
2>C:\Users\dan\test\parent\some.other.file
2>C:\Users\dan\test\parent\some.file
2>MyPreBuild
2>C:\Users\dan\test\parent\some.other.file
2>C:\Users\dan\test\parent\some.file
========== Rebuild All: 2 succeeded, 0 failed, 0 skipped ==========

A:

If you use the import method you can add a condition to the child targets to only execute when that flag is not set. Then, in your parent, set the flag to a value.
Child
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <MyItem Include="some.file" />
    </ItemGroup>

    <Target Name="MyChildPreBuild" BeforeTargets="Build" Condition="'$(ParentProject}'==''">
        <Message Text="MyChildPreBuild" Importance="high" />
        <Message Text="%(MyItem.FullPath)" Importance="high" />
    </Target>
</Project>

And then, in your parent project
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
        <ParentProject>parent.csproj</ParentProject>
    </PropertyGroup>

    <ItemGroup>
        <MyItem Include="some.other.file" />
    </ItemGroup>

    <Import Project="..\child\child.csproj" />

    <Target Name="MyPreBuild" BeforeTargets="Build">
        <Message Text="MyPreBuild" Importance="high" />
        <Message Text="%(MyItem.FullPath)" Importance="high" />
    </Target>
</Project>

This should prevent the child targets from being called when imported.


Q:

T-SQL Stored Procedure help: Getting a person's friends from Friends table

I am having trouble with T-SQL. I am a beginner at T-SQL.
I have a database of friend entries. One column contains MemberA_ID, which is an integer ID for one of the friend's member ID in a pair of friends. Another column contains MemberB_ID, which is an integer ID for the other friend's member ID in a pair of friends.
So if Mary's ID is 1 and John's ID is 2, and they are friends, then a row in the Friends table would contain 1 and 2 (among other data).
I am trying to write a T-SQL stored procedure that takes in a member ID as input, and retrieves, for all the friends of that member, their memberID and username (username is stored in another table called MemberProfiles).
I am trying this code, but It is not being accepted.
    ALTER PROCEDURE dbo.GetFriends (@ownMemberID [int])

    AS

    DECLARE @localFriendID_A AS INTEGER
    DECLARE @localFriendID_B AS INTEGER

    IF EXISTS
    (
        SELECT @localFriendID_B = MemberB_ID
        FROM Friends
        WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
        AND (RequestRejectDate IS NULL) AND (MemberA_ID = @ownMemberID)
    )
    BEGIN
        SELECT MemberID, VisibleUsername
        FROM MemberProfiles
        WHERE (MemberID = @localFriendID_B)
    END

    ELSE IF EXISTS
    (
        SELECT @localFriendID_A = MemberA_ID
        FROM Friends
        WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
        AND (RequestRejectDate IS NULL) AND (MemberB_ID = @ownMemberID)
    )
    BEGIN
        SELECT MemberID, VisibleUsername
        FROM MemberProfiles
        WHERE (MemberID = @localFriendID_A)
    END

    RETURN

A:

The only problem with the above code is, you are trying to initialize while checking for the existence of a row...
you have to write the TSQL as below
ALTER PROCEDURE dbo.GetFriends (@ownMemberID [int])

AS

DECLARE @localFriendID_A AS INTEGER
DECLARE @localFriendID_B AS INTEGER

SET @localFriendID_A = 0
SET @localFriendID_B = 0

SELECT @localFriendID_B = MemberB_ID
FROM Friends
WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
AND (RequestRejectDate IS NULL) AND (MemberA_ID = @ownMemberID)

SELECT @localFriendID_A = MemberA_ID
FROM Friends
WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
AND (RequestRejectDate IS NULL) AND (MemberB_ID = @ownMemberID)

IF ( @localFriendID_B <> 0 )
BEGIN
    SELECT MemberID, VisibleUsername
    FROM MemberProfiles
    WHERE (MemberID = @localFriendID_B)
END
ELSE IF (@localFriendID_A <> 0 )
BEGIN
    SELECT MemberID, VisibleUsername
    FROM MemberProfiles
    WHERE (MemberID = @localFriendID_A)
END

RETURN


Q:

Using Qt 4 vs Qt 5 to develop application for Windows and OS X?

I am considering using Qt to port a standalone Windows application to OS X and possibly Linux. I have never used Qt before. I do not know if I should work with Qt 4 or Qt 5.
I would be interested to get the feedback of developers of fairly large applications using Qt 4 and 5. What are the pros/cons for each version?
More info about the project:
The application is a high end tool for digital photography: real time HDR, Tone Mapping, etc, of large photos at 96-bits per pixel.
The application is currently using the following technologies:

UI code : C#, C++/CLI, .NET 2.0 WinForm
Core algorithms: C++, OpenMP, SSE

I plan to use the Qt framework to redevelop the UI code. I have the following constraints:

Supported OS: Windows XP, Vista, 7 and 8; OS X; (Linux)
Two builds: 32 and 64-bit
Application must be able to run on VMs (with little or no OpenGL support)
Execution speed / real time aspects are essential
Main development environment: Visual Studio on Windows 7 64-bit

Thanks!

A:

Based just on your platform constraints you probably want to use Qt 5. Windows 7 64-bit is a tier 1 platform in Qt 5. Windows 8 isn't even a tier 2 platform in Qt 4. Qt 5 has better support for High DPI displays (important to Mac users with Retina displays).

Qt 4 Supported Platforms
Qt 5 Supported Platforms


Q:

Mask a UIView with a cut-out circle

I’ve created a UIView with a semi-transparent black background to sit across my main app’s view. What I’m aiming for here is to create a cut-out circle shape somewhere in that UIView where the semi-transparent black background is not seen, giving the effect of a black mask over the whole image except the circular area (this is to highlight a button in that area).
I’ve managed to use CAShapeLayer to create a circular mask, but this has had the opposite effect (i.e. the rest of the view is clear, and INSIDE the circle is the semi-transparent black. What I’d like is everything outside of the circle to keep the semi-transparent black, then what’s inside to be clear. Here’s the code I used, how would I go about making it work in the opposite way? My blackMask is the semi-transparent black view, and my buttonCircle is the circle I’d like to be kept clear.
Perhaps I need to invert the path, somehow?
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
CGRect maskRect = buttonCircle.frame;
CGPathRef path = CGPathCreateWithEllipseInRect(maskRect, NULL);
maskLayer.path = path;
CGPathRelease(path);
blackMask.layer.mask = maskLayer;

EDIT: Trying this now, not seeing any mask at all with this one:
UIView *circularMaskView = [[UIView alloc] initWithFrame:buttonCircle.frame];
circularMaskView.backgroundColor = [UIColor greenColor];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

CGPathRef path = CGPathCreateWithEllipseInRect(buttonCircle.frame, NULL);
maskLayer.path = path;
CGPathRelease(path);

circularMaskView.layer.mask = maskLayer;

[blackMask addSubview:circularMaskView];

A:

So, here’s what I did. I created a custom UIView subclass called BlackoutView, like so:
BlackoutView.h
#import <UIKit/UIKit.h>

@interface BlackoutView : UIView

@property (nonatomic, retain) UIColor *fillColor;
@property (nonatomic, retain) NSArray *framesToCutOut;

@end

BlackoutView.m
#import "BlackoutView.h"

@implementation BlackoutView

- (void)drawRect:(CGRect)rect
{
    [self.fillColor setFill];
    UIRectFill(rect);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetBlendMode(context, kCGBlendModeDestinationOut);

    for (NSValue *value in self.framesToCutOut) {
        CGRect pathRect = [value CGRectValue];
        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:pathRect];
        [path fill];
    }

    CGContextSetBlendMode(context, kCGBlendModeNormal);
}

@end

I then instantiate it as normal, and set the properties to the colour of the mask I want to use, and the frames to be cut out of the mask:
[blackMask setFillColor:[UIColor colorWithWhite:0.0f alpha:0.8f]];
[blackMask setFramesToCutOut:@[[NSValue valueWithCGRect:buttonCircleA.frame],
                               [NSValue valueWithCGRect:buttonCircleB.frame]]];

This could be improved by allowing me to cut out other shapes besides ovals, but it’s fine for my purposes here and would be easily adapted to do so later. Hopefully this helps others!

A:

If You are using any Black Image to mask then
-(void)maskWithImage:(UIImage*)maskImage toImageView:(UIImageView*)imgView{

    CALayer *aMaskLayer=[CALayer layer];
    aMaskLayer.contents=(id)maskImage.CGImage;

    imgView.layer.mask=aMaskLayer;

}

If you have any Custom ShapeLayer to mask
-(void)maskWithShapeLayer:(CALayer*)layer toImageView:(UIImageView*)imgView{
    //Layer should be filled with Black color to mask those part of Image
    imgView.layer.mask=layer;
}

If You want to make ImageView Mask with Circle
-(void)maskWithCircle:(UIImageView*)imgView{

    CAShapeLayer *aCircle=[CAShapeLayer layer];
    aCircle.path=[UIBezierPath bezierPathWithRoundedRect:imgView.bounds cornerRadius:imgView.frame.size.height/2].CGPath; // Considering the ImageView is square in Shape

    aCircle.fillColor=[UIColor blackColor].CGColor;
    imgView.layer.mask=aCircle;

}

A:

Here is my conversion of the accepted answer in Swift:
public class OverlayView: UIView {
let fillColor: UIColor = UIColor.grayColor()
public var framesToCutOut: Array<NSValue> = [NSValue]()

override public func drawRect(rect: CGRect) {
    super.drawRect(rect)

    fillColor.setFill()
    UIRectFill(rect)

    if let context: CGContextRef = UIGraphicsGetCurrentContext() {
        CGContextSetBlendMode(context, .DestinationOut)

        for value in framesToCutOut {
            let pathRect: CGRect = value.CGRectValue()
            let path: UIBezierPath = UIBezierPath(ovalInRect: pathRect)
            path.fill()
        }

        CGContextSetBlendMode(context, .Normal)
    }
}


Q:

error copy file that was created in C#

I have this problem when I try to copy a file that was created in C#:
"System.IO.IOException: 'The process can not access the file' d:\las.txt 'because it is being used in another process.'"
my code:

using System;

namespace modulo1
{
    class Program
    {
        static void Main(string[] args)
        {
           string folderName = @"c:\lasss";

           System.IO.Directory.CreateDirectory(folderName);

           string archivo = @"d:\las.txt";

           System.IO.File.Create(archivo);

            string dest = @"d:\soft";

           //here is the problem
            System.IO.File.Copy(archivo, dest, true);
        }
    }
}

How can i solve this problem???

A:

The File.Create() method creates a file and returns a FileStream object to the file (see the documentation here). So, if you're not going to use that file stream, then you need to close it before you can access the file:
System.IO.File.Create(archivo).Close();

Or, since FileStream implements IDisposable, you can put it in a using block, which will close and dispose of it for you:
using (var fileStream = System.IO.File.Create(archive))
{
    // do something with the file stream here if you need to
}


Q:

JavaScript setInterval is not stoping

I am running the JavaScript timer using setInterval(). I want to run the timer for 5 seconds then restart the timer from zero seconds and the same process should run for 3 times.
<!DOCTYPE html>

    <title>Jquery setinterval stop after sometime</title>

Counter:

Seconds:

The above code timer works fine until counter value is less than 3 but after that setInterval() keeps running and doesn't stop even on using clearInterval().
Can anyone point out the problem in the given code that why setInterval() is not stopping after counter value is greater than or equal to 3 ?

A:

There are a few problems. The main one is that start_seconds needs to be local to the function rather than declared outside the function — you want to control each interval independently within the function. The way you have it, you lose the references to the earlier timers. And you want to clear the interval when seconds == 5 regardless of whether the counter < 3 because you are starting a new one.
Something like this:

var counter = 0;
function intervalFunc(){
    var seconds = 0
    var start_secs = setInterval(function(){
        console.log(seconds)
        if(seconds===5){
            if(counter < 3){
                intervalFunc();
            }
            // after 5 times clear the interval
            // a new one is started if counter < 3
            clearInterval(start_secs);
            return
        }
        seconds++;
    }, 500);
    counter++;
}

intervalFunc();


Q:

Not possible to block VoIP calls in iOS 13?

CallKit's call directory extension can be used to block standard phone calls.
However how is blocking a VoIP call supposed to work with iOS 13?
When there is a VoIP call your app receives a VoIP push, but now with iOS 13 Apple are mandating that when the push is received the app must call CXProvider.reportNewIncomingCall().
However when reportNewIncomingCall() is called, the OS displays an incoming call screen (which is not the same as for a regular incoming call). It is apparently not possible for this call screen to be suppressed, and even if reportNewIncomminCall() is invoked with a parameter which is a number which has been registered as blocked with the CallKit extension, the call screens still being displayed.
So it would seem it is impossible for an application to offer the ability to block a VoIP phone call (unless the app sends its list of blocked numbers to the server, and the server doesn't send the push for a particular handset for blocked numbers. But if the app is installed in hundreds of thousands or millions of handsets, that's a large undertaking on the server side to implement).

A:

I had some correspondence with an Apple Voip engineer. Apple are expectingthat if you need to block Voip calls then you need to do it on the server, not the handset.


Q:

Looping total not same in database

Hello i have a script looping php, and each loop 4 data/row then show ads.
but i have a problem.. because in database i have data 123 row.
but in show in php only  92 row/data :'(
this is my script
<?php
include "connection.php";
$i=0;
$data_school=mysql_query("select * from school");
while ($school=mysql_fetch_object($data_school))
{
    if($i%4==0)
    {
    echo "

";
    }
    else
    {
        echo $school->name_school"
";
    }
$i++;
}
?>

when i run in browser, and ads show but school only show "92 row/data"
if i remove script
 if($i%4==0)
        {
        echo "

";
        }

then script be like this
<?php
    include "connection.php";
    $i=0;
    $data_school=mysql_query("select * from school");
    while ($school=mysql_fetch_object($data_school))
    {
            echo $school->name_school"
";

    $i++;
    }
    ?>

this data show all 123 row/data
help me, i want like this
school 1
school 2
school 3
school 4
#ads
school 5
school 6
school 7
school 8
#ads
Help me, Thank's

A:

Try this:
<?php
include "connection.php";
$i=0;
$data_school=mysql_query("select * from school");
while ($school=mysql_fetch_object($data_school))
{
    if($i%4==0)
    {
        echo "

";
    }
    echo $school->name_school . "
";
    $i++;
}
?>

You want to echo the school name every time
Also why aren't you getting errors on this:
echo $school->name_school"
";


Q:

SQL Server Synonyms and Concurrency Safety With Dynamic Table Names

I am working with some commercial schemas, which have a a set of similar tables, which differ only in language name e.g.:
Products_en
Products_fr
Products_de

I also have several stored procedures which I am using to access these to perform some administrative functions, and I have opted to use synonyms since there is a lot of code, and writing everything as dynamic SQL is just painful:
declare @lang varchar(50) = 'en'

if object_id('dbo.ProductsTable', 'sn') is not null drop synonym dbo.ProductsTable
exec('create synonym dbo.ProductsTable for dbo.Products_' + @lang)

/* Call the synonym table */
select top 10 * from dbo.ProductsTable
update ProductsTable set a = 'b'

My question is how does SQL Server treat synonyms when it comes to concurrent access? My fear is that a procedure could start, then a second come along and change the table the synonym points to halfway through causing major issues. I could wrap everything in a BEGIN TRAN and COMMIT TRAN which should theoretically remove the risk of two processes changing a synonym, however the documentation is scarce on this matter and I can not get a definitive answer.
Just to note, although this system is concurrent, it is not high traffic, so the performance hits of using synonyms/transactions are not really an issue here.
Thanks for any suggestions.

A:

Your fear is correct.  Synonyms are not intended to used in this way.  Wrapping it is a transaction (not sure what isolation level would be required) might solve the issue, but only by making the system single user.
If I was dealing with this then I would probably have gone with dynamic SQL becuase I am familiar with it.  However, having thought about it I wonder if schemas could solve your problem.
If you created schema for each language and then had a table called products in each schema.  Your stored proc can then reference an un-qualified table name and SQL should resolve the reference to the table that is in the default schema of the current user.  You'll then need to either change what account your application authenticates as to determine which schema it uses or use EXECUTE AS in a stored proc to decide which schema is default.
I haven't tested this schema idea, I may not have thought of everything and I don't know enough about your application to know if it is actually workable in your case.  Let us know if you decide to try it.


Q:

Can I open an investment account in the United States as a Green Card holder?

Can a green card holder open a Schwab investment account as a normal US citizen would, or most they open an International account?  Funds to use would all be coming from a US bank and not overseas.

A:

Your bank doesn't care about your immigration status, it cares about your tax status. You're a US tax resident and will open a US-resident account, not an international account (regardless of where the money comes from).

A:

As a relatively recent nonimmigrant visa holder (O1), I was able to open an ETrade brokerage account without problems. I have full tax residence in the USA so have an SSN, and a credit history so it was no problem.
Later, as a greencard holder, I opened IRA accounts with them, too. Again, there were no issues as I had all the information that the IRS paperwork required at hand.


Q:

"deleteAll" method only removes one occurrence

I've been asked to write a Standard ML Program which deletes every occurrence of a list from another list. For the life of me I cannot understand what is wrong with my code. Any help would be appreciated!
My input for this program is as follows:
deleteAll [1,2,3] [3,2,1,2,3,2,1,2,3];
However my output is this:
val it = [3,2,2,1,2,3] : int list
When it should be: [3,2,2];
fun length(x) = if x = [] then 0 else 1+length(tl(x));

val length = fn : ''a list -> int

fun drop 0 L = L
|   drop n [] = raise c4
|   drop n (h::t) = drop (n-1) t;

val drop = fn : int -> 'a list -> 'a list

fun starts [] _ = true
|   starts _ [] = false
|   starts (h::t) (x::xs) = if(h=x) then starts t xs else false;

val starts = fn : ''a list -> ''a list -> bool

fun deleteAll [] _ = []
|   deleteAll xs [] = xs
|   deleteAll (x::xs) (y::ys) = if(starts (x::xs) (y::ys))
    then deleteAll (x::xs) (drop (length(x::xs)) (y::ys))
    else y::(deleteAll (x::xs) ys);
val deleteAll = fn : ''a list -> ''a list -> ''a list

A:

First you don't need to create a length function as length is a build-in function that returns an int representing the elements of an 'a list.
One more thing, you raise an exception c4 in your function drop. Then you should also include that in the beginning of your program.
The primary reason your code doesn't work is your deleteAll function base cases. The corrected version should be:
fun deleteAll [] xs = xs (* when the first list is empty, it should return the original list *)
|   deleteAll xs [] = [] (* when the second list is empty, it should return an empty list *)
|   deleteAll (x::xs) (y::ys) = if(starts (x::xs) (y::ys))
                                then deleteAll (x::xs) (drop (length(x::xs)) (y::ys))
                                else y::(deleteAll (x::xs) ys);

The rest is good! After the change the answer should be correct : )
- deleteAll [1,2,3] [3,2,1,2,3,2,1,2,3];
val it = [3,2,2] : int list


Q:

Access WebAPI with AntiForgeryToken in Aspnet 5.0 on Xamarin

i'm trying to access a WebAPI which is using ValidateAntiForgeryToken. My WebAPI Method is this (a simple one), which is inside a User Controller (just for a test):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Test(String field)
{
    String result = String.Empty;
    if (ModelState.IsValid)
    {
        HtmlSanitizer sanitizer = new HtmlSanitizer();

        try
        {
            result = sanitizer.Sanitize(field);
        }
        catch (Exception ex)
        {
            result = ex.Message;
            throw;
         }
    }
    return Json(result);
}

With Ajax, i can access it with ease:
$.ajax({
    url: '/User/Test',
     type: "POST",
    contentType: "application/x-www-form-urlencoded",

    data: {

        field: self.textField(),
         __RequestVerificationToken: $("input[name='__RequestVerificationToken']").val(),
    },
    success: function(e) {
       self.textField(e)
        self.divField(e);
    },
    error: function(e) {
        console.log(e.error());
    },
});

But, until now, i can't access this webapi with httpclient on xamarin. This is my code:
    private async void DoTestWebApi()
{
    try
    {
        HttpClient clientPage = new HttpClient()
        {
            BaseAddress = new Uri("https://localhost:44356/user")
        };

        var pageWithToken = await clientPage.GetAsync(clientPage.BaseAddress);

        String verificationToken = GetVerificationToken(await pageWithToken.Content.ReadAsStringAsync());

        HttpClient client = new HttpClient()
        {
            BaseAddress = new Uri("https://localhost:44356/user/test/")
        };

        HttpRequestMessage message = new HttpRequestMessage()
        {
            RequestUri = new Uri("https://localhost:44356/user/test/"),
            Method = HttpMethod.Post
        };

        message.Headers.Add("__RequestVerificationToken", verificationToken);

        String field = "teste";

        //StringContent content = new StringContent("field=test", Encoding.UTF8, "application/x-www-form-urlencoded");
        StringContent content = new StringContent("__RequestVerificationToken=" + verificationToken + ",field=test", Encoding.UTF8, "application/x-www-form-urlencoded");

        // this doesn't work
        //client.DefaultRequestHeaders.Add("__RequestVerificationToken", verificationToken);
        var response2 = await client.SendAsync(message);

        if (response2.IsSuccessStatusCode)
        {
            var t = response2.Content.ReadAsStringAsync();

            if (true)
            {
                // just to check if t has value
            }
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        throw;
    }

}

Honestly, i don't know what else i could do to pass my anti forgery token inside the message. It works perfectly in ajax, i pass it inside the data content, but in xamarin it doesn't work.
All the code is executed inside the same localhost. If i remove the [ValidateAntiForgeryToken], it works.
What am i missing?
Edit:
Ok, so now i'm sending with cookies, but is not hitting the method again.
This is my update:
HttpClient clientPage = new HttpClient()
{
    BaseAddress = new Uri("https://localhost:44356/user")
};

var pageWithToken = await clientPage.GetAsync(clientPage.BaseAddress);

String verificationToken = GetVerificationToken(await pageWithToken.Content.ReadAsStringAsync());

List<KeyValuePair<String, String>> cookiesInfo = new List<KeyValuePair<String, String>>();

foreach (var item in pageWithToken.Headers)
{
    cookiesInfo.Add(new KeyValuePair<String, String>(item.Key, item.Value.ToString()));
}

cookiesInfo.Add(new KeyValuePair<string, string>("field", "value"));
cookiesInfo.Add(new KeyValuePair<string, string>("__RequestVerificationToken", verificationToken));

CookieContainer cookieContainer = new CookieContainer();

using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("https://localhost:44356/user") })
    {
        var content = new FormUrlEncodedContent(cookiesInfo);

        cookieContainer.Add(client.BaseAddress, new Cookie("__RequestVerificationToken", verificationToken));

        foreach (var item in cookiesInfo)
        {
            cookieContainer.Add(client.BaseAddress, new Cookie(item.Key, item.Value));
        }

        var result = client.PostAsync(new Uri("https://localhost:44356/user/test"), content).Result;

        result.EnsureSuccessStatusCode();
    }

};

This is driving me nuts... Ok the test is in localhost but soon this app will be in Azure, and this is a pre-requisite...

Edit: GetVerificationToken Method:
private string GetVerificationToken(String verificationToken)
    {
        if (verificationToken != null && verificationToken.Length > 0)
        {
            verificationToken = verificationToken.Substring(verificationToken.IndexOf("__RequestVerificationToken"));
            verificationToken = verificationToken.Substring(verificationToken.IndexOf("value=\"") + 7);
            verificationToken = verificationToken.Substring(0, verificationToken.IndexOf("\""));
        }

        return verificationToken;
    }

A:

ValidateAntiForgeryToken is also expecting a cookie with __RequestVerificationToken and the value provided. This is to make sure that the one posting to the controller is the one who viewed the form.


Q:

Fast zip list of lists while completing shorter lists by cycling

Please note this is not a duplicate of this post because I want to zip more than 2 lists (or at least I cannot easily generalize that post for use here without explicit loops)
I want to find the best performing (in terms of speed) implementation that merges list of lists in a particular way. The input is a list of lists (or tuples), ordered such that the length of the next list is always multiples of the previous one. For example:
a = ['A', 'B', 'C', 'D']
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
input_list = [a, b]

The output is a merged list of:
output = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H']

That is, the shorter lists (in this case a) all get expanded to the longest list (in this case b) by cycling over itself so that lists will have equal length. Then all lists are merged in a vertical stacking fashion.
Currently I have an implementation that essentially does the following:
step 1            step 2           step 3
======            ========         ======
ABCD              ABCDABCD
ABCDEFGH -------> ABCDEFGH ------> AABBCCDDAEBFCGDH

It works but not efficient:
def flatten_list(value):
    return sum(value, [])

def group(value):
    for idx in reversed(range(1, len(value))):
        multiplier = int(len(value[idx]) / len(value[idx - 1]))
        if multiplier > 1:
            value[idx - 1] = flatten_list([value[idx - 1] for i in range(multiplier)])
    return flatten_list(list(zip(*value)))

Is there a faster implementation? Performance is really crucial to my application as the input can be huge. Any suggestions are appreciated!

A:

Using cycle, chain, islice from itertools:
list(chain(*islice(
    zip(*(cycle(l) for l in input_list)),
    0, len(max(input_list, key=len)))))
# ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H']

Or, in its parts:
# generator producing cycles of each list
(cycle(l) for l in input_list)
# zip these cycles together: ('A', 'A') -> ('B', 'B') -> infinitely
zip(*...)
# take a slice of this iterable of tuples with the length of the longest list
islice(..., 0, len(max(input_list, key=len)))
# chain those tuples together into one list
list(chain(*...))

Or illustrated:
lists = [
                 #        chain--┐-----┐-----┐
                 #              ┌--┐  ┌--┐  ┌--┐
                 #        | ┌-┐ | ┌-┐ | ┌-┐ | ┌-┐  | ┌-┐
   [1],          # cycle: | |1|,| |1|,| |1|,| |1|, | |1|, ...
   [1, 2],       # cycle: | |1|,| |2|,| |1|,| |2|, | |1|, ...
   [1, 2, 3, 4], # cycle: | |1|,| |2|,| |3|,| |4|, | |1|, ...
]                #        | └-┘ | └-┘ | └-┘ | └-┘  | └-┘
                 #        |  └--┘  └--┘  └--┘      |
                 #        | zip   zip   zip   zip  | zip  ...
                 #        |                        |
                 #   islice start           islice stop
                 #   -->  [1,1,1,1,2,2,1,1,3,1,2,4]

The time complexity of this is O(n) where n is the length of the output list. In Python2 you will have to use itertools.izip instead of zip as the latter would try to build an infinite list.


Q:

How to create union class structure?

Say class A had method do(); and class B had field data;. I wonder if there is a way (using Boost for example) to create a class union from A and B which would have method do() and field data?

A:

Union has a specific meaning in c and c++, and it's not what you want. It sounds like you want is multiple inheritance, a class C that inherits from both A and B. Alternatively, you could also have a class C that contains instances of classes A and B. Oftentimes composition ("has-a") is preferable over inheritance ("is-a").


Q:

NSTextFields Positioned Lower On Other Macs

This is a weird situation. In Xcode's IB, I have a NSTableCellView subclass that I've built. It looks like this:

And when I run the app on my Mac, it comes out exactly as I would expect:

However, if any other Mac runs my app, every text field drops by something between 5-10 pixels:

Notice how the image view on the top right, and the hairline separator remain correctly positioned. This is just the text fields.
My brain balks at solving this because I can't guess what the cause is: my Mac is retina (hence right now the larger-looking image from my Mac) but I spend most of my time developing on a non-retina LED cinema display. I've tested this on three other Macs than my own, and the results are the same; it seems my own Mac is the outlier.
Any guesses as to the cause of this layout discrepancy?
UPDATE: I am using springs and struts to lay out the app. But I also tried using AutoLayout on one of my NIBs in case that was related. But the results were identical.

A:

Found the answer! Turns out I had an additional copy of Avenir installed on my Mac which nobody else had. That Avenir has different metrics associated with it, and once I disabled the non-system-provided Avenir, my Mac is now showing the same screwed-up layout as every other computer does. Yay?


Q:

Parametrized full text search query

I have a full text search query and try add to it Sql parameters.
Here is my code
using (var connection = GetDbConnection())
         {
            connection.Open();
            using (var cmd =
               new SqlCommand(
                  string.Format("ALTER FULLTEXT STOPLIST [{0}] ADD @stopWord LANGUAGE [{1}];", stopWord.StopList,
                     stopWord.Language), (SqlConnection)connection))
            {
               cmd.Parameters.AddWithValue("@stopWord", stopWord.StopWord);

               cmd.ExecuteNonQuery();
            }
         }

But it thows an error

Incorrect syntax near '@stoplist'. --->
  System.Data.SqlClient.SqlException: Incorrect syntax near '@stoplist'.

How can I construct my query to protect from sql injections?
For example as stopWord value I can send this with quote symbol

test's

A:

Escape the single quote
stopWord.StopWord = stopWord.StopWord.Replace("'", "''")


Q:

Не компилируется, ошибка, хотя там её нету

Не работает программа, пишет "22  expected `;' before '{' token ", учусь через Dev-C++ 4.9, и в Far проверяю .exe, не понимаю, что происходит с ней. Помогите.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

main()
{
    setlocale(LC_ALL, "rus");
    int counter = 1, number = 0, largest = 0, largest2 = 0;

    while (counter < 10)
    {
        printf("Enter number ");
        scanf("%d", &number);

        if (number > largest) {
            largest = number;
            largest2 = largest;
        } else
            (number > largest2) {
            largest2 = number;
            }
        counter++;
    }

    printf("1 %dn", largest);
    printf("2 %dn", largest2);
    system("PAUSE");
}

A:

Перед main поставьте int.
И вместо else поставьте else if.

A:

Ну как же нет ошибки, если есть:
else (number > largest2)

а, вероятно, нужно:
else if (number > largest2)


Q:

What hardware could be implanted on someones computer to bypass their VPN?

I was wondering what hardware could be used to bypass a VPN and get a user's email for example.

A:

This is impossible from the outgoing network connection port (assuming the VPN is correctly configured). If it wasn't then any party between the client and remote infrastructure could MitM the connection.
So hardware wise you'd need something inside the machine with access to either the relevant data or VPN configuration - like a malicious CPU/RAM module. If you've got that level of physical access then if the disk is unencrypted it would be far easier to just inject a software hack.


Q:

cannot round decimals to two decimal places in R

I have tried different functions to round decimals to two digits, such as format(), formatC(),signif() and round(). None of them can truly round all decimals to two decimal places.
For example, my data frame DF has three columns: Index, PDF and CDF:
   Index          PDF          CDF
1  -1.00 8.306360e-07 8.306360e-09
2  -0.99 8.332774e-07 1.663913e-08
3  -0.98 8.411712e-07 2.505085e-08
4  -0.97 8.542267e-07 3.359311e-08
5  -0.96 8.722951e-07 4.231606e-08
6  -0.95 8.951719e-07 5.126778e-08
7  -0.94 9.226012e-07 6.049380e-08
8  -0.93 9.542808e-07 7.003660e-08
9  -0.92 9.898679e-07 7.993528e-08
10 -0.91 1.028986e-06 9.022514e-08
...
...
...

The column Index is a vector, from -1.00 to 10.00.The difference between any consecutive elements is 0.01. It implies that unique(diff(Index)) should return only one value and it must be 0.01. However, unique(diff(Index)) can return several 0.01.
My purpose is to compute the difference between any two elements of the columnCDF, and these two elements are selected by indicating their Index. For example,
a<-DF$CDF[DF$Index==(r+dr)];

b<-DF$CDF[DF$Index==(r-dr)];

res<-a-b;

r is any number of Index, drcan be 0.01, 0.02 or 0.03. However, since some elements of Index cannot be rounded to 2 digits (although they all look like that), therefore I cannot compute res for any r and dr.
How should I tackle this problem? Thanks for your advice in advance!

A:

At some point in the function unique, the function will have to test, if two Index-Diffs are the same and it will likely do this with ==. However, comparing floating point values with == is rarely a good idea. Use your favourite searching page with "floating point equal" or "floating point comparison" or read at http://floating-point-gui.de/errors/comparison/ about this problem, which you should always be aware of, not only for this specific problem.
My advice in this case: Multiply you index values by 100, convert them to integers and == (and thereby unique) will work perfectly alright with integers.
Edit
Thanks to the comments by @hrbrmstr below I found, that you need to not only as.integer but to also round the numbers, as illustrated in the following code
#wrong result due to floating point arithmetic
unique(diff(seq(-1,1,0.1)))

# multiple steps towards a working solution
seq(-1, 1, 0.1)
10*seq(-1, 1, 0.1)
as.integer(round(10*seq(-1, 1, 0.1)))
diff(as.integer(round(10*seq(-1, 1, 0.1))))
unique(diff(as.integer(round(10*seq(-1, 1, 0.1))))) # works!


Q:

How do I configure Open Rasta to show a webpage under site root

I am using Open Rasta 2.0 under IIS 6. I would like to redirect the root of the site to a web page.
The documentation says:

Note that this will disable IIS default page mapping. The work-around
  is to either expose your default pages using OpenRasta itself....

I cannot work out how to achieve this. I have tried various routes in the configuration but they don't seem to work with IIS. I am also using Cassini server on my DEV pc, it has no issues when no routes are added but under some routes I tried broke it.

A:

Do you mean you want to show a webpage using OpenRasta on the root of the site? In this case you can do something like this when you have wildcard mappings setup.
using (OpenRastaConfiguration.Manual)
{
     ResourceSpace.Has.
     ResourcesOfType<Home>().
     AtUri("/").
     HandledBy<HomeHandler>().
     RenderedByAspx("/views/index.aspx")
}

Also when you say routes are you talking about OpenRasta resource configuration or IIS handler mappings?


Q:

Docker compose: bind multiple hosts to dynamic container's IP

I declare my service in docker-compose.yml like this:
wildfly:
  image: "myrepo/wildfly:latest"
  hostname: wildfly

So, compose adds entry to /etc/hosts:
172.18.0.4      wildfly

Where 172.18.0.4 is generated automatically by docker.
But I need to bind some.host.name to this generated IP in /etc/hosts to have multiple entries in /etc/hosts:
172.18.0.4      wildfly
172.18.0.4      some.host.name

How can I do that?
I tried to use extra_hosts syntax, but in docker-compose.yml I have no idea what IP will be assigned to container.
Have anybody faced the similar problem?

A:

You should version '3' format of the compose which supports aliases. Since you are already using a supported docker version
version: '3'
services:
  wildfly:
    image: "myrepo/wildfly:latest"
    hostname: wildfly
    networks:
      default:
        aliases:
          - some.host.name

This won't add host entries since docker now uses its own internal DNS server. If you need to use multiple compose files to be able to reach the services. Then you should create an external network
docker network create commonnet

And then use below in your compose
version: '3'
services:
  wildfly:
    image: "myrepo/wildfly:latest"
    hostname: wildfly
    networks:
      commonnet:
        aliases:
          - some.host.name
networks:
  commonnet:
    external: true


Q:

how to center the box in C?

ok now I need help on how to center my box, I tried many ways on solving it but didnt come up with the right one. I am still new at this sorry if it is confusing.
void box()
{
    int i, j, w=20, h=12;
    putchar(218);
    for(i=0;i<w-2;i++){
         putchar(196);
    }
    putchar(191);
    printf("\n");
    for(i=0;i<h-2;i++)
    {
        putchar(179);
        for(j=0;j<w-2;j++){
            printf(" ");
        }
        putchar(179);
        printf("\n");
    }
    putchar(192);
    for(i = 0; i<w-2;i++)
    {
        putchar(196);
    }
    putchar(217);
}
    int main()
    {
        gotoxy(30,0); printf("\nRobby Robot walks in a Cartesian plane.\n");
        box();
        gotoxy(30,5); printf("a. Orgigin\n");
        gotoxy(30,6); printf("b. Location\n");
        gotoxy(30,7); printf("c. Move\n");
        gotoxy(30,8); printf("d. Exit");
    }

A:

#define SWIDTH (80) /* you may need to change this screen-width value */
void box()
{
    int i, j, w=20, h=12;
    putchar(218);
    for(i=0; i<(SWIDTH-w)/2; i++) putchar(' ');
    for(i=0; i<w-2; i++)
    {
        putchar(196);
    }
    putchar(191);
    printf("\n");
    for(i=0; i<h-2; i++)
    {
        for(j=0; j<(SWIDTH-w)/2; j++) putchar(' ');
        putchar(179);
        for(j=0; j<w-2; j++)
        {
            printf(" ");
        }
        putchar(179);
        printf("\n");
    }
    for(i=0; i<(SWIDTH-w)/2; i++) putchar(' ');

    putchar(192);
    for(i = 0; i<w-2; i++)
    {
        putchar(196);
    }
    putchar(217);
}

UPDATE
SWIDTH = screen width in characters (number of characters that fit in one line on the terminal screen)
|<---------------------   SWIDTH   ---------------------->|
|                   ------------------                    |
|                  |                  |                   |
|                  <-  BOXWIDTH (W) ->                    |
|<- (SWIDTH-W)/2 ->                                       |
          ...


Q:

Error with a predicate in std::remove_if

I basically have an std::deque of objects, and I want to remove some of these objets according a condition on a given member variable of the objects, so that I use a predicate, but I have errors that I don't really understand.
I am using g++ with the -std=c++11 for STL reasons (shared pointers) but I was trying to work this out on windows with MVS with non c++11 code, so that I am looking for a non c++11 solution, without lamdas etc
The code is :
#include <iostream> // for std::cout and std::endl
#include <cstdio> // for getchar()
#include <memory> // for std::shared_ptr
#include <deque> // for std::deque
#include <algorithm> // for std::earse and std::remove_if

class A
{
    private:
        int _i;
        double _d;
    public:
        A(int i, double d)
        {
            _i = i;
            _d = d;
        }
        int geti()const
        {
            return _i;
        }
        double getValueOnWhichToCheck()const
        {
            return _d;
        }
};

typedef std::shared_ptr<A> A_shared_ptr;
typedef std::deque<A_shared_ptr> list_type;

void PrintDeque(list_type & dq)
{
    if (0 ==  dq.size())
    {
        std::cout << "Empty deque." << std::endl;
    }
    else
    {
        for (int i = 0 ; i < dq.size() ; ++i)
        {
            std::cout << i+1 << "\t" << dq[i] << std::endl;
        }
    }
}

class B
{
    public:
        double getThreshold() // Non constant for a reason as in real code it isn't
        {
            return 24.987; // comes from a calculation not needed here so I return a constant.
        }
        bool Predicate(A_shared_ptr & a)
        {
            return a->getValueOnWhichToCheck() >= getThreshold();
        }
        void DoStuff()
        {
            A_shared_ptr pT1 = std::make_shared<A>(A(2,      -6.899987));
            A_shared_ptr pT2 = std::make_shared<A>(A(876,    889.878762));
            A_shared_ptr pT3 = std::make_shared<A>(A(-24,    48.98924));
            A_shared_ptr pT4 = std::make_shared<A>(A(78,     -6654.98980));
            A_shared_ptr pT5 = std::make_shared<A>(A(6752,   3.141594209));
            list_type dq = {pT1,pT2,pT3,pT4,pT5};
            PrintDeque(dq);
            bool (B::*PtrToPredicate)(A_shared_ptr &) = &B::Predicate;
            dq.erase(std::remove_if(dq.begin(), dq.end(), PtrToPredicate),dq.end());
            PrintDeque(dq);
        }
};

int main()
{
    B * pB = new B();
    pB->DoStuff();
    getchar();
}

and the output of g++ -std=c++11 main.cpp -o main is :
In file included from /usr/include/c++/5/bits/stl_algobase.h:71:0,
                 from /usr/include/c++/5/bits/char_traits.h:39,
                 from /usr/include/c++/5/ios:40,
                 from /usr/include/c++/5/ostream:38,
                 from /usr/include/c++/5/iostream:39,
                 from main.cpp:1:
/usr/include/c++/5/bits/predefined_ops.h: In instantiation of ‘bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Deque_iterator<std::shared_ptr<A>, std::shared_ptr<A>&, std::shared_ptr<A>*>; _Predicate = bool (B::*)(std::shared_ptr<A>&)]’:
/usr/include/c++/5/bits/stl_algo.h:866:20:   required from ‘_ForwardIterator std::__remove_if(_ForwardIterator, _ForwardIterator, _Predicate) [with _ForwardIterator = std::_Deque_iterator<std::shared_ptr<A>, std::shared_ptr<A>&, std::shared_ptr<A>*>; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool (B::*)(std::shared_ptr<A>&)>]’
/usr/include/c++/5/bits/stl_algo.h:936:30:   required from ‘_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = std::_Deque_iterator<std::shared_ptr<A>, std::shared_ptr<A>&, std::shared_ptr<A>*>; _Predicate = bool (B::*)(std::shared_ptr<A>&)]’
main.cpp:67:73:   required from here
/usr/include/c++/5/bits/predefined_ops.h:234:30: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((__gnu_cxx::__ops::_Iter_pred<bool (B::*)(std::shared_ptr<A>&)>*)this)->__gnu_cxx::__ops::_Iter_pred<bool (B::*)(std::shared_ptr<A>&)>::_M_pred (...)’, e.g. ‘(... ->* ((__gnu_cxx::__ops::_Iter_pred<bool (B::*)(std::shared_ptr<A>&)>*)this)->__gnu_cxx::__ops::_Iter_pred<bool (B::*)(std::shared_ptr<A>&)>::_M_pred) (...)’
  { return bool(_M_pred(*__it)); }
                              ^

A:

Not a fan of function pointers, but using lambda's this seems to compile... https://ideone.com/0StRcw
        dq.erase(std::remove_if(dq.begin(), dq.end(), [this](const std::shared_ptr<A>& a) {
            return a->getValueOnWhichToCheck() >= getThreshold();
        }),dq.end());

Or without lambdas..
        auto predicateToUse = std::bind(&B::Predicate, this, std::placeholders::_1);
        dq.erase(std::remove_if(dq.begin(), dq.end(), predicateToUse), dq.end());

Update no auto:
dq.erase(std::remove_if(dq.begin(), dq.end(), std::bind(&B::Predicate, this, std::placeholders::_1)), dq.end());


Q:

Type of space in a black hole

Outgoing photons that start off outside the Event Horizon can escape
Outgoing photons that are emitted at r = 2M remain at r = 2M forever
Outgoing photons that are emitted at r < 2M fall towards r = 0
What does it mean when someone says that black hole interior and exterior is Minkowski space but event horizon is Schwarzschild solution?
(I heard this on a bus but can't work out what they meant)

A:

There is only one kind of spacetime. In environments like black hole interiors properties we normally regard as belonging purely to space or time get mixed up.
You are right in that one can measure the circumference of a black hole and get a reasonable result. If you try it around a dense body like a neutron star and then measure how deep a hole to the core is, you will indeed find that the distance to the centre and interior volume is a bit bigger than expected from the circumference: there is some stretching of the space near and in heavy masses.
However, black holes do not really have infinite volume. Actually defining a volume of a black hole is surprisingly tricky, since it matters when we measure it and across what kind of slice of spacetime (remember, on the inside radial and time coordinates kind of switch meaning). Christodoulou and Rovelli worked out one approach that gives a surprisingly large, but finite, interior volume of black holes. Others have extended it to rotating black holes. These volumes are not really what one would observe if one were to dive in, though. In a sense the radial coordinate becomes your time, counting down inexorably toward meeting the singularity, and the time coordinate helps adding volume. So saying the type of space inside is different is not entirely wrong.


Q:

Filter property from multiple objects in array

I have an array of objects that look like this
const data = [
    {id: 1, locale: 'en'},
    {id: 2, locale: 'nl'}
]

Now I'm trying to filter out the locale property in every item in the array (not delete it for good, just filter it out this once), so my data would ideally resemble this:
const data = [
    {id: 1},
    {id: 2}
]

I've tried

Using a map function to spread out the properties, but I'm stuck as to how to continue with this.
this.translations.map(translation => {
    return { ...translation }
})

A:

You can use parameter destructuring to extract the locale and keep the other ones:

const data = [
    {id: 1, locale: 'en'},
    {id: 2, locale: 'nl'}
]

const withoutLocale = data.map(({locale, ...rest}) => rest)

console.log(withoutLocale)


Q:

How can I view my pending edits?

After editing some questions I got edit saying that too many pending edits. So, I need to check them which of those are still in pending. This will also help me to revise them and keep track of my edited post.
How can see my pending edited posts ?

A:

If you look at your activity on your user profile, there is a tab for "All Actions". Within that is a sub-tab which contains all suggested edits you've made, and the list will show them as "pending" when they have not yet been reviewed:


Q:

Is the range of the Radon-Nikodym derivative always measurable?

I am a student majoring applied mathematics. While writing my thesis paper, I found out that I need to prove or disprove the following statement:
Suppose that $P$ and $Q$ are probability measures on the same measurable space, and $Q$ is absolutely continuous with respect to $P$. Then, the range of $dQ/dP$ is a measurable subset of $\mathbb{R}$.
I made several attempts to prove the statement or find a counterexample, but I am having difficulties. Is there anyone who knows an answer to this question? Thank you.

A:

The question is not quite meaningful.  The Radon-Nikodym derivative $dQ/dP$ can be any nonnegative (a.e.) member $f$ of $L^1(P)$ with $\int f\; dP = 1$.  However, members of
$L^1$ are not really functions, but rather equivalence classes of functions under equality almost everywhere.  So there really is nothing you can point to as the range of $f$.
You can change $f$ arbitrarily on a set of $P$-measure $0$, and it is
the same as a member of $L^1(P)$, but it has a different range.  Now given any non-measurable subset $Y$ of $\mathbb R$ and any subset $X$ of $\mathbb R$ with cardinality $c$ and measure $0$, there is a function taking $X$ onto $Y$.  So it can be that some representatives of $f$ have measurable range while others do not.


Q:

Order by datetime field DESC or order by primary key DESC?

This should be a fairly regular operation: when retrieving records from a table in DB, I need them to be ordered by descending creation date time. But if I use a AUTOINCREMENT key, I can also order by descending key value.
My question is: which is better?

Performance-wise, I know primary keys and datatime fields use different type of indice, which one is more efficient?
Do they always return the same result? Does AUTO-INCREMENT key wrap around when it reaches maximum?

A:

I think you should identify the sorted columns clearly. If not, the order of result can be changed if you update 1 line of data


Q:

Server 2008 Firewall not allowing connection through

Running Server 2008 R2. I'm trying to get a Zabbix agent working. The agent works if I turn off the firewall on the server. For obvious reasons, I don't want to leave the firewall off.
As per the Zabbix instructions, I opened inbound TCP ports 10050-10051 on the server (also tried UDP) via WF.msc. As soon as the firewall is turned on, everything stops working. I enabled the firewall log which of course is (and remains) empty. Nothing in event viewer, either.
Any ideas why WF.msc directives might not be honored?

A:

First, I suggest you verify that the application behavior matches the documentation: type netstat -anb in an elevated command-line and you'll get a list of open ports with the associated executable (if possible).
Once you have that, make sure your rules matches the actual listening pattern of your application.
An alternative would be to open the ports not based on port number but based on the executable itself. That might make it easier to manage.


Q:

Reading txt file in Python, selecting rows where a value lies within certain range, writing to csv

I have a large text file (about 44MB) and I'm trying to read and filter it without bankrupting my computer's memory. The text file is comma seperated, with each column representing different weather variables and then each row representing their values over time. I want to select only the rows in which the wind direction lies between 10 and 100 degrees and then to write these rows to a new file (txt file or csv would be fine). I am a complete python noob, so any help would be greatly appreciated!
A sample of the data
hd,Station Number,Year Month Day Hours Minutes in YYYY,MM,DD,HH24,MI format in Local time,Year Month Day Hours Minutes in YYYY,MM,DD,HH24,MI format in Local standard time,Year Month Day Hours Minutes in YYYY,MM,DD,HH24,MI format in Universal coordinated time,Precipitation since last (AWS) observation in mm,Quality of precipitation since last (AWS) observation value,Air Temperature in degrees Celsius,Quality of air temperature,Air temperature (1-minute maximum) in degrees Celsius,Quality of air temperature (1-minute maximum),Air temperature (1-minute minimum) in degrees Celsius,Quality of air temperature (1-minute minimum),Wet bulb temperature in degrees Celsius,Quality of Wet bulb temperature,Wet bulb temperature (1 minute maximum) in degrees Celsius,Quality of wet bulb temperature (1 minute maximum),Wet bulb temperature (1 minute minimum) in degrees Celsius,Quality of wet bulb temperature (1 minute minimum),Dew point temperature in degrees Celsius,Quality of dew point temperature,Dew point temperature (1-minute maximum) in degrees Celsius,Quality of Dew point Temperature (1-minute maximum),Dew point temperature (1 minute minimum) in degrees Celsius,Quality of Dew point Temperature (1 minute minimum),Relative humidity in percentage %,Quality of relative humidity,Relative humidity (1 minute maximum) in percentage %,Quality of relative humidity (1 minute maximum),Relative humidity (1 minute minimum) in percentage %,Quality of Relative humidity (1 minute minimum),Wind (1 minute) speed in km/h,Wind (1 minute) speed quality,Minimum wind speed (over 1 minute) in km/h,Minimum wind speed (over 1 minute) quality,Wind (1 minute) direction in degrees true,Wind (1 minute) direction quality,Standard deviation of wind (1 minute),Standard deviation of wind (1 minute) direction quality,Maximum wind gust (over 1 minute) in km/h,Maximum wind gust (over 1 minute) quality,Visibility (automatic - one minute data) in km,Quality of visibility (automatic - one minute data),Mean sea level pressure in hPa,Quality of mean sea level pressure,Station level pressure in hPa,Quality of station level pressure,QNH pressure in hPa,Quality of QNH pressure,#
hd, 40842,2000,03,20,10,50,2000,03,20,10,50,2000,03,20,00,50,      ,N, 25.7,N, 25.7,N, 25.6,N, 21.5,N, 21.5,N, 21.4,N, 19.2,N, 19.2,N, 19.0,N, 67,N, 68,N, 66,N, 13,N,  9,N,100,N,  4,N, 15,N,     ,N,1018.6,N,1017.5,N,1018.6,N,#
hd, 40842,2000,03,20,10,51,2000,03,20,10,51,2000,03,20,00,51,   0.0,N, 25.6,N, 25.8,N, 25.6,N, 21.5,N, 21.6,N, 21.5,N, 19.2,N, 19.4,N, 19.2,N, 68,N, 68,N, 66,N, 11,N,  9,N,107,N, 11,N, 13,N,     ,N,1018.6,N,1017.5,N,1018.6,N,#
hd, 40842,2000,03,20,10,52,2000,03,20,10,52,2000,03,20,00,52,   0.0,N, 25.8,N, 25.8,N, 25.6,N, 21.7,N, 21.7,N, 21.5,N, 19.5,N, 19.5,N, 19.2,N, 68,N, 69,N, 66,N, 11,N,  9,N, 83,N, 13,N, 13,N,     ,N,1018.6,N,1017.5,N,1018.6,N,#

this is my best code, which keeps produce a NULL BYTE error message
import csv

with open("X:\hd_040842_2000_03.txt") as input, open("X:\wanted.txt", "w") as wanted, open("X:\unwanted.txt", "w") as unwanted:
   reader = csv.DictReader(input, delimiter=",")
   fieldnames = reader.fieldnames
   writer_wanted = csv.DictWriter(college, fieldnames, delimiter=",")
   writer_unwanted = csv.DictWriter(adult, fieldnames, delimiter=",")
   writer_wanted.writeheader()
   writer_unwanted.writeheader()
   for row in reader:
       if float(row["Wind (1 minute) direction in degrees true"]) > 10.0 and float(row["Wind (1 minute) direction in degrees true"]) < 110.0:
          writer_college.writerow(row)
       else:
          writer_adult.writerow(row)

So you know, I adapted this code as best I could from this post Use Python to select rows with a particular range of values in one column

A:

When working with csv files (in Python 2.x) you need to open the file using rb mode. Secondly, as your data contains a lot of leading spaces in the cells, I suggest adding the skipinitialspace=True parameter. Lastly, your posted code still had some left over changes from where you had copied it from, the following appears to work for the data you have provided:
import csv

with open(r"X:\hd_040842_2000_03.txt", "rb") as input, open(r"X:\wanted.txt", "wb") as wanted, open(r"X:\unwanted.txt", "wb") as unwanted:
   reader = csv.DictReader(input, delimiter=",", skipinitialspace=True)
   fieldnames = reader.fieldnames
   writer_wanted = csv.DictWriter(wanted, fieldnames, delimiter=",")
   writer_unwanted = csv.DictWriter(unwanted, fieldnames, delimiter=",")
   writer_wanted.writeheader()
   writer_unwanted.writeheader()

   for row in reader:
       if 10.0 <= float(row["Wind (1 minute) direction in degrees true"]) <= 110.0:
          writer_wanted.writerow(row)
       else:
          writer_unwanted.writerow(row)

Note, if you are still getting problems, then add some diagnostics:
import csv

with open(r"X:\hd_040842_2000_03.txt", "rb") as input, open(r"X:\wanted.txt", "wb") as wanted, open(r"X:\unwanted.txt", "wb") as unwanted:
    reader = csv.DictReader(input, delimiter=",", skipinitialspace=True)
    fieldnames = reader.fieldnames
    writer_wanted = csv.DictWriter(wanted, fieldnames, delimiter=",")
    writer_unwanted = csv.DictWriter(unwanted, fieldnames, delimiter=",")
    writer_wanted.writeheader()
    writer_unwanted.writeheader()

    for line_number, row in enumerate(reader, start=1):
        try:
            if 10.0 <= float(row["Wind (1 minute) direction in degrees true"]) <= 110.0:
                writer_wanted.writerow(row)
            else:
                writer_unwanted.writerow(row)
        except:
            print "Failed to parse line", line_number
            print row

This will display the line number and row of any rows that cause a problem so you can investigate where the problem is.


Q:

Are answers that just contain a link acceptable?

If somebody answers by just putting a link, is the answer acceptable?
Should the answer be flagged as "not an answer"?

A:

This has been covered numerous times previously; the most thorough being the MSO post, Are answers that just contain links elsewhere really "good answers"?
Short version: it's a really bad idea.
A link isn't an answer; it's just a pointer to a possible answer. With no context, someone seeing just a link doesn't know if it might be on-topic, off-topic, a joke, or spam. Even a little bit of context helps make it clear why the link is worth following.
Additionally, answers here should be for the long term. If someone has the same problem two years from now, the link that's currently to a great blog post may well later be a 404 (or worse). If the link was the entire answer, then Apple.SE no longer has an answer for the question.
Link-only answers should be flagged as what they are: not answers.


Q:

Any+Time DatePicker - show popup below field

I'm using the Any+Time DatePicker and when I click on the date field, the calendar UI displays above the date field. It is obstructing information that would be useful to help enter the date. Is there a way to get the calendar UI to appear below the field that has been clicked upon?
My code is:
$("#start_date").click(
        function(e) {
            $("#start_date").AnyTime_noPicker().AnyTime_picker({ format: '%d-%m-%Y'}).focus();
            e.preventDefault();
        }
    );

Solution:
comment out line 3051 from anytime.js version 4.1112L.The line is:
if ( top < 0 )

A:

Short answer: comment out line #3051 of anytime.js version 4.1112L
Long answer: The pos() method positions the picker relative to the input field. By default, the method tries to place the picker above the field.  Line #3051 tests to see if there is space there for it.  If not, line #3052 moves the picker below the field instead. Simply commenting out line #3051 will cause the method to ALWAYS move the picker below the field.
If you have further questions or problems using Any+Time(TM), try using the contact page on www.AMA3.com for a faster response!


Q:

Building relationships in neo4j

I have a csv file that has 5 columns Sender, Receiver, Weight, Fairness Score (of Sender), Goodness Score (of Receiver).

I am trying to create a network in NEO4J where goodness is a property of the sender and fairness is the relationship between the sender and the receiver. I also want it to import distinct values because I have senders that are receivers and receivers that are also senders.

A:

If you are asking for a query to generate data from your file, this is roughly what you want (if you want to avoid duplicate nodes and relationships):
LOAD CSV WITH HEADERS FROM 'file:///input.csv' AS row
MERGE(s:Person {id: row.Sender})
SET s.fairness = TOINTEGER(row.`Fairness Score`)
MERGE(r:Person {id: row.Receiver})
SET s.goodness = TOINTEGER(row.`Goodness Score`)
MERGE (s)-[hr:SENDS_TO]->(r)
SET hr.weight = TOINTEGER(row.Weight)

In the future, you need to put much more info into your questions (like what your desired data model is, what you have already tried, and what the results were). And, most importantly, you need to actually state a question!


Q:

Is every closed subgroup of dual group an annihilator?

Let $G$ be a LCA group. It is well-known that to every closed subgroup $H$ of $G$ correspond a closed subgroup in the dual group $\widehat{G}$, namely the annihilator of $H$.
My question is this : is there a one-to-one correspondance between the closed subgroups of $G$ and the closed subgroups of the dual group $\widehat{G}$ ? Is every closed subgroup of $\widehat{G}$ an annihilator for some closed subgroup $H$ of $G$ ?

A:

Each closed subgroup $i: H \to G$ (each regular mono, in category-speak) induces a quotient map of topological groups $\hat{i}: \hat{G} \to \hat{H}$ (a regular epi), whose kernel is the annihilator. There is a one-one correspondence between such regular monos and regular epis under the Pontryagin dual equivalence. Furthermore, if $K$ is any closed subgroup of the LCA group $\hat{G}$, then the quotient $\hat{G}/K$ is also LCA. So we have one-one correspondences between (1) closed subgroups of $G$, (2) LCA quotient groups of $\hat{G}$, and (3) closed subgroups of $\hat{G}$.


Q:

glide crashing when I go to another activity

I load image from Server with Glide in Recyclerview  adapter The problem occurs just when I close the Activity or go to another activity,
   @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder,  int position) {

            final MyAdapterHolader postholader = (MyAdapterHolader) holder;

            final ListMeesg move = (ListMeesg) moveList.get(position);
              glide.asBitmap().load(move.imagp).skipMemoryCache(true).override(move.width,move.hegth).format(DecodeFormat.PREFER_RGB_565).into(new CustomTarget<Bitmap>(move.width,move.hegth) {
                            @Override
                            public void onResourceReady(@NonNull final Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                postholader.imgtitle.setImageBitmap(resource);
                                new Thread(new Runnable() {
                                    public void run() {

                                        File file1 = new File(Environment.getExternalStoragePublicDirectory("/Android/data/mjplus.messages/"), move.imagn);
                                        try {
                                            if (!file1.exists()) {
                                                FileOutputStream fileOutputStream;

                                                fileOutputStream = new FileOutputStream(file1);
                                                resource.compress(CompressFormat.JPEG, 80, fileOutputStream);
                                                fileOutputStream.close();
                                            }
                                        } catch (IOException e2) {

                                            e2.printStackTrace();
                                        }

                                    }
                                }).start();
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {

                                postholader.imgtitle.setImageDrawable(placeholder);

                            }

                            @Override
                            public void onDestroy() {

                            }

                            @Override
                            public void onStop() {

                            }

                            @Override
                            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                             ]

                            }

                            @Override
                            public void onLoadStarted(@Nullable Drawable placeholder) {
                             ]

                            }

                        });

    }

logcat:
09-16 17:51:34.621 29129-29144/mjplus.messages I/art: Background partial concurrent mark sweep GC freed 30594(2MB) AllocSpace objects, 26(4MB) LOS objects, 36% free, 28MB/44MB, paused 3.442ms total 115.362ms
    09-16 17:51:34.661 29129-29141/mjplus.messages E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
                                                                 java.lang.Throwable: Explicit termination method 'close' not called
                                                                     at dalvik.system.CloseGuard.open(CloseGuard.java:184)
                                                                     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:287)
                                                                     at com.android.okhttp.Connection.upgradeToTls(Connection.java:242)
                                                                     at com.android.okhttp.Connection.connect(Connection.java:162)
                                                                     at com.android.okhttp.Connection.connect(Connection.java:174)
                                                                     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:316)
                                                                     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:249)
                                                                     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:397)
                                                                     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
                                                                     at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
                                                                     at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
                                                                     at com.android.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.connect(TrackedHttpURLConnection.java:128)
                                                                     at com.android.tools.profiler.support.network.httpurl.HttpsURLConnection$.connect(HttpsURLConnection$.java:366)
                                                                     at com.bumptech.glide.load.data.HttpUrlFetcher.loadDataWithRedirects(HttpUrlFetcher.java:104)
                                                                     at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:59)
                                                                     at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100)
                                                                     at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:62)
                                                                     at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:309)
                                                                     at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:279)
                                                                     at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:235)
                                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                     at java.lang.Thread.run(Thread.java:818)
                                                                     at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:446)
    09-16 17:51:34.661 29129-29141/mjplus.messages W/System.err: StrictMode VmPolicy violation with POLICY_DEATH; shutting down.

A:

the problem is with your close not being called when Glide got interrupted

A resource was acquired at attached stack trace but never released.
  See java.io.Closeable for information on avoiding resource leaks.
  java.lang.Throwable: Explicit termination method 'close' not called at
  dalvik.system.CloseGuard.open(CloseGuard.java:184) at

you can use the try-with-resource
 if (!file1.exists()) {
   try (
     //put the resources that you want to close in the round brackets
     FileOutputStream fileOutputStream = new FileOutputStream(file1);
    ){

     resource.compress(CompressFormat.JPEG, 80, fileOutputStream);

    } catch (IOException e2) { ... your exception stuff...}
 }

Notice that there is no longer a need to call the close.


Q:

Rails has_many through: (many to many relationship) error uninitialized constant Group::Keywords

A Group can have many keywords and a Keyword can have many groups. I have this relationship defined as
class Keyword < ActiveRecord::Base
   has_many :groups_keywords
   has_many :groups, through: :groups_keywords
end

class GroupsKeyword < ActiveRecord::Base
  belongs_to :groups
  belongs_to :keywords
end

class Group < ActiveRecord::Base
  has_many :groups_keywords
  has_many :keywords, through: :groups_keywords
end

I can do Group.find(1).groups_keywords so the relationship is working?
But I want to get all of my Groups keywords so I do the following.
Group.find(1).keywords
But I get the error uninitialized constant Group::Keywords

A:

Try changing the below
class GroupsKeyword < ActiveRecord::Base
  belongs_to :groups
  belongs_to :keywords
end

to
class GroupsKeyword < ActiveRecord::Base
  belongs_to :group
  belongs_to :keyword
end


Q:

WebGL FrameBuffer - Render Depth Texture

I am in the process of integrating post processing effects into my 3D engine. I have hit a roadblock with capturing depth data using a FrameBuffer Object with WebGL. There has been no issue capturing color data into the FrameBuffer. However, I am not able to get any Depth data even with the Depth Extension enabled for Chrome/Firefox.
var DepthEXT = webGLContext.getExtension( "WEBKIT_WEBGL_depth_texture" ) ||
                webGLContext.getExtension( "MOZ_WEBGL_depth_texture" );

I have tried many different settings to see if it was a configuration issue, but no matter what I try I just see a white texture. The screenshot at the end of the post shows the color attachment rendered as a texture and the depth attachment rendered as a texture. Is there a problem with my initialization of the FrameBuffer or should I be looking elsewhere to solve this issue?
Below is my code for initializing the FrameBuffer Object:
    // Frame Buffer
    this.m_frameBuffer = gl.createFramebuffer();
    gl.bindFramebuffer( gl.FRAMEBUFFER, this.m_frameBuffer );

    // Render Buffer
    this.m_renderBuffer = gl.createRenderbuffer();
    gl.bindRenderbuffer( gl.RENDERBUFFER, this.m_renderBuffer );
    gl.renderbufferStorage(
        gl.RENDERBUFFER,
        gl.DEPTH_COMPONENT16,
        sharedRenderer.canvasDOMElement.width,
        sharedRenderer.canvasDOMElement.height );

    // Diffuse Component
    this.m_diffuseComponentTexture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, this.m_diffuseComponentTexture );

    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_MAG_FILTER,
        gl.LINEAR );

    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_MIN_FILTER,
        gl.LINEAR );

    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(
        gl.TEXTURE_2D,
        0,
        gl.RGBA,
        sharedRenderer.canvasDOMElement.width,
        sharedRenderer.canvasDOMElement.height,
        0,
        gl.RGBA,
        gl.UNSIGNED_BYTE,
        null );

    // Depth
    this.m_depthComponentTexture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, this.m_depthComponentTexture );

    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_MAG_FILTER,
        gl.NEAREST );

    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_MIN_FILTER,
        gl.NEAREST );

    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(
        gl.TEXTURE_2D,
        0,
        gl.DEPTH_COMPONENT,
        sharedRenderer.canvasDOMElement.width,
        sharedRenderer.canvasDOMElement.height,
        0,
        gl.DEPTH_COMPONENT,
        gl.UNSIGNED_SHORT,
        null );

    // FrameBuffer
    // Diffuse
    gl.framebufferTexture2D(
        gl.FRAMEBUFFER,
        gl.COLOR_ATTACHMENT0,
        gl.TEXTURE_2D,
        this.m_diffuseComponentTexture,
        0 );

    // Depth
    gl.framebufferTexture2D(
        gl.FRAMEBUFFER,
        gl.DEPTH_ATTACHMENT,
        gl.TEXTURE_2D,
        this.m_depthComponentTexture,
        0 );

    // RenderBuffer
    gl.framebufferRenderbuffer(
        gl.FRAMEBUFFER,
        gl.DEPTH_ATTACHMENT,
        gl.RENDERBUFFER,
        this.m_renderBuffer );

    // Unbind buffers and textures
    gl.bindTexture( gl.TEXTURE_2D, null );
    gl.bindRenderbuffer( gl.RENDERBUFFER, null );
    gl.bindFramebuffer( gl.FRAMEBUFFER, null );

Here is the code where I render the current scene to the FrameBuffer.
CBRenderer.prototype.renderSceneToGBuffer = function( sceneToRender, GBufferTarget, deltaSeconds )
{
        CBMatrixStack.clearMatrixStackAndPushIdentityMatrix();

        this.applyProjectionMatrix();

        GBufferTarget.bindGBufferFrameBuffer();

        this.renderer.enable( this.renderer.DEPTH_TEST );
        this.renderer.depthMask( true );
        this.renderer.clearDepth( 1.0 );
        this.renderer.clearColor( 0.1, 0.1, 0.1, 0.0 );

        this.renderer.clear( this.renderer.COLOR_BUFFER_BIT | this.renderer.DEPTH_BUFFER_BIT );

        sceneToRender.render( deltaSeconds );

        this.renderer.flush();

        GBufferTarget.m_dirty = false;
        GBufferTarget.unbindGBufferFrameBuffer();

        this.renderer.clearColor( 0.0, 0.0, 0.0, 0.0 );
        this.renderer.clear( this.renderer.COLOR_BUFFER_BIT | this.renderer.DEPTH_BUFFER_BIT );

        this.renderer.bindTexture( this.renderer.TEXTURE_2D, null );
}

A:

You don't have the depth texture attached to your FBO at the end of setting it up. You do set the texture as the depth attachment at some point:
// Depth
gl.framebufferTexture2D(
    gl.FRAMEBUFFER,
    gl.DEPTH_ATTACHMENT,
    gl.TEXTURE_2D,
    this.m_depthComponentTexture,
    0 );

But immediately following that, you set a renderbuffer as the depth attachment instead:
// RenderBuffer
gl.framebufferRenderbuffer(
    gl.FRAMEBUFFER,
    gl.DEPTH_ATTACHMENT,
    gl.RENDERBUFFER,
    this.m_renderBuffer );

You can have only one target attached to each FBO attachment point. So the second call sets a new depth attachment, replacing the one you just set in the first call. So at the end of this, m_depthComponentTexture is not attached to the FBO anymore.
If you want to use a depth texture, I don't see why you would want to create a depth renderbuffer as well. You should only need one of the two. You would normally use a renderbuffer for the depth if you don't need it for sampling later. If you want to sample from the result, you need a texture instead, and there's no need for a renderbuffer anymore.


Q:

Obter texto dentro de input com input-group-addon de radiobutton

Tenho esse form com esses inputs, quero obter o valor que esta dentro do input do radio button selecionado, exemplo como na imagem, eu deveria obter "bb".

Meu html:
Respostas:

                                <input type="radio" name="respostacorreta">

                            <input type="text" class="form-control" id="pergunta1">

                                <input type="radio" name="respostacorreta">

                            <input type="text" class="form-control" id="pergunta2" >

                                <input type="radio" name="respostacorreta" >

                            <input type="text" class="form-control" id="pergunta3">

Meu jquery até então, estou obtendo apenas o texto de todos os campos:

A:

Para pegar o input selecionado use:
$('input[name="respostacorreta"]:checked')

E depois suba um Nivel usando .parent() para pegar o próximo input que existe
Exemplo:
Fiquei com preguiça de carregar o Bootstrap

$('button').click(function(){
    var resposta = $('input[name="respostacorreta"]:checked').parent().next('input').val();
    alert(resposta);
});

Respostas:

                                <input type="radio" name="respostacorreta">

                            <input type="text" class="form-control" id="pergunta1">

                                <input type="radio" name="respostacorreta">

                            <input type="text" class="form-control" id="pergunta2" >

                                <input type="radio" name="respostacorreta" >

                            <input type="text" class="form-control" id="pergunta3">

<button>Ação!</button>


Q:

Can I run compiz with specified profile from terminal?

I am making a personal Desktop Environment and one of the programs I use is compiz. However, I need to execute all my components from a shell script, and every time I launch compiz it runs in its default mode. Is there any way to run Compiz from the terminal while telling it to use a CCSM profile? Thanks in advance.

A:

No, you can't. So far, you can use ccsm with only one from the following four options:

-h (--help) - show the help message and exit
-p PLUGIN (--plugin=PLUGIN) -open ccsm to the page of PLUGIN. For example:
ccsm -p expo

-c CATEGORY (--category=CATEGORY) - open ccsm directly to CATEGORY. For example:
ccsm -c "Window Management"

-v (--version) -display the current version of ccsm and exit.

See man ccsm to check all of these.

Meanwhile, in your script, you can play with a command similar to the following:
(ccsm &) && sleep 2 && xdotool key Tab Tab Tab Tab Tab Tab Tab Tab Tab Tab Tab Return && sleep 2 && xdotool key Tab Tab Tab Tab Tab Tab Tab Return && sleep 2 && xdotool key slash p a t h slash t o slash y o u r underscore c c s m period p r o f i l e Return

You only need to adapt it to your system.


Q:

How to "return" an error message from a C# property setter to the user?

I have a windows form that allows the user to input an integer value. This value is used to update a member of a separate class (foo) so long as it falls within a certain valid range. If the user inputs something invalid, I want an error message to tell the user that the default value for the parameter will be used.
In order to accomplish this, I have been error checking the user input within the code for the windows form before letting foo set the field in question, and simply displaying a message if the input fails the check.
But what I would like to do is send the raw user input to a property setter within the class foo and have the property setter handle all the error checking. For other functions in foo that may require a message be displayed on the user interface, I am simply returning a string, but to my knowledge there is no way to return any sort of status or value from a property setter. Is there a graceful way to bubble up a status message of some sort from a property setter to a different function? I don't want foo to modify the user interface directly.
Thanks in advance for any help or tips, and I apologize if my question is too vague or should be asked differently as I am new to StackOverflow

A:

I fixed my problem (as well as removed the need to return strings from nearly all my functions) by implementing INotifyPropertyChanged in my class foo and raising a PropertyChanged event to be caught by the windows form whenever it was necessary to let the user know something had changed.
in class foo-
public class foo : INotifyPropertyChanged {

    public event PropertyChangedEventHandler PropertyChanged;
    public int bar;

    private void NotifyPropertyChanged(string type) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(type));
        }
    }

    private void test(){
        bar = 1;
        NotifyPropertyChanged("changed int");
    }

}

in the windows form:
public partial class GUI : Form {
     foo fooinstance = new foo();

     public GUI(){
           InitializeComponent();
           fooinstance.PropertyChanged += doEvent;
     }

     private void doEvent(object sender, PropertyChangedEventArgs e){
        foo updated = sender as foo;
        if (object.ReferenceEquals(e.PropertyName, "changed int")) {
            ShowWhatChanged(updated.bar); //show on GUI
        }
     }

}
EDIT:
A more graceful and cleaner way that I ended up using was to utilize callbacks. The GUI passed a function pointer into foo upon instantiation and foo used it as a delegate to pass strings back to the GUI whenever necessary. No events required:
public class foo {

    public delegate void UpdateCallback(string msg);
    private UpdateCallback _ucb;
    public foo(UpdateCallback cb){
        _ucb = cb;
    }

    private void test(){
        if(_ucb != null) {
           _ucb("Message Here");
        }
    }
}

public partial class GUI : Form {

     public GUI(){
           InitializeComponent();
           foo fooinstance = new foo(showmessage);

     }

     private void showmessage(string msg){
           //do whatever with the message
     }
}