Q:

Creating project using angular cli throws schematic flow error

I am trying to learn Angular and have installed nodejs version 14 and installed angularcli but when I use the command ng new proj it throws error

Installing packages...npm WARN deprecated tslint@6.1.2: TSLint has
been deprecated in favor of ESLint. Please see
https://github.com/palantir/tslint/issues/4534 for more information.
npm WARN deprecated request@2.88.2: request has been deprecated, see
https://github.com/request/request/issues/3142 npm WARN deprecated
chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to
chokidar 3 with 15x less dependencies. npm WARN deprecated
fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using
insecure binaries. Upgrade to fsevents 2. npm WARN deprecated
urix@0.1.0: Please see https://github.com/lydell/urix#deprecated npm
WARN deprecated resolve-url@0.2.1:
https://github.com/lydell/resolve-url#deprecated npm ERR! Unexpected
end of JSON input while parsing near '...d701271192d27fd28ddc9'
npm ERR! A complete log of this run can be found in: npm ERR!     C:\Users\bhask\AppData\Roaming\npm-cache_logs\2020-06-15T15_42_15_755Z-debug.log
× Package install failed, see above. The Schematic workflow failed.
See above.

my project's package.json contents
{
  "name": "hello",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.1.11",
    "@angular/common": "~9.1.11",
    "@angular/compiler": "~9.1.11",
    "@angular/core": "~9.1.11",
    "@angular/forms": "~9.1.11",
    "@angular/platform-browser": "~9.1.11",
    "@angular/platform-browser-dynamic": "~9.1.11",
    "@angular/router": "~9.1.11",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.901.8",
    "@angular/cli": "~9.1.8",
    "@angular/compiler-cli": "~9.1.11",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~5.0.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~3.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~3.8.3"
  }
}

I have tried to uninstall and install older version of nodejs but the issue still prevails

A:

Run

npm cache clean --force

Run

npm i - @angular/cli@latest

Then run your project creation command.


Q:

CLion "Instantiating an unknown structure without reference" but compiles fine

I've been trying to get my cmake project set up with HDF5 on Windows 10 (64bit), using the CLion editor and MinGW. After a ton of time trying to get my CMakeLists file set up properly, I got something working - the code compiles, no errors from mingw32-make or from cmake. However, I'm still getting red underlined errors in CLion, which don't seem to have any impact on the build, but I have a feeling that they're there because I did something incorrect. (I'm very new doing anything more than class projects with C++)
Here is my CMakeLists.txt
cmake_minimum_required(VERSION 2.8)

project(testProject)
add_definitions(-std=c++11)
set(SOURCE_FILES hdf_example.cpp)

link_libraries("C:/Program Files/HDF_Group/HDF5/1.8.16/lib/hdf5_hl_cpp-shared.lib"
               "C:/Program Files/HDF_Group/HDF5/1.8.16/lib/hdf5_cpp-shared.lib"
               "C:/Program Files/HDF_Group/HDF5/1.8.16/lib/hdf5-shared.lib")

add_executable (abc hdf_example.cpp)

Compiling this from the command line using mingw32-make or in the IDE both result a successful compilation with no errors or warnings that I can see.
C:\Users\Me\Documents\project_name\temp-build\src\abc>mingw32-make
[ 50%] Building CXX object src/s3/CMakeFiles/abc.dir/hdf_example.cpp.obj
[100%] Linking CXX executable abc.exe
[100%] Built target abc

Is this something I should be concerned about? Or should I just ignore it since everything compiles?

A:

I had this problem and solved it by placing #include <getopt.h> above #include <unistd.h> in the C file. This could be viewed as a bug in CLion. I have created an issue for this. The workaround for now is to rearrange your imports.
For details you can also read my question about this.
Instantiating an unknown structure without a reference

A:

Your IDE and building tools are two "completely" different processes. You have nothing to worry about if your code compiles with Cmake and MingW. You probably have configured your IDE with different settings than given in your CMakeLists. You need to link the hdf5 C++ library in your editor to solve the "problems" in your IDE. This will only improve readability.


Q:

Do we need a canonical question on infected Android and iOS?

We have a canonical question on how to handle a PC and one for servers.
Recent activity highlights that we also get questions about "possibly infected" Android and iOS. (More Android than iOS?). They tend to get closed pretty quickly, and hence deleted, so there is not many to find via search.
This presents us with an opportunity to create a "Help! I think my Android/iOS is infected! What do I do?" canonical question.
Should we provide a dupe target for these questions so that we can provide some kind of help? Can such a question be constrained enough to provide concise instructions that would be applicable across a wide range of issues?
Do we need one for iOS and another for Android, or can they be combined?

A:

Yes, we should have a duplicate.
Closing as a duplicate of a canonical question is far the best user experience for the person asking the question, and for people finding it via google later. Just having the question closed, or marked as a duplicate of some specific question describing different circumstances doesn't quite do it.
But it's not easy to ask the right question. One problem is that what people belive is caused by a virus often isn't. A lot of these questions are about situations where it's unclear if it's a virus or not. If we close "I got a error message on a website, do I have a virus?" as a duplicate of "do a full factory reset" we are not helping anyone...
In the PC question I specifically excluded this from the question by just stating that there was a virus. I don't know if that was a good idea for that question, and I don't know if it's a good idea for this one. Just wanted to highlight the issue.
Just brainstorming questions here...

Do I have a virus on my phone? To broad! There's no way to give a general answer.
I have a virus, what do I do? Good in theory, but in practice this is not what people are asking.
How do I do a factory restet? To hands on to be on topic.


Q:

Upgradation of Windows phone 8 App to windows phone 8.1

We have created a net banking app last year for a bank. Now we are supposed to upgrade that app to Windows Phone 8.1. I know that windows phone 8 app will definitely run on Windows Phone 8.1. But I need to investigate how we can make the app experience better for the user by using new API. I have been searching over the internet on this could not find anything particular. Can you people please guide me what are the API/Namespaces that has been there in Windows Phone 8 but being deprecated in Windows Phone 8.1. Any pointer or any URL would help.

A:

Currently you have option to build Windows Phone 8.1 Application using the OLD SILVERLIGHT BASED API's used in Windows Phone 8 as well as NEW XAML BASED UNIVERSAL API's which have convergence ratio of 90% between Windows 8.1 & Windows Phone 8.1. If you want to know the features that you can have in Windows Phone 8.1 application then I suggest you go through
1: Building Apps for Windows Phone 8.1 Video Tutorials (At least first few) - This video series gives you the basics of Windows Phone 8.1 application developement
2: Windows Phone 8.1 Development for Absolute Beginners This will also help you in understanding the basics & start developing WP 8.1 applications using NEW XAML BASED API's
3: What's New in Windows Phone 8.1 Microsoft Documentation
You will find much more blogs on internet describing the differences between WP 8 & 8.1 but the above links will briefly cover the technical differences.
Hope this helps.


Q:

Do Rational Functions Act $n$-Transitively on $\mathbb{C}$?

Let $p_1, ..., p_n$ be $n$ distinct points in $\mathbb{C}$, and let $q_1, ..., q_n$ be $n$ distinct points in $\mathbb{C}$. Is there a rational function $f \in \mathbb{C} (x)$ such that $f(p_i) = q_i$ for each $1 \leq i \leq n$? Thinking of $\mathbb{C}(x)$ as a monoid under composition, this question asks whether $\mathbb{C}(x)$ acts $n$-transitively on $\mathbb{C}$.
More importantly, if this is false, then is there a nice description of the set of pairs $((a_1, ..., a_n), (b_1, ..., b_n)) \in \mathbb{C}^n \times \mathbb{C}^n$ for which there is a rational function $f \in \mathbb{C}(x)$ such that $f(a_i) = b_i$?
A rational function is determined by its preimages counting multiplicities at 3 distinct points, so I suspect this is false.

A:

By Lagrange interpolation, you don't even need rational functions — polynomials suffice.


Q:

Customer Authentication in a website

Just to be clear, by authentication I don't mean user-authentication, but I want to make sure that my app is running on the customer's server and in a defined time-span.
Some of our customers use our web apps in their Intranet and on their own servers, on the other hand some of them use Hosting services and they don't own any server machine.
With that said, I'm looking for ways to make sure about customer's Identity. I don't want them to be able to xcopy the app, also I'd like to have some kind of time-expiration limit.
In traditional desktop apps we could use USB security tokens, but their not usable with hosting providers.
It seems that we have to make a central authentication server. I'm a little confused about possible options, so any suggestion about where to start is welcome.

A:

This is a very complex thing. What you need is a licensing mechanism where you create for example a key based on unique system information like servername, mac address, company name, cpu id, etc. You can also have a compbination of those information. After that you need to create a "key generator" and in your software read this information, verify on each startup if they are identical and run the software. Additionally you can add a time information for the expiration date, or days which the user can use your app.
But (and this is my personal opinion) you dont need to develop a super complex licensing mechanism. Nearly everthing is breakable. The question is: is your software worth to put so much effort in cracking your licensing mechanism? Is you app designed for small, mid size or large companies? How expensive is your app?
Here is an SO article on that. Search for 'licensing', 'software licensing [development language]' , 'key generator' ...


Q:

Tensor product of real line bundles is trivial as a map $\mathbb{R}P^\infty\to\mathbb{R}P^\infty\times\mathbb{R}P^\infty\to\mathbb{R}P^\infty$

The tensor product of a real line bundle with itself is trivial, as is easily seen by looking at the transition functions or checking the Stiefel-Whitney class. Real line bundles are classified by the space $\mathbb{R}P^\infty$, and there is a map $\mathbb{R}P^\infty\times\mathbb{R}P^\infty\overset{\mu}{\to}\mathbb{R}P^\infty$ corresponding to tensor product. Hence we should expect that the composite map $\mathbb{R}P^\infty\overset{\Delta}{\to}\mathbb{R}P^\infty\times\mathbb{R}P^\infty\overset{\mu}{\to}\mathbb{R}P^\infty$ be nullhomotopic, where the first map is the diagonal. Is there a way to see this directly? Is there an explicit description of $\mu$ as a map to projective space?

A:

(A representative for) $\mu$ is the "infinite Segre embedding"
$$(x_0 : x_1 : \dots) \times (y_0 : y_1 : \dots) \mapsto (x_0 y_0 : x_0 y_1 : x_1 y_0 : \dots)$$
so the composition with the diagonal is the "infinite Veronese embedding"
$$(x_0 : x_1 : \dots) \mapsto (x_0^2 : x_0 x_1 : x_1 x_0 : x_1^2 : \dots).$$
An explicit nullhomotopy from this map to the map with constant value $(1 : 0 : \dots)$ is given by
$$t \times (x_0 : x_1 : \dots) \mapsto \left( x_0^2 + t (1 - x_0^2) : x_0 x_1 (1 - t) : x_1 x_0 (1 - t) : \dots \right).$$
The reason this works is just that we always have $x_0^2 \ge 0$, and moreover at least one of $x_0^2, x_1^2, \dots$ is nonzero. The subspace of $\mathbb{RP}^{\infty}$ where any coordinate is always positive is contractible, being a copy of $\mathbb{R}^{\infty}$, and in this case we can take $x_0^2 + x_1^2 + \dots$ to be the coordinate (I mean the sum of the coordinates with those entries in it; hopefully this is clear). In order for a map to $\mathbb{RP}^{\infty}$ to not be nullhomotopic it must have the property that every coordinate takes the value $0$ at least once.


Q:

Feedly Mark as Read not working on Objective-C

I'm trying to implement a method in my iOS app to mark an article as read using the Feedly API. However, I keep getting error responses:
{
    "errorCode": 400,
    "errorId": "sandbox-he.2015010906.2770040",
    "errorMessage": "no data"
}

This is the method:
- (void)markRead:(NSString*)articleID {
    NSLog(@"Artidle ID is: %@", articleID);

    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *accessToken = [standardUserDefaults objectForKey:@"AccessToken"];

    NSString *feedUrl = [NSURL URLWithString:@"https://sandbox.feedly.com/v3/markers"];

    NSError *error = nil;

    NSString *post =[[NSString alloc] initWithFormat:@"action=markAsRead&type=entries&entryIds=%@",articleID];
    NSLog(@"PostData: %@",post);

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:feedUrl];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    [request setHTTPBody:postData];
    [request addValue:accessToken forHTTPHeaderField:@"Authorization"];

    //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

    NSError *errror = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&errror];

    NSLog(@"Response code: %ld", (long)[response statusCode]);

    if ([response statusCode] >= 200 && [response statusCode] < 300)
    {
        NSLog(@"Success marking this as read.");

    } else {
        if (error) NSLog(@"Error: %@", errror);
        NSLog(@"No success marking this as read.");
    }

}

The Feedly API describes that it requires this as input:
{
   "entryIds": [
       "TSxGHgRh4oAiHxRU9TgPrpYvYVBPjipkmUVSHGYCTY0=_14499073085:c034:d32dab1f",
       "TSxGHgRh4oAiHxRU9TgPrpYvYVBPjipkmUVSHGYCTY0=_1449255d60a:22c3491:9c6d71ab"
   ],
   "action": "markAsRead",
   "type": "entries"
}

In my opinion I'm providing this as input, so I actually expected a proper response. However, I keep getting 400 and can't seem to figure out what I'm doing wrong. I've been busting my head for hours on this.

A:

Instead of using your current body data, try creating the data with following code:
NSDictionary *bodyDict = [NSDictionary dictionaryWithObjectsAndKeys:@[articleID],@"entryIds",
                          @"markAsRead",@"action",
                          @"entries",@"type", nil];

NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:bodyDict options:0 error:&error];
[request setHTTPBody:postData];

This will send the body as a JSON object.
Sending parameter like you did (with action=markAsRead&type=entries&entryIds=%@) is usually used when calling a web method with the GET request method. Take a look at POST vs GET for a better understanding.


Q:

Jquery returning "Undefined"

We are plotting a Google graph data from a Jquery. No matter what, "data.d" comes back undefined.  It doesn't throw exception, just Google complains that we are passing something wrong.
Taking a step back and looking at the content of argument... well, that is effectively undefined.
ManageProfile.aspx
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="head">

</asp:Content>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

</asp:Content>

ManageProfile.aspx.cs
using System.Web.Services;
using System.Web.Script.Services;

namespace ASPGoogleChart.Dcr_Logged
{
    public partial class ManageProfile : System.Web.UI.Page
    {
        protected void Page_Load()
        {
            GetChartData();

        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static object[] GetChartData()
        {
            var chartData = new object[2];
            chartData[0] = new object[]{
                "Year",
                "Electronics"
            };

            chartData[1] = new object[]{
                20,
                40
            };
            return chartData;
        }
    }
}

A:

 google.setOnLoadCallback(drawChart);
 drawChart();

move those to ajax success not done.


Q:

The team provision profile invalid

On the iPhone Provisioning Portal, the team provisioning profiles with the specific ID is invalid.
As I did some research on net and it said I should click on the Xcode preference, then click the view details about the account, and then click the refresh button on the bottom right corner but I could not find it.

A:

First thing is that you can create,edit or delete provisioning profile (developer,distribution) or certificates which wont effect the apps already live (on app-store). But it will effect the apps that you are using in your current project for testing in Device.
You can Delete all provisioning profiles and certificates. But you have to create again for testing your app in to device as well as upload new app on app-store from iTunes connect.
Apple provide Very nice and clear documentation please read bellow link for more clear
Provisioning and Development
Push Notification
The push certificate cannot be renewed. You have to create a new one.
The push notification certificate is not part of the application build. Therefore for push to continue working you only have to create a new certificate and deploy the p12 file (or whatever other format you are using) at your server. You don't have to submit a new version of your app.
Regarding refreshing the accounts and provisioning profiles, check here and here.


Q:

Java switch constant expression... Is there any clever way to get this to compile?

I'm returning to Java dev after many years away from it. Is there anyway to get this code to compile?
class Mpeg4
    {
    public static final int FourCC2Int(char aA, char aB, char aC, char aD)
        {
        return (aA << 24) | (aB << 16) | (aC << 8) | (aD);
        }

    public static void main(String aArgs[]) throws Exception
        {
        int x = Integer.parseInt(aArgs[0]);

        switch (x)
            {
            case Mpeg4.FourCC2Int('f', 't', 'y', 'p'): // This won't be reduced by the compiler to a constant.
                // doSomething();
                break;

            }
        }
    }

I tried also to have a class constant such as
class Mpeg4
    {
    private static final int KFtyp = Mpeg4.FourCC2Int('f', 't', 'y', 'p');

    public static void main(String aArgs[]) throws Exception
        {
        int x = Integer.parseInt(aArgs[0]);

        switch (x)
            {
            case KFtyp: // Foiled again.
                // doSomething();
                break;
            }
        }
    }

The language has changed quite a bit, and I've done Googling. Is there any way I can keep my code tidy
i.e. not manually reducing the 'macro' or having a potentially massive if-then-else-if block?
Maybe compiler optimisation flags might be one route? I find this situation quite lame.

A:

You could do this
    switch (x) {
    case ('f' << 24) | ('t' << 16) | ('y' << 8) | ('p'):
        // doSomething();
        break;
    }

Here is the JLS on what can go in a constant expression thats part of the case. Turns out its pretty flexible.
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313

A:

switch needs compile-time constant expressions (of integral or enum types, from Java 7 on also strings) for the cases, and the result of a method call is not a compile-time constant. (The compiler will not call your method.)
If you only need a single (or a low number of) case block, use an if instead.
If you have a large number, you could think about using a HashMap or such with the Command pattern. Or let some other program generate your code (e.g. if you are writing a parser).


Q:

A complete dummy in Recursion in C++

Hi guys I have recently learn recursion, I have tried many return types and it seems that I have been struggling in this particular problem for the past day or two. And sadly I got no luck.
The idea is:

I enter a value and base
find its first remainder and store it in a string.
then divide the value by the base to get a new value
Repeat process until the value is 0 or 1, then return the whole string.

Code:
string convert(int value, int b){
    stringstream s;
    //Once the value is 0 or 1 it returns the whole result
    if(value ==0 || value ==1)
        return s.str();
    else
    {
        //I store the remainder results in the stringstream and call the function again
        s<<convert(value/b,b)<<value%b;
    }
}

A:

One critical a-ha moment when dealing with recursion is that it almost never makes sense for the function the user calls to be recursive.  Using recursion usually means using a recursive helper function.
/* this is the helper function */
void convert(stringstream& s, int value, int b)
{
    if (value == 0) return;
    convert(s, value / b, b); /* recursive call */
    s << (char)('0' + value % b);
}

/* this is the function the user calls */
string convert(int value, int b)
{
    stringstream s;
    convert(s, value / b, b); /* calls helper, not itself */
    s << (char)('0' + value % b);
    return s.str();
}

Now the entry point takes care of some special cases:

The ones digit is always stored, even if zero, so that numeric zero becomes "0" and not an empty string.
The entry point creates a stringstream.
The entry point gets and returns the stringstream buffer.

These are steps you don't want the recursive function performing.  Copying a string or stringstream at each recursive call is very wasteful.
Furthermore, a stringstream isn't really helpful here, since there's no real formatted output occurring.  So I would just do:
void convert(string& s, int value, int b)
{
    if (value == 0) return;
    convert(s, value / b, b); /* recursive call */
    s.append('0' + value % b);
}

/* this is the function the user calls */
string convert(int value, int b)
{
    string s;
    convert(s, value / b, b); /* calls helper, not itself */
    s.append('0' + value % b);
    return s;
}


Q:

Old router problem Can't enter setup

I have an old router. When I try going into settings by going to 192.168.1.1 .Then I enter my user-name and password and click on OK and it asks for credentials again and then again and nothing else opens. It just keeps on asking for my user name and password.

A:

There should be a pinhole reset button on the router.  Use a paperclip and hold it in with the power on for about 15-20 seconds.  Afterwards look up the router's manual online to find the default username and password.


Q:

Android : Share intent is not working for video file path

I have a video file path and want to share the video on social media, but unable to share the video. I am trying following code in Android Studio 2.2, but it's not working.
Code snippet :
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button shareBtn = (Button) findViewById(R.id.sharebutton);

    shareBtn .setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {

                    File f = new File("/sdcard/VID_20161201123613.mp4");
                    Uri uriPath = Uri.parse(f.getPath());

                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_TEXT, "Text");
                    shareIntent.putExtra(Intent.EXTRA_STREAM, uriPath);
                    shareIntent.setType("video/*");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    startActivity(Intent.createChooser(shareIntent, "send"));

                }
            }
    );
}

A:

Try This :
public void shareVideo(final String title, String path) {

MediaScannerConnection.scanFile(getActivity(), new String[] { path },

            null, new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Intent shareIntent = new Intent(
                            android.content.Intent.ACTION_SEND);
                    shareIntent.setType("video/*");
                    shareIntent.putExtra(
                            android.content.Intent.EXTRA_SUBJECT, title);
                    shareIntent.putExtra(
                            android.content.Intent.EXTRA_TITLE, title);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                    shareIntent
                            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    context.startActivity(Intent.createChooser(shareIntent,
                            getString(R.string.str_share_this_video)));

                }
            });
}


Q:

How to make sidebar menu in iOS application?

I want to create side bar menu in iOS application like android using xib not by storyboard?
please help me on above.
Thanks

A:

You can do a slide menu by using MFSideMenu
 from git hub.
There are provide you a simple demo application also. Try to use this


Q:

ImageIO wont import BufferedImage correctly

Error thrown--
Exception in thread "Thread-3" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
Code--
try {
        playerImage = ImageIO.read(Player.class
                .getResourceAsStream("/toon.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }

File path--
H:\workspace\Isaac\resources\toon.png
Ive researched this a bit but none of the solutions have really worked for me. any ideas?

A:

If Isaac is your project folder, then the way your are reading should work. Please check whether the directory resources is a source folder (in eclipse it should have an icon of a folder with an overlay of a java package), if not then right click on it and got to Build path and choose Use as Source Folder.
Your directory structure should look something like this:
before compiling
H:\workspace\Isaac
├───resources
│       toon.png
│
└───src
        Player.java

after compiling
H:\workspace\Isaac
├───bin
│       Player.class
│       toon.png
│
├───resources
│       toon.png
│
└───src
        Player.java

getResourceAsStream looks for the image in bin and not in the one in resources


Q:

GLES20 How to get global position of vertex after translating and rotating it

I have a vertex (Which i will not be showing/rendering in the scene)
float vertex[] = {
            1.0f, 1.0f, 1.0f,
};

And i have a mesh, which i have translated and rotated using:
Matrix.translateM(World.mModelMatrix, tmOffset, globalPositionX, globalPositionY, globalPositionZ);

Matrix.rotateM(World.mModelMatrix, rmOffset, globalRotationZ, 0, 0, 1);
Matrix.rotateM(World.mModelMatrix, rmOffset, globalRotationY, 0, 1, 0);
Matrix.rotateM(World.mModelMatrix, rmOffset, globalRotationX, 1, 0, 0);

How can apply those translations and rotations to the vertex, and get its global position (x,y,z) after?

A:

Use the Matrix.multiplyMV method:
float vertex[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float result[] = { 0.0f, 0.0f, 0.0f, 0.0f };

Matrix.multiplyMV(result, 0, matrix, 0, vertex, 0);

Note, that you will have to add a homogeneous coordinate to your vector to make it work.


Q:

Why is there no Picture in my Panel/Window?

whats wrong with my code? I just want to have a Picture in my Window...
//class ImagePanel:

public class ImagePanel extends JPanel {

    private static final long serialVersionUID = -7664761101121497912L;

    public Image i;

    public ImagePanel(Image i) {
        this.i = i;
    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponent(g);
        g.drawImage(this.i, 0, 0, null);
    }
}

//class Main

public class Main extends JFrame {

    public static void main(String[] args) {

    JFrame frame = new JFrame();
        frame.setSize(1024, 768);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ImagePanel panel = null;

        try {
            panel = new ImagePanel(ImageIO.read(new File("D:/test.JPG")));
        } catch (IOException e) {
            e.printStackTrace();
        }

        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
}

There is just a Window without a picture :(
Whats the problem? And is there an easy way to set size of the window == picture size?
Thank you!

A:

You must override paintComponent(Graphics g) instead of paintComponents(Graphics g).

A:

The best solution is to use a JLabel. Don't reinvent wheel. There is no need for you to do custom painting.
But if you do custom painting then you need to override the getPreferredSize() method to be the size of the image so the layout manager can do their job.

A:

please read this tutorials about Icon in Swing and your Image would by placed to the JLabel but with same way/funcioanlities as to the JPanel


Q:

pandas: how do I select first row in each GROUP BY group?

Basically the same as Select first row in each GROUP BY group? only in pandas.
df = pd.DataFrame({'A' : ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
                'B' : ['3', '1', '2', '4','2', '4', '1', '3'],
                    })

Sorting looks promising:
df.sort('B')

     A  B
1  foo  1
6  bar  1
2  foo  2
4  bar  2
0  foo  3
7  bar  3
3  foo  4
5  bar  4

But then first won't give the desired result...
    df.groupby('A').first()
     B
A
bar  2
foo  3

A:

Generally if you want your data sorted in a groupby but it's not one of the columns which are going to be grouped on then it's better to sort the df prior to performing groupby:
In [5]:
df.sort_values('B').groupby('A').first()

Out[5]:
     B
A
bar  1
foo  1

A:

The pandas groupby function could be used for what you want, but it's really meant for aggregation. This is a simple 'take the first' operation.
What you actually want is the pandas drop_duplicates function, which by default will return the first row. What you usually would consider the groupby key, you should pass as the subset= variable
df.drop_duplicates(subset='A')

Should do what you want.
Also, df.sort('A') does not sort the DataFrame df, it returns a copy which is sorted. If you want to sort it, you have to add the inplace=True parameter.
df.sort('A', inplace=True)

A:

Here's an alternative approach using groupby().rank():
df[ df.groupby('A')['B'].rank() == 1 ]

     A  B
1  foo  1
6  bar  1

This gives you the same answer as @EdChum's for the OP's sample dataframe, but could give a different answer if you have any ties during the sort, for example, with data like this:
df = pd.DataFrame({'A': ['foo', 'foo', 'bar', 'bar'],
                   'B': ['2', '1', '1', '1'] })

In this case you have some options using the optional method argument, depending on how you wish to handle sorting ties:
df[ df.groupby('A')['B'].rank(method='average') == 1 ]   # the default
df[ df.groupby('A')['B'].rank(method='min')     == 1 ]
df[ df.groupby('A')['B'].rank(method='first')   == 1 ]   # doesn't work, not sure why


Q:

Cannot find file setuptools-27.2.0-py3.5.egg

This question is for Python 3.5.2, using Anaconda 4.3.0 on Windows 10 (64-bit)
When I try to install packages with pip I get this error:
Command "python setup.py egg_info" failed with error code 1 in C:\Users\HMGSYS\AppData\Local\Temp\pip-build-xit1wtvr\shapely\

Based on other SO answers, I tried to  upgrade setuptools:
pip install --upgrade setuptools

But I get this error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\HMGSYS\\Anaconda3\\lib\\site-packages\\setuptools-27.2.0-py3.5.egg'

However, if I try to install setuptools:
python -m pip install -U pip setuptools

It tells me that all packages are up to date, including setuptools:
Requirement already up-to-date: setuptools in c:\users\hmgsys\anaconda3\lib\site-packages

Also, when I look in lib\site-packages, I see a folder for setuptools and another for setuptools-34.3.2.dist-info.
What should I try next? Why is setuptools looking for version 27.2.0 and ignoring the more recent versions?
EDIT:
I downloaded the specific version of setuptools that the system was looking for and the error from 'pip install --upgrade setuptools' disappeared. However, I'm still getting the first 'egg_info' error. I've also installed ez_setup, which had no effect.

A:

Try to use conda to update setuptools:
conda update setuptools

A:

You may try to downgrade your python into python 3.5.0.
conda install python=3.5.0

( I had encountered the same error with python 3.5.3, and it installed without error after downgraded to 3.5.0.)


Q:

Snort rules question

I just noticed my snort rules fired today on this, on a brand new ossim server I was testing.
"shellcode x86 inc ebx noo" on with the source ip from Canada. Why might a brand new server, behind a firewall and a NAT router, see an alert like this coming from an external IP?

A:

For sake of argument, let's assume you're referring to the rule mentioned by Mark in his comment. This works out well since when doing a full text search of your quoted text across all VRT and ET rules, it's the only one I found as well. It is sid 1390, found in the file shellcode,rules for those keeping track at home.
The full rule text is:
alert ip $EXTERNAL_NET any -> $HOME_NET any (msg:"SHELLCODE x86 inc ebx NOOP"; content:"CCCCCCCCCCCCCCCCCCCCCCCC"; classtype:shellcode-detect; sid:1390; rev:9;)

Thankfully, this is a nice and simple rule. For the same of analysis let's also assume that this device is on your border and the IP variables have been properly configured.
So, this rule gets checked against every IP packet that comes into your organization. Already it seems pretty noisy. It looks in the payload section of the packet for the a string containing 25 consecutive 'C' characters. The reason for this is that this character maps to the inc ebx instruction for the x86 architecture (as implied by the name of the rule). In the x86 architecture this instruction is functionally equivalent to NOP, and as such can be used as part of a NOOP slide, but is slightly less obvious.
This specific rule, and many of the shellcode rules in fact, are well known generators of false positives since they can often be generated by downloading binary files. The traditional tuning advice is to disable these rules on web ports.
So, depending on your risk threshold, you can either

Disable the rules entirely
Modify the rule to ignore packets on "web ports"

Disabling the rules is easy, and something you should be well acquainted with if you're attempting to make reasonable use of an IDS at all. Modification can be a little trickier.
Tuning By Port Filtering
Depending on your version of Snort, you should already have two variables set in your snort.conf that will be useful. One is HTTP_PORTS and the other is SHELLCODE_PORTS. By default, they're set to rather basic values.
# Ports you run web servers on
portvar HTTP_PORTS [80,8080]

# Ports you want to look for SHELLCODE on.
portvar SHELLCODE_PORTS !80

What I would recommend is changing HTTP_PORTS to whatever you actually use in your environment, and then setting SHELLCODE_PORTS to the inverse of that, so something like:
# Ports you run web servers on
portvar HTTP_PORTS [80,8080]

# Ports you want to look for SHELLCODE on.
portvar SHELLCODE_PORTS !$HTTP_PORTS

Then you can modify the Snort signature to use the appropriate port variable.
alert ip $EXTERNAL_NET $SHELLCODE_PORTS -> $HOME_NET any (msg:"SHELLCODE x86 inc ebx NOOP"; content:"CCCCCCCCCCCCCCCCCCCCCCCC"; classtype:shellcode-detect; sid:1390; rev:9;)

So now this will exclude any data coming from an external web server, so say downloading an executable from a vendor website. It is best to keep in mind that since this rule is not stateful, a malicious attacker could craft their exploit in such a way as to avoid the rule.
Tuning By State Tracking
Alternatively, we could tighten up the rule by forcing it to be stateful instead. Let's remove the port restriction and tighten up the rule to only to outside initiated communication by adding the flow keyword, turning that rule into:
alert ip $EXTERNAL_NET any -> $HOME_NET any (msg:"SHELLCODE x86 inc ebx NOOP"; flow:to_server,established; content:"CCCCCCCCCCCCCCCCCCCCCCCC"; classtype:shellcode-detect; sid:1390; rev:9;)

So now the rule will look for at least 25 consecutive 'C' characters on any outside initiated communication. So while we'll now see the cases where the malicious user spoofs their source ports, in an effort to bypass firewall restrictions, we will miss cases where the exploit code is downloaded from a local host.
Analysis Paralysis
In both cases, there are obvious ways to bypass the detection routine, so which direction you choose depends entirely on your risk profile and your threshold for acceptance.


Q:

how to access xml-described resources from non-context class far from app's root?

Need to access resources from non-context class without passing context through deep call stack.
I've already read all answers on this topic, but this class is not created from Activity, and it's really far from it. The way to send context through all calls is not a variant, because it'll require to send it through a number of classes and methods which does not any need to know something about context.
Do I have any chance to access resources without passing context through a really deep call stack? Any static methods needed? It would be really amazing if it's impossible to get application resources from any place of application with an easy and natural way.

A:

You can extends Android's Application class and implement it as a singleton which will make it globally available.
public class SampleApplication extends Application {
    private static SampleApplication INSTANCE;

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
    }

    public static SampleApplication instance() {
        return INSTANCE;
    }
}

If you do this it requires some work in the AndroidManifest.xml.  This will tell the framework to load your Application instead of the default application.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.yourdomain"
  android:versionCode="1"
  android:versionName="1.0">

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".SampleApplication">
    <activity android:name=".SampleActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

This will easily give you a mechanism to grab your Application context whenever necessary.  You can even implement a static method that returns your resources, but the following should work.
SampleApplication.instance().getResources();

Don't know if you have tried this, but it should work.   I didn't test this code, so it may take some tweaking, but you should get the idea.


Q:

What are the main arguments in favor of the Anātman view over the Ātman view?

The main difference (I know) between Buddhism and Hinduism is that the first defends Anātman theory whereas the second defends Ātman theory.
What are the main arguments in favor of the Anātman view over the Ātman view?

A:

The idea of Atman tends to be defined as having three characteristics:

permanent
controllable
satisfactory

When it is any of those things, it can be seen as Atman.
In SN 22.59 the Buddha explains that neither form, feeling, determination and consciousness have those characteristics:

Bhikkhus, form is not-self. Were form self, then this form would not lead to affliction, and one could have it of form: 'Let my form be thus, let my form be not thus.' And since form is not-self, so it leads to affliction, and none can have it of form: 'Let my form be thus, let my form be not thus."
"Bhikkhus, how do you conceive it: is form permanent or impermanent?"
  — "Impermanent, venerable Sir." — "Now is what is impermanent painful
  or pleasant?" — "Painful, venerable Sir." — "Now is what is
  impermanent, what is painful since subject to change, fit to be
  regarded thus: 'This is mine, this is I, this is my self'"? — "No,
  venerable sir."'

note: I've translated it as: "Unsatisfactory vs satisfactory"; the quoted text translated it as "Painful vs Pleasant" and I've also seen "stress-full vs stress-less." I hope the point is clear.
It's also something that becomes apparent after meditating and following the path, when the Buddha asks Annanda, what the 10 perceptions gained by mindfulness of in - and out-breathing are, he answers pertaining to non-self:

"And what is the perception of not-self? There is the case where a monk — having gone to the wilderness, to the shade of a tree, or to an empty building — reflects thus: 'The eye is not-self, forms are not-self; the ear is not-self, sounds are not-self; the nose is not-self, aromas are not-self; the tongue is not-self, flavors are not-self; the body is not-self, tactile sensations are not-self; the intellect is not-self, ideas are not-self.' Thus he remains focused on not-selfness with regard to the six inner & outer sense media. This is called the perception of not-self.

On a more secular note, Sam Harris, who has been inspired by Buddhism and tried meditation, talks about this realisation as well:

Occasionally, a breakthrough did occur: In a moment of seeing, for instance, there would be pure seeing, and consciousness would appear momentarily free of any feeling to which the notion of a “self” could be attached. But then the experience would fade, and I couldn’t get back there at will. There was nothing to do but return to meditating dualistically on contents of consciousness, with self-transcendence as a distant goal.

I believe that those are the main argument in favour of the Anatman view:
1) understanding that experience is changing , uncontrollable and unsatisfactory
2) Seeing in meditation that when one is mindful, no sense of self arises.
thus concluding that there is nothing that one can say about:
"This is me, This is mine, I am this."


Q:

Angular - Dynamically loading an image

I've searched all over StackOverflow but I haven't been able to find a solution to my problem.

F.Y.I I'm using ASP.net Core 2.0's default angular project
I'm currently building an Angular application where I'm trying to load in a customer's logo based on a config found elsewhere.
I'm trying to load this file into my home.component.html
I created a "CustomerService" which has a function getLogo() which in itself returns the customer's logo's path.
My folder structure is as follows:
FOLDER STRUCTURE IMAGE
The assets folder holds the images, and the HTML found below is found in home.component.html
I know that "../../" isn't the way to go, so my first question is how I'd be able to fix that.
I've created the following HTML structure:

And the CustomerService's getLogo function returns the following:
getLogo() {
    return "../../assets/timeblockr-logo.png";
}

** EDIT: FOUND THE SOLUTION!!! **
Turns out I had to use:
getLogo(): string{
    return require("../assets/timeblockr-logo.png");
}

Special thanks to @Niladri for the solution to this issue!

A:

Your image source should be without ../../. The image paths are relative in the output folder. Just change to this:

And your function should be:
getLogo(): string {
    return "assets/timeblockr-logo.png";
}

As per your comments, you need to change your "assets" entry in .angular-cli.json to this:
"assets": [
    "assets",
    "favicon.ico",
    {
        "glob": "**/*",
        "input": "./assets/images/",
        "output": "./assets/images/",
        "allowOutsideOutDir": false
    }
],

A:

Webpack uses url-loader to load images from your angular project that comes with extension .png,.jpg etc . Take a look at the below code from the url-loader repo in github https://github.com/webpack-contrib/url-loader
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  }
}

it looks for image files with the above extensions. But we need to use require statement to the actual image path for the Webpack to understand the path of the image so that it can pick them up. This is required in .ts / typescript files while using the path of the image as a variable or returning the path value from a method . The first image tag
 was working because Webpack uses html-loader for .html files, which automatically replaces src attribute values on image tags with the bundled image URL.
So your getLogo() method should be like below
getLogo():string {
    return require("../assets/timeblockr-logo.png");
}


Q:

Write/Update data SQLite database in iOS

I have an application made in air in Flash Builder for iOS plataform
I've compiled a version and installed it on my iPhone, the app talks to the database but it does not write/update in database. What can be the problem? Permission of the device or the path of the database?
thanks for now.
code:
private var dbFile : File;
private var dbPath : String = "SAG.sqlite"; //name of database

 private function setaAPP():void{
    if(app == 'ANDROID'){
        dbFile = new File('/mnt/sdcard/SAG/' + dbPath); // to ANDROID
    }else if(app == 'DESKTOP'){
        //app == DESKTOP
        dbFile = File.applicationDirectory.resolvePath(dbPath); // to DESKTOP
    }else if(app == 'DEBUG'){
        //only to debug in Android
        dbFile = File.applicationDirectory.resolvePath(dbPath); // to DEBUG in device
    }else if(app == 'IOS'){
        //app == IOS
        dbFile = File.applicationStorageDirectory.resolvePath(dbPath); // to iOS
    }
}

A:

If the structure is the same as your ANDROID or DEBUG projects (i.e. you included the db in the root application directory when packaging), you should be able to use File.applicationDirectory.resolvePath(dbPath) just as you did in those cases.
EDIT:
The app directory is not writable, so if you want to write to the database, you will need to move the file to the Documents directory, which you can access with var docs:File = new File(File.userDirectory.nativePath + '/Documents');


Q:

Fix returned number

I want to know how to clamp/range/fix (I don't know how to call it) a number.
For exmaple, I want to always fix a number into multiple of 10 so it should works like this:
If you get number: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 must be fixed at 0.
If you get number: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 must be fixed at 10.
If you get number: 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 must be fixed at 20.
And so on.
I know that it must be easy but I can't find out by myself, thank you in advise.

A:

Divide by the desired precision (e.g. 10) -- integer division always floors values, i.e. returns the smallest integer for the division -- and then multiply again with the same precision.
public static int FloorToPrecision(int value, int precision) {
  return (value / precision) * precision;
}

e.g. Console.WriteLine(FloorToPrecision(17, 10)); prints out 10.


Q:

gvimdiff mergetool for msysgit

I'm trying to use gvimdiff as a mergetool for git on Windows. Previously I've used vimdiff in console mode, but know feel like I'm not happy with limiting view Windows console size, so I'm trying to switch to gvimdiff which have more flexible approach to setting window size.
But trying to call git mergetool now I'm receiving error which is not clear for me:
The merge tool gvimdiff is not available as 'gvim'
How this could be resolved?
gvim for Windows is install and accessible via command line. The same is true for gvimdiff command.
I'm trying to find the place where this error is raised in git scripts, but currently with no luck.

A:

If you start a Git console, are you sure the commands are accessible? I'm suspecting that it is not on the PATH of your Git console, only the Windows PATH (which is not entirely included).

A:

Combining your answers, these are my settings
.gitconfig
[alias]
    d = difftool
[diff]
    renames = copy
    tool = gvimdiff
[difftool "gvimdiff"]
    cmd = "gvim -d" "$LOCAL" "$REMOTE"
[difftool]
    prompt = false

And added file gvim accessible in %PATH% with content:
"C:\Program Files (x86)\Vim\vim73\gvim.exe" "$@"

Git difftool in Windows to see list of all changed files in addition to file diffs (a la Kaleidoscope)?


Q:

Overriding equals for Clojure records

I have a record where one field is of type byte[]. Since Clojure equality is not defined for arrays, we have:
(defrecord Record [^bytes field])
(def rec1 (->Record (byte-array (map byte "abc"))))
(def rec2 (->Record (byte-array (map byte "abc"))))

(= rec1 rec2)
; => false

This is, of course, not acceptable.
Now, we do have java.util.Arrays.equals which defines proper equality for arrays. Since = works so well for other Clojure objects, I don't want to use interop every time I compare my Record type, types including that type etc.
Is it possible to override the equals function for a record to handle arrays as well?

I have tried the following:
(defrecord Record [^bytes field])
  Object
    (equals [this other] (Arrays/equals this other)))

But I get an error, "Duplicate method name&signature".

A:

The reason arrays don't compare as equal, in clojure, is because they can change at any time, and objects which are equal should stay equal. Imagine a map like {rec1 1}. If your two objects compare as equal, I should be able to look up rec2 in it and find the answer 1. But if someone does (aset (:field rec2) 1 3), suddenly rec2 has changed, and is no longer equal to rec1!. This is just not something that should happen, so clojure says they're not equal.
This is similar to the equality semantics for atoms and other mutable containers: just because two mutable containers (atoms, or arrays) have equal contents now doesn't mean the containers are themselves equal. That tenuous equality could change at any time, when someone modifies one of them. Similarly, your two arrays may become unequal at any time; this means that, really, they were never equal at all.

A:

Arrays are mutable and thus not values. Clojure equality depends on the immutability of component values in composite things like records. Arrays are dirty mutable things - as a general starting point, just don't do this.
If you really really want to use arrays and you need custom semantics, use a deftype and define your own equals method. But you need to be aware you are then "off the map" as far as Clojure is considered - this is not "normal" Clojure.


Q:

What does "express grant of patent rights from contributors to users" mean?

I'm trying to choose which open source license I should use in my app, and in the description for one of the licenses, it says the license provides an "express grant of patent rights from contributors to users".
Would someone be able to explain to me what this means?
The license that this is from is the Apache License 2.0.

A:

There are two, completely independent, forms of intellectual property rights that can be used to protect software against unwanted copying/modification:

Copyright
Patents

Copyright protects the "expression of an idea" and applies to the source code that gets written. Copyright protection is granted automatically at the moment that the code is written. Copyright protection means that only the author is allowed to make copies of or changes in the code, unless the author explicitly gives this right also to others by means of a copyright license.
Patents protect inventions and need to be explicitly requested. When a patent has been granted to you, you have the exclusive right to make use of that invention or to give a patent license to others.
Patents can be broader that copyrights, because if someone else makes the same invention that you have a patent on, then you can force them to stop using the invention or to buy a patent license from you. With copyright, however, it is possible that multiple people independently write very similar code and each has their own copyright protection.
The Apache License 2.0 is primarily a copyright license that gives people the right to use the code written by the person granting the license.
However, contrary to many other copyright licenses, the Apache license also takes patents into consideration and includes a license to use the relevant patents  that the person holds who released the code under the Apache license. That is what the phrase means that you quoted.


Q:

Conditional model validations dependent on controller

I have a user model, that stores, amongst other things, the users address. When creating an account (user_sessions controller) I only wish to validate the presence of their name, the address is optional.
When they upgrade their account (upgrade controller) i want to validate that that their full address is entered.
Is there an elegant way of having a conditional validation based on the controller?

A:

Have you tried creating a new model that inherits from the old one.  So you could have:
class User < ActiveRecord::Base
  attr_accessible :name, :address
  validates_presence_of :name
end

class UpgradedUser < User
  validates_precense_of :address
end

Since it inherits from the User class, the UpgradedUser class has validations for both address and name. And this solution would still be only using one database table. Because they are still one table, you'd have to add a :account_status column or something to determine whether an account has been upgraded or not.
In your upgraded_users controller you would have a standard update method:
class upgraded_users_controller

  def update
    @upgraded_user = UpgradedUser.find params[:id]
    respond_to do |format|
      if @upgraded_user.update_attributes params[:user]
        format.html { redirect_to @upgraded_user }
      end
    end

This method will access the same User table just like the users_controller  would, but its simply doing so through the UpgradedUser model instead, and therefore would check the validators on save for both name and address presence.


Q:

Install a custom module in magento 2 stable

Downloaded the M2 from magentocommerce with sample data. I have custom module which i developed locally on M2-rc 2.0. My question is that now how can i install module and where i place the custom module as there is no code folder in app directory and all the magento modules are in vendor folder. Also i dont want to create a repo for my module. Also i want to put my module in vendor folder

A:

Just create the app/code/YourNameSpace/ModuleName folder yourself. Make sure, that your composer.json in the project root contains the line
    "files": [
        "app/etc/NonComposerComponentRegistration.php"
    ]

in the autoload section (see https://github.com/magento/magento2-community-edition/blob/master/composer.json#L42) which is responsible for loading modules which are not installed via composer.


Q:

Rearranging the content of a cell in Cognos 10

I've got birthdays as a varchar formatted as dd-mm-yyyy and I'm trying to build a filter that shows only the birthdates of the last 7 days.
Now normally I'd convert that field to a date field, but since it contains dummy values this isn't an option.
So I want to change the output to YYYYMMDD so I can use the value in a => filter.
How can I do this?

A:

If you want the result in string format:
substring([Date],7) || substring([Date],4,2) || substring([Date],1,2)

..or in integer format:
cast(substring([Date],7),integer) * 10000 + cast(substring([Date],4,2),integer) * 100 + cast(substring([Date],1,2),integer)


Q:

Clang++: weird error message

I try to compile a simple class, but I always get the same error:
≥ clang++ LIF_network.cpp -std=c++11
LIF_network.cpp:3:1: error: expected unqualified-id
public LIF_network::LIF_network(){
^
1 error generated.

.hpp:
#ifndef LIF_NETWORK_HPP
#define LIF_NETWORK_HPP
#include <vector>
#include <cstdlib>
#include "LIF_neuron.hpp"
#include "currentTimer.hpp"

#define MAX_TIME 15

class LIF_network{
    public:
        LIF_network();
};

#endif //LIF_NETWORK_HPP

.cpp:
#include "LIF_network.hpp"

public LIF_network::LIF_network(){
    mNumNeurons = 0;
    mNeurons = std::vector<std::vector<LIF_neuron>>();
    mOutput = std::vector<double>();
    mCurrentTimer = CurrentTimer(MAX_TIME, mNumNeurons);
}

The error message does not really help me. Can you spot my mistake? Thanks a lot!

A:

The access specifier (public: private: and protected:) only works within a class definition and not outside of it.  It looks like you are trying to port Java code.


Q:

Python read multiline post data

I'm using BaseHTTPRequestHandler to implement my httpserver. How do a I read a multiline post data in my do_PUT/do_POST?
Edit: I'm trying to implement a standalone script which sevices some custom requests, something like listener on a server, which consolidates/archives/extracts from various log files, I don't want implement something which requires a webserver, I don't have much experience in python, I would be grateful if someone could point any better solution.
Edit2: I can't use any external libraries/modules, I have to make do with plain vanilla python 2.4/java1.5/perl5.8.8, restrictive policies, my hands are tied

A:

Getting the request body is as simple as reading from self.rfile, but you'll have to know how much to read if the client is using Connection: keep-alive. Something like this will work if the client specifies the Content-Length header...
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class RequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        print post_data

server = HTTPServer(('', 8000), RequestHandler)
server.serve_forever()

...although it gets more complicated if the client sends data using chunked transfer encoding.


Q:

ROW_FORMAT - COMPRESSED vs COMPACT vs DYNAMIC

In MySQL InnoDB, what is the difference between COMPRESSED, COMPACT and DYNAMIC for ROW_FORMAT?
What are the benefits between each other?

A:

COMPACT is format supported by Antilope. It stores first 768 bytes of BLOB in case its value doesn't fit in page.
DYNAMIC is almost the same as COMPACT except only 20 bytes for each BLOB field is used. Benefits - more BLOB fields are possible in a record.
COMPRESSED is used for compressed tables. Hence its benefits.


Q:

Why center of RenderTransformOrigin is 0.5,0.5?

When I see samples codes where RenderTransformOrigin is used, they would have 0.5, 0.5 as the center instead of 0,0.
I tried both and I don't see any differences. Is there a reason why 0.5,0.5 use used as center instead of 0,0?

A:

According to MSDN, the values of RenderTransformOrigin are

values between 0 and 1 [and] are
  interpreted as a factor for the range
  of the current element in each x,y
  axis. For example, (0.5,0.5) will
  cause the render transform to be
  centered on the element, or (1,1)
  would place the render transform at
  the bottom right corner of the
  element.

In other words, 0.5,0.5 places the transform origin in the center of the element, and 0,0 places it at the top left corner. If you apply a rotation transform, the result of the former is a rotation about the element's center, and in the the latter case, the rotation is about its top left corner.


Q:

Find intersection of multiple DSM's using Python and GDAL

I am quite a beginner in respect to GIS and hopefully someone can help me out with the problem I have.
I have multiple digital surface models [DSMs] of the same area with all necessary geo-information (6 in total). However they are not exactly the same as they have been acquired on different days (row and cols of the raster are not identical). I already managed to align the DSMs, however now I need to find the intersecting area that is part of all six DSMs because I want to do some processing with this (which I indent to do in python).
I found the following post:
http://sciience.tumblr.com/post/101722591382/finding-the-georeferenced-intersection-between-two
This methods works fine for two DSMs, however the extension to more areas is not straightforward (at least not for me at the moment).
I guess this is a rather standard beginner problem, however I only ever found answers regarding exactly two areas.

A:

Reclassify the six surface models so that all the elevation data values equal one and the non-data pixels equal 0.
Multiply the 6 reclassified outputs together.  The resulting  raster will contain values of one or zero.  Anyplace the output has a value of one will be that place where all six surface share data values.
Here is a GDAL link to get you started.
Here is a link to the reclassify tool in ArcGIS.
And here is a QGIS solution.
If you are interested in a Python solution you should still work it out in GIS first.  Consider learning Model Builder in ArcGIS then export your model to Python once you have it working.


Q:

Why was this "unclear" flag declined?

This question is unclear, so I flagged it as such. As far as I understand, he wants to detect players in a radius, but somehow doesn't like the radius selector or something like that. It's unclear if he wants to use something else to solve his problem (in that case he should describe the problem) or if he wants help with the selector he mentioned. The answers are also just guessing what he means.
The flag was declined without any comment. Why?

A:

The reason your flag was declined without comment, is because the post was found to have three "Leave Open" votes. See review (I'm not sure if you can look at the review link or not).
From this Meta SE post:

If your flag was a recommend closure flag, if it receives three "Leave Open" responses in the Close Votes queue without a single close vote, it will be marked declined.

This is why there is no reason behind the decline message, since it was an "automated" decline. That explains the "why it was declined," by why was it declined?  Well, the community appears to have disagreed with you that it should have been closed.  I've noticed that you seem to specialize in Minecraft and Minecraft Command questions.  You may be more educated on those types of questions where other members of the community are not.  For me, an unclear post is one that can't be comprehended.  Your reasoning for this example seems a bit more technical, and that may be why others have disagreed with you.


Q:

Basic rules to calculate the equivalent resistance of a resistor circuit

I have a certain circuit only containing resistors of different values. There is one 'input' and one 'output' for the current. How do I calculate the equivalent resistance of the circuit? Are there any basic rules to follow?

A:

If determining replacement value is the only goal then I can think of the following steps:
1) Analyse the circuit into the smallest solvable sub-circuits possible (series and parallel);
2) Calculate series resistors \$R_S = R_1 + R_2\$;

simulate this circuit – Schematic created using CircuitLab
3) Calculate parallel resistors: \$R_P = \frac{1}{\frac{1}{R_3}+\frac{1}{R_4}}\$

simulate this circuit
4) Apply wye-delta (Y-Δ) transform or reverse
5) Repeat until solved or run the circuit through a circuit simulator like SPICE.
Wye-delta (Y-Δ) transform

simulate this circuit
Y→Δ
$$R_{ab} = R_{an} + R_{bn} + \frac{ R_{an} \cdot R_{bn} }{ R_{cn} }$$
$$R_{ac} = R_{an} + R_{cn} + \frac{ R_{an} \cdot R_{cn} }{ R_{an} }$$
$$R_{bc} = R_{bn} + R_{cn} + \frac{ R_{bn} \cdot R_{cn} }{ R_{an} }$$
Δ→Y
$$R_{an} = \frac{ R_{ab} \cdot R_{ac} }{ R_{ab} + R_{ac} + R_{bc} }$$
$$R_{bn} = \frac{ R_{ab} \cdot R_{bc} }{ R_{ab} + R_{ac} + R_{bc} }$$
$$R_{cn} = \frac{ R_{ac} \cdot R_{bc} }{ R_{ab} + R_{ac} + R_{bc} }$$


Q:

How can i show that $\det(A)=\det(A^\intercal)$?

For all $n$-dimension matrix, how can i show that $\det(A)=\det(A^\intercal)$ by using induction? ($A^\intercal$ is a transpose of $A$)

A:

If $A$ is not invertible, then $A^T$ is also not invertible. So if $det(A) = 0$ then $det(A^T) = 0$ and vice versa. If $A$ is invertible, then $A = E_1\cdot E_2\cdot...E_n$ and $A^T = E_n^T\cdot E_{n-1}^T\cdot ...E_1^T$ with each $E_i$ is an elementary matrix which is obtained by a single row operation on $I_n$, and there are $3$ of types of them. For each of the $3$ types we can verify that $det(E_i) = det(E_i^T)$. So $det(A) = det(E_1)\cdot \det(E_2)\cdot...det(E_n) = det(E_n^T)\cdot det(E_{n-1}^T)\cdot...det(E_1^T) = det(E_n^T\cdot E_{n-1}^T\cdot...E_1^T) = det(A^T)$.


Q:

MySQL compare DateTime

I have this data table in database MySQL.
+---------------------+---------------------+--------+----+
| Start___Date        | End___Date          | Coding | ID |
+---------------------+---------------------+--------+----+
| 2014-12-16 18:08:51 | 2014-12-16 20:00:16 | 7605   | 1  |
| 2014-12-16 22:01:39 | 2014-12-16 23:36:36 | 9905   | 2  |
| 2014-12-16 22:45:00 | 2014-12-16 23:36:36 | 9905   | 3  |
| 2014-12-16 23:18:32 | 2014-12-16 23:19:04 | 9905   | 4  |
+---------------------+---------------------+--------+----+

In this table I have three identical codings: 9905.
I need with one query delete all rows when the same coding is repeated within an hour of the time of start date.
In this case I need canceling the row number three.
+---------------------+---------------------+--------+----+
| Start___Date        | End___Date          | Coding | ID |
+---------------------+---------------------+--------+----+
| 2014-12-16 18:08:51 | 2014-12-16 20:00:16 | 7605   | 1  |
| 2014-12-16 22:01:39 | 2014-12-16 23:36:36 | 9905   | 2  |
| 2014-12-16 23:18:32 | 2014-12-16 23:19:04 | 9905   | 4  |
+---------------------+---------------------+--------+----+

Because the same coding 9905 is recorded in the table twice within an hour compared to the start time (22:01) and save the record number 4 with coding 9905 because the start time (23:18) is greater compared to the start time (22:01) with the same coding.
Can you help me?
Thank you in advance.
EDIT #1
I have tried this query JOIN but the output is wrong:
mysql> SELECT
    CB.Start___Date,
    CB.End___Date,
    CB.Coding
FROM
    doTable AS CB
JOIN doTable AS CD ON (CB.Coding = CD.Coding)
WHERE
    TIME_TO_SEC(
        TIMEDIFF(
            CB.Start___Date,
            CD.Start___Date
        )
    ) / 60 > 60
GROUP BY
    CB.Coding;
+---------------------+---------------------+--------+
| Start___Date        | End___Date          | Coding |
+---------------------+---------------------+--------+
| 2014-12-16 23:18:32 | 2014-12-16 23:19:04 |   9905 |
+---------------------+---------------------+--------+
1 row in set

A:

This is my solution for your problem, happy coding!
mysql> DROP TABLE
IF EXISTS `doTable1`;

CREATE TABLE `doTable1` (
    `coding` INT (10) DEFAULT NULL,
    `Start___Date` datetime DEFAULT NULL,
    `id` INT (10) NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (`id`)
) ENGINE = MyISAM;

INSERT INTO `doTable1` (coding, Start___Date)(
    SELECT
        coding,
        MIN(Start___Date)
    FROM
        doTable
    GROUP BY
        coding
);

SELECT
    a.*, b.*, TIMEDIFF(
        a.Start___Date,
        b.Start___Date
    ) AS diff
FROM
    doTable a
JOIN `doTable1` b ON a.coding = b.coding
WHERE
    (
        TIMEDIFF(
            a.Start___Date,
            b.Start___Date
        ) = '00:00:00'
        OR TIMEDIFF(
            a.Start___Date,
            b.Start___Date
        ) >= '01:01:01'
    );
Query OK, 0 rows affected

Query OK, 0 rows affected

Query OK, 2 rows affected
Records: 2  Duplicates: 0  Warnings: 0

+--------+---------------------+---------------------+----+--------+---------------------+----+----------+
| Coding | End___Date          | Start___Date        | ID | coding | Start___Date        | id | diff     |
+--------+---------------------+---------------------+----+--------+---------------------+----+----------+
|   7605 | 2014-12-16 20:00:16 | 2014-12-16 18:08:51 |  1 |   7605 | 2014-12-16 18:08:51 |  1 | 00:00:00 |
|   9905 | 2014-12-16 23:36:36 | 2014-12-16 22:01:39 |  2 |   9905 | 2014-12-16 22:01:39 |  2 | 00:00:00 |
|   9905 | 2014-12-16 23:19:04 | 2014-12-16 23:18:32 |  4 |   9905 | 2014-12-16 22:01:39 |  2 | 01:16:53 |
+--------+---------------------+---------------------+----+--------+---------------------+----+----------+
3 rows in set


Q:

How to change innerHTML of CRM form in MS Dynamics CRM 2015 form?

I have a form in MS CRM 2015 Online. it was updated to 2015 from 2013 recently.
I have a requirement such that i have to show multi select check boxes on CRM form. In CRM 2013 i have an option set with some options, with those options i am forming HTML with check boxes using script and am changing HTML.
In CRM 2013 i had changed form UI using document.getelemntByID("#element").innerHTML.
but in CRM 2015 javascript is not working. i am unable to get element using doument.getelementbyID.
I am unable to find alternative for this requirement. can any one of suggest me on this?

A:

Those JavaScript commands are not supported by CRM and shouldn't be used.
To do this I would suggest building a web resource and embedding on the page. Then you have full control.


Q:

cakephp match against order by doesn't work

I am trying to order my pagination result. But it doesn't work.
$this->paginate = array(
                'limit' => 15,
                'fields' => array('*', "MATCH (headline, author, short_headline, subline, teaser, text) AGAINST ('$var') AS score"),
                'conditions' =>  "MATCH(headline, author, short_headline, subline, teaser, text) AGAINST('$var' IN BOOLEAN MODE)",
                'order' => array('score' => 'desc')
            );

The query looks like:
SELECT *, MATCH (`headline`, `author`, `short_headline`, `subline`, `teaser`, `text`) AGAINST ('herz tod') AS `score`, `Story`.`id` FROM `fates`.`stories` AS `Story` WHERE MATCH(headline, author, short_headline, subline, teaser, text) AGAINST('herz tod' IN BOOLEAN MODE) LIMIT 15

and order by score is gone! What i am doing wrong? thanks for help!

A:

Try making score a virtualField before you try to paginate in order to use it to order your pagination.  (There may be other ways to get it to order by score, but I'm not aware of them.)
$this->Model->virtualFields['score'] = "MATCH (headline, author, short_headline, subline, teaser, text) AGAINST ('" . Sanitize::escape($var) . "')";

I'd like to also point out, just in case, that your code (and the code I posted above for that matter) is vulnerable to SQL injection, if you cannot assume $var to be trustworthy data, like if $var comes from user input.


Q:

Format Date and Time in XSLT

I have the column which returns the date and time in the default format.
<xsl:value-of select="/CAudioFile/CRI/LocalStartTime"/>

Which returns

2014-05-08T08:01:26.4000000-0700

I want to put this time in this format:

05/08/2014 08:01:26

I have tried to get the format with the different combination of substring:
<xsl:value-of select="substring(/CAudioFile/CRI/LocalStartTime,1,10)"/>

But it's either returning me just the date or just the time.
Any suggestions?
Thank you.

A:

You need to work a bit harder at it:
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 6, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 9, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 1, 4)"/>
<xsl:text> </xsl:text>
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 12, 8)"/>


Q:

When re-siding a house, where should I start?

My wife and I just bought our first house and it has some rather old aluminum siding. It's a smaller house (~ 1400 sq. ft.).
We'd like to switch to wood siding, but we honestly have no idea where to begin other than guessing that the process breaks down into two steps.

Remove aluminum siding
Install wood siding

Obviously we're going to need a little more detail than that if we're going to attempt doing it ourselves.
Any tips on where to start? Any recommended resources online?

A:

Have you thought about using hardy board siding?  You can get the same look and feel of wood without the risk of mold or termites.  The price would not be much different than a good quality wood siding.  It is not that difficult to install either, so labor cost should be no different.  It is also easy to remove and replace incase there are any future problems with the house(ie electric or plumbing) that would require you to have to remove your siding.


Q:

I found the IP Addresses via Logs & Google AP. I have a question about the the GPI?

I found out how to get all the IP addresses via Server Logs.
I'm using the IP addresses to get the Latitude and Longitude. The address appear to be approx 1 3 miles away from the actual address of the vistor.
Can someone explain why the GPI coordinates via IP address are not exactly matching the location of the user?
Is there a more dependable way to get the address?
Erik

A:

There is a similar question answered here:

Determining the nation of an Internet user based on his or her IP address is relatively simple and accurate (95%-99% percent) because a country name is required information when an IP range is allocated and IP registrars supply that information for free.
  Determining the physical location down to a city or ZIP code, however, is more difficult and less accurate because there is no official source for the information, users sometimes share IP addresses and Internet service providers often base IP addresses in a city where the company is basing operations.

Unfortunately, it's generally impossible to get the exact location of an user based on their IP address – only approximations.


Q:

Rate of change of cross-section of cylinder

I got this task on my calculus class and I got stuck at process of figuring it out
A clay cylinder is being compressed so that its height is changing at the rate of 4 millimeters per second, and its diameter is increasing at the rate of 2 millimeters per second. Find the rate of change of the area of the horizontal cross-section of the cylinder when its height is 1 centimeter.
What I know:
Volume is unknown and constant
Rate of change of diameter is $$\dfrac {dD}{dt} = 0,2\text{cm}/\text{sec}$$
Rate of change of height is $$\dfrac {dh}{dt} = -0,4\text{cm}/\text{sec}$$
Trying to find $\dfrac{dD}{dt}$ by using formula $$V=\pi r^2h$$

A:

So, First we know that $$V=\frac{\pi D^2 h}{4} $$ where $D$ is the Diameter, and $h$ is the height.
Now by differentiating this with respect to time, we get,
$\frac{dV}{dt} = \frac {\partial V}{\partial D}\frac{dD}{dt}\ + \frac {\partial V}{\partial h}\frac{dh}{dt}$
$\;\;\;\;\;= \frac{\pi D h}{2} \frac{dD}{dt}\ + \frac{\pi D^2}{4} \frac{dh}{dt}$
Now, $\frac {dV}{dt} = 0  ; \; \frac{dD}{dt}=2; \; \frac{dh}{dt} = -4; \;\;\; and \;\;\; h=10 $
(Note: All units are in mm)
Solving for $D$ we get, $D=10 mm$
Now coming back to the question we are needed to find $$\frac {dA}{dt}$$
where $A= \frac {\pi D^2}{4}$ (Cross sectional area)
Taking derivative with respect to time, we get,
$\frac {dA}{dt} = \frac {\pi D}{2} \frac {dD}{dt}$
Plugging in values, we obtain,
$\mathbf {\frac {dA}{dt} = 10 \pi \; \;mm^2/s}$


Q:

Are all Time Lords like the Doctor?

In A Good Man Goes to War, the reason they took the Ponds’ baby was they wanted a Time Lord weapon, and when the Doctor asks why Vastra says they have seen him.
My question is: are all Time Lords like the Doctor? Can they do everything he can (because surely the Doctor cannot be the smartest, bravest, etc. Time Lord) but choose not to because of their religion and politics?
Or is it just the case that the Doctor is the very very best of them and has a grander sense of duty?

A:

I'm going to assume Paul's edit to the question is an accurate representation of daniel's intent, as he has made it just specific enough that I can now go into a decent amount of detail.
The Doctor is the only Time Lord going out of his way to help people all across the universe for most of the show's run.
There's a lot of ground to cover here, so first I'm going to address "the Time Lords" as a cohesive group and ignore the handful of "rogue"/"renegade" Time Lords off doing their own thing. And I'm going to start with New Who because, let's face it, that's the part most people reading this are going to be interested in.
In New Who, most of the Time Lords didn't exist, and then they were evil, and now they're in hiding. So they've never been a force for good the way the Doctor tries to be.
For the first few seasons of New Who, the Doctor was the only Time Lord left in the universe, so he was special for that reason alone.
Then in The End of Time we learn that the events of The Last Great Time War changed the Time Lords for the worse.

WILF: But you said your people were dead. Past tense.
  DOCTOR: Inside the Time War. And the whole War was Timelocked. Like, sealed inside a bubble. It's not a bubble but just think of a bubble. Nothing can get in or get out of the Timelock. Don't you see? Nothing can get in or get out, except something that was already there.
  WILF: The signal. Since he was a kid.
  DOCTOR: If they can follow the signal, they can escape before they die.
  WILF: Well, then, big reunion. We'll have a party.
  DOCTOR: There will be no party.
  WILF: But I've heard you talk about your people like they're wonderful.
  DOCTOR: That's how I choose to remember them, the Time Lords of old. But then they went to war. An endless war, and it changed them right to the core. You've seen my enemies, Wilf. The Time Lords are more dangerous than any of them.

Note that later in that episode we found out the Time Lords were literally trying to bring an end to all of time and space.
This appears to have changed when the Doctor found a way to retroactively save Gallifrey from the Time War in The Day of the Doctor by placing the planet in a pocket universe. In the next episode, The Time of the Doctor, we discover the Time Lords are asking (in a suitably convoluted and timey-wimey way) whether or not it's safe to return to their home universe, and the Doctor doesn't answer them because it's not safe.
It's been explicitly confirmed as recently as Hell Bent that Gallifrey is still in hiding, and still has a pretty bad reputation:

CLARA: You're monsters. Here you are, hiding away at the end of Time. Do you even know why? Because you are hated. You are hated by everybody. But by nobody more than me.

So that's probably not going to change for a while.
In Old Who, the Time Lords were very non-interventionist. In fact, it seems like the only times they did go out of their way to help the universe at large were when the Doctor asked them to.
This is established in the very same story that first introduced the Time Lords: The War Games.

ZOE: What did he mean, Doctor? Who mustn't you call?
  DOCTOR: The only people who can put an end to this whole ghastly business and send everyone back to their own times. The Time Lords.
  ...
  DOCTOR: The Time Lords holding a trial is a very rare event.
  ZOE: Why?
  DOCTOR: Well, normally they don't interfere with the affairs of other planets, but they had to when I called for help.
  ...
  TIME LORD: You have heard the charge against you, that you have repeatedly broken our most important law of non-interference in the affairs of other planets. What have you to say? Do you admit these actions?
  DOCTOR: I not only admit them, I am proud of them. While you have been content merely to observe the evil in the galaxy, I have been fighting against it.
  TIME LORD 3: It is not we who is on trial here, Doctor, it is you.
  DOCTOR: No, no, of course, you're above criticism, aren't you.
  TIME LORD: Do you admit that these actions were justified?
  DOCTOR: Yes, of course, I do. Give me a thought channel and I'll show you some of the evils I've been fighting against.
  [the Doctor shows them the many monsters he fought during the first few seasons of Doctor Who]
  DOCTOR: All these evils I have fought while you have done nothing but observe. True, I am guilty of interference, just as you are guilty of failing to use your great powers to help those in need!
  TIME LORD: Is that all you have to say?
  DOCTOR: Well, isn't it enough?

The Third Doctor also tells a story that confirms this is not the first time he's tried (much less succeeded) in talking the Time Lords into doing something.

DOCTOR: We are to those creatures up there, Jo. Roll up! Roll up! Roll up! And see these funny little creatures in their native habitat! Watch them go through their funny little tricks! Poke them with a stick and make them jump!
  JO: Oh, stop it, Doctor. It's not funny.
  DOCTOR: No. Oh no, believe me, I'm just as angry as you are. As a matter of fact, I had a great deal to do with the banning of these miniscopes.
  JO: You did?
  DOCTOR: Yes, I did. I managed to persuade the High Council of the Time Lords they were an offence against the dignity of sentient lifeforms.
  JO: But I thought the Time Lords never interfered?
  DOCTOR: Yes, well, they don't as a rule. But, frankly, I made such a nuisance of myself. Well, they banned the things.

All of the other characters who could be considered renegade Time Lords are either evil, trying to keep a low profile, or in another universe.

The Master, Omega, The Rani and The Monk are not exactly upstanding citizens when they appear in the TV show. When they interfere with the rest of the universe, they do so for their own selfish reasons.
At first, Romana was babysitting the Doctor for the High Council of Gallifrey. After many seasons together, she eventually came around to the Doctor's way of looking at things, and in her final TV story (Warrior's Gate) decided to stay in E-space (aka, another universe) to help the Tharils.
If we count unaired episodes, then it's worth noting Doctor Chronotis from Shada is simply trying to keep a low profile on Earth, since he's actually one of Gallifrey's most notorious criminals.
The Meta-Crisis Doctor is trapped in another universe.
Donna was sort of a Time Lord for a brief while, but the Doctor had to undo that to keep her from dying.


Q:

Given average of positive bounded sequence converges to zero, does the average of the square sequence also converge?

Given $\frac{\sum\limits_{i=1}^n |x_i|}{n}\rightarrow 0, |x_i|\leq C $, does $\frac{\sum\limits_{i=1}^n |x_i|^2}{n}\rightarrow 0$ also hold true?

A:

Hint:
$$\frac{\sum\limits_{i=1}^n |x_i|^2}{n}\leq C\frac{\sum\limits_{i=1}^n |x_i|}{n}$$


Q:

Call function automatically whenever I open a Dialog

I've got some code in my CMyView class. There I open a dialog with DoModal():
AnotherDialog dlg;
dlg.DoModal();

Now I want to automatically run a function. The poblem is, whenever I call dlg.DoModal(), the compiler waits till I close the Dialog window again, to continue running my code into the CMyView class. The function can also automatically be called into my AnotherDialog class.
Can anyone tell me, how I can automatically run a function whenever I open another Dialog?

A:

AnotherDialog has a constructor, AnotherDialog::AnotherDialog(). Any function called from there will be called every time a dialog is created without providing arguments. If you add constructor overloads, each constructor can have different behavior, and it's up to you to make your code not confusing. (I.e. just be consistent)
If AnotherDialog is not your class, you may want to derive from it instead: class MyOtherDialog : public AnotherDialog. You can now have a MyOtherDialog::MyOtherDialog constructor which is called after AnotherDialog::AnotherDialog().
You could also add code to DoModal(), again in the existing class or a derived class.


Q:

Creating a .txt document with **kwargs

How do I get my **kwargs into my newly created .txt document?
def credentials_file(filename, **kwargs):
    open(filename, "w")
    for key, value in kwargs.items():
        filename.write("{}: {}\n" .format(key, value))

credentials_file("credentials.txt", First_Name="John",
Last_Name="Cleese")

A:

open(filename, "w") does not transforms filename from a string into a file handler, it opens the file (sometimes creating a file) and returns a handle.
So you should use:
def credentials_file(filename, **kwargs):
    handle = open(filename, "w")
    for key, value in kwargs.items():
        handle.write("{}: {}\n" .format(key, value))
    handle.close()
It is however in case of a handle, better to use a with context:
def credentials_file(filename, **kwargs):
    with open(filename, "w") as handle:
        for key, value in kwargs.items():
            handle.write("{}: {}\n" .format(key, value))
the context will automatically close the file when you jump out of the with.


Q:

C fscanf reports EOF if parsed for a digit but not for a string

I have the following line of text left in a file that I wish to parse one digit by one digit:
10001111001000101001010001100000101110000102

however when I use the format specifier %d fscanf returns an EOF indicator and not a digit. This is contrasted to when I use %s where it returns what I expect though it does it all at once and in a string.
So when I change (as well as the type of he from int to char[250])
if (fscanf(f, "%d", &character) != EOF)

to
if (fscanf(f, "%s", &character) != EOF)

A:

If you want to scan digit by digit, you need to use "%1d" as the format.
Otherwise, it reads the whole line (apart from the newline) as the number and invokes undefined behaviour when it converts the large decimal number into a 32-bit int.  Note that the mnemonic for d is not 'digit' but 'decimal', as opposed to 'o' for octal, 'x' for hexadecimal, and 'i' for integer in decimal, octal or hexadecimal according to the normal prefixes (leading 0 for octal, 0x for hex, or decimal otherwise).
It is still not entirely clear why it returns EOF, but with undefined behaviour, any response is valid.
The standard (ISO/IEC 9898:2011 Section 7.21.6.2 The fscanf() function, Para 10) says (in the relevant part):

If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

There is quite a lot of verbiage about the behaviour under error conditions, but this is the crucial one here.  Since the behaviour is undefined, getting EOF is a valid and relatively benign response.  It would be interesting to investigate whether the file stream is in the state where feof(f) or ferror(f) returns true.  There's no obvious reason why it should be except that you do not normally get EOF from fscanf() unless one or the other is true.


Q:

Cannot set property of undefined - Global objects and namespacing in JavaScript

I'm using a variable attached to the window:
window.App
As a reference point for the rest of my variables within my application. However, when I attempt to do this:
window.App = {};

App.Views.User.Login = /* Login View Instance */;

It will complain about Views not being defined. This is fine for the most part because I can  predefine App.Views, App.Models, App.Collections, etc.
However when we get into the submodules that aren't always needed (App.Views.User) I would prefer for this to be loaded when needed...
Is the only option the following?
if( ! App.Views.User ) { App.Views.User = {}; };

App.Views.User.Login = /* Login View Instance */;

A:

I would start your submodules like this:
App.Views.User = App.Views.User || {};
App.Views.User.Login = new Backbone.Marionette.ItemView.extend({});

Only marginally cleaner than what you have already but that's generally what you do.


Q:

How to delete a Google Search Console property

Is it possible to remove a property from Google Search Console?

A:

Yes you can remove a property from Google Search Console:

Manage property
Delete property


Q:

Android: How to create a StateListDrawable programmatically

I have a GridView to display some objects, and visually each of the objects will have an image icon and a text label. I also want the image icon to have some "push and pop" effect when clicked, that is, when pressed, the image will move a small distance to the bottom right direction, and when released get back to its original position.
The objects (and their image icons) are from some dynamic sources. My intuition is to create a StateListDrawable for each item, which will have two states: pressed or not. For GridView item view, I would use a Button, which can accomodate a Drawable and a label, that perfectly satisfies my requirment.
I defined an item class to wrap up the original object:
public class GridItem<T> {

    public static final int ICON_OFFSET = 4;

    private StateListDrawable mIcon;
    private String mLabel;
    private T mObject;

    public Drawable getIcon() {
        return mIcon;
    }

    public void setIcon(Drawable d) {
        if (null == d) {
            mIcon = null;
        }else if(d instanceof StateListDrawable) {
            mIcon = (StateListDrawable) d;
        } else {
            InsetDrawable d1 = new InsetDrawable(d, 0, 0, ICON_OFFSET, ICON_OFFSET);
            InsetDrawable d2 = new InsetDrawable(d, ICON_OFFSET, ICON_OFFSET, 0, 0);
            mIcon = new StateListDrawable();
            mIcon.addState(new int[] { android.R.attr.state_pressed }, d2);
            mIcon.addState(StateSet.WILD_CARD, d1);
            //This won't help either: mIcon.addState(new int[]{}, d1);
        }
    }

    public String getLabel() {
        return mLabel;
    }

    public void setLabel(String l) {
        mLabel = l;
    }

    public T getObject() {
        return mObject;
    }

    public void setObject(T o) {
        mObject = o;
    }

}

Now the problem is, when I touch a grid item, the icon "moves" quite as I have expected, but it won't restore its original position when my finger lifts up leaving the item.
My question is: how to programmatically create a StateListDrawable equivalent to one inflated from an XML resource like
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/image_pressed" />
    <item android:drawable="@drawable/image_normal" />
</selector>

?

A:

if your drawables are just bitmaps, you could draw them programmatically, for now it should help, however I wonder what is the problem with InsetDrawable usage here, basically use prepared BitmapDrawables that are drawn programatically, you would need to modify your method to accept bitmaps b
        Bitmap bc1 = Bitmap.createBitmap(b.getWidth() + ICON_OFFSET, b.getHeight() + ICON_OFFSET, Bitmap.Config.ARGB_8888);
        Canvas c1 = new Canvas(bc1);
        c1.drawBitmap(b, 0, 0, null);
        Bitmap bc2 = Bitmap.createBitmap(b.getWidth() + ICON_OFFSET, b.getHeight() + ICON_OFFSET, Bitmap.Config.ARGB_8888);
        Canvas c2 = new Canvas(bc2);
        c2.drawBitmap(b, ICON_OFFSET, ICON_OFFSET, null);

        mIcon = new StateListDrawable();
        mIcon.addState(new int[] { android.R.attr.state_pressed },  new BitmapDrawable(bc2));
        mIcon.addState(StateSet.WILD_CARD, new BitmapDrawable(bc1));

A:

I can see the answer is already accepted. I am sharing if you want to assign dynamically colors of buttons from the users for normal as well as pressed state. then you can just call this function :
public static StateListDrawable convertColorIntoBitmap(String pressedColor, String normalColor){

        /*Creating bitmap for color which will be used at pressed state*/
        Rect rectPressed = new Rect(0, 0, 1, 1);

        Bitmap imagePressed = Bitmap.createBitmap(rectPressed.width(), rectPressed.height(), Config.ARGB_8888);
        Canvas canvas = new Canvas(imagePressed);
        int colorPressed = Color.parseColor(pressedColor);
        Paint paintPressed = new Paint();
        paintPressed.setColor(colorPressed);
        canvas.drawRect(rectPressed, paintPressed);
        RectF bounds = new RectF();
        bounds.round(rectPressed);

        /*Creating bitmap for color which will be used at normal state*/
        Rect rectNormal = new Rect(0, 0, 1, 1);
        Bitmap imageNormal = Bitmap.createBitmap(rectNormal.width(), rectNormal.height(), Config.ARGB_8888);
        Canvas canvasNormal = new Canvas(imageNormal);
        int colorNormal = Color.parseColor(normalColor);
        Paint paintNormal = new Paint();
        paintNormal.setColor(colorNormal);
        canvasNormal.drawRect(rectNormal, paintNormal);

        /*Now assigning states to StateListDrawable*/
        StateListDrawable stateListDrawable= new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new BitmapDrawable(imagePressed));
        stateListDrawable.addState(StateSet.WILD_CARD, new BitmapDrawable(imageNormal));

        return stateListDrawable;

    }

Now all you need is to set it as your textview or button background like below :
 if(android.os.Build.VERSION.SDK_INT>=16){
        yourbutton.setBackground(convertColorIntoBitmap("#CEF6CE00","#4C9D32"));

            }else{

yourbutton.setBackgroundDrawable(convertColorIntoBitmap("#CEF6CE00","#4C9D32"));
    }

Here you can see all you need to pass the colors dynamically and we're done. hope this will help someone :) You can find it's gist too here :)

A:

I have seen the previous answers, but came up with a much shorter and better solution using ColorDrawable.
/**
     * Get {@link StateListDrawable} given the {@code normalColor} and {@code pressedColor}
     * for dynamic button coloring
     *
     * @param normalColor  The color in normal state.
     * @param pressedColor The color in pressed state.
     * @return
     */
    public static StateListDrawable getStateListDrawable(int normalColor, int pressedColor) {
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(pressedColor));
        stateListDrawable.addState(StateSet.WILD_CARD, new ColorDrawable(normalColor));
        return stateListDrawable;
    }

This accepts resolved colors as integer and uses ColorDrawable to add them in a StateListDrawable.
Once you have the drawable, you can use it simply like this,
if (android.os.Build.VERSION.SDK_INT >= 16) {
            mButton.setBackground(Utils.getStateListDrawable(ResourceUtils.getColor(R.color.white),
                    ResourceUtils.getColor(R.color.pomegranate)));
        } else {
            mButton.setBackgroundDrawable(Utils.getStateListDrawable(ResourceUtils.getColor(R.color.white),
                    ResourceUtils.getColor(R.color.pomegranate)));
        }


Q:

Django : How to rollback in save method

Our app need to sync his data within a LDAP backend.
Eg : Each time a user in saved in django some of the data must be saved in LDAP.
For that, we use the django ldap backend which work great.
At start we wrote the sync code in post_save signal of the member. Sync work well, but this way, we can't rollback database save if LDAP fail for any reason.
So we plane to wrote sync code in overridded save method. But here too we can't find a way to rollback.
The closest solution we have is :
@transaction.commit_manually
def save(self, *args, **kwargs):

    super(MyModel, self).save(*args, **kwargs)

    try:
        self.sync_with_ldap()
    except:
        transaction.rollback()
        raise
    else:
        transaction.commit()

This code return a TransactionManagementError : "This is forbidden when an 'atomic' block is active."
How can we do to :

Rollback inside a save method
Or another way to get our two models synced each overs

A:

In fact, was very simple :
Just have to decorate with @transaction.atomic
@transaction.atomic
def save(self, *args, **kwargs):

    super(MyModel, self).save(*args, **kwargs)

    try:
        self.sync_to_ldap()
    except:
        raise