Q:

Shipping a new SQLite database in app update

Our app will ship with a pre-populated database which continually downloads updates from our production server's database to stay up to date. When we make updates to our app's codebase and push those updates out to the AppStore we'll also include an updated db.sqlite file.
My questions is: when we do this I assume it will overwrite the users "old" database file that already exists?
I assume (and hope) the answer is yes, but just wanted to double check - I couldn't find any answers in Apple's documentation, but might have simply overlooked, or have been looking for the wrong terminology.

A:

When you say "which continually downloads updates from our production server's database" I assume that means the app will download the data and update the database?  In which case the database must exist in the Documents folder and it won't get into the Documents folder until you copy it there.
Normally this is done by the app if the database file doesn't already exist, however if you want to overwrite the current database you'll need a mechanism to discover if the one in the Documents folder is out-of-date, compared to the one in the app bundle.  This probably means having a "metadata" table (with two columns name/value) containing a version number or some such.  You read both databases and decide whether or not to copy.


Q:

Core Animation performance on iphone

I'm trying to do some animations using Core Animation on the iphone. I'm using CABasicAnimation on CALayer. It's a straight forward animation from a random place at the top of the screen to the bottom of the screen at random speed, I have 30 elements that doing the same animation continuously until another action happens. But the performance on the iPhone 3G is very sluggish when the animations start. The image is only 8k.
Is this the right approach? How should I change so it performs better.
// image cached somewhere else.
CGImageRef imageRef = [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]] CGImage];

- (void)animate:(NSTimer *)timer
{
    int startX          = round(radom() % 320);
    float speed         = 1 / round(random() % 100 + 2);

    CALayer *layer      = [CALayer layer];
    layer.name          = @"layer";
    layer.contents      = imageRef; // cached image
    layer.frame         = CGRectMake(0, 0, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));

    int width           = layer.frame.size.width;
    int height          = layer.frame.size.height;

    layer.frame         = CGRectMake(startX, self.view.frame.origin.y, width, height);

    [effectLayer addSublayer:layer];

    CGPoint start       = CGPointMake(startX, 0);
    CGPoint end         = CGPointMake(startX, self.view.frame.size.height);
    float repeatCount   = 1e100;

    CABasicAnimation *animation     = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.delegate              = self;
    animation.fromValue             = [NSValue valueWithCGPoint:start];
    animation.toValue               = [NSValue valueWithCGPoint:end];
    animation.duration              = speed;
    animation.repeatCount           = repeatCount;
    animation.autoreverses          = NO;
    animation.removedOnCompletion   = YES;
    animation.fillMode              = kCAFillModeForwards;

    [layer addAnimation:animation forKey:@"position"];
}

The animations are fired off using a NSTimer.
animationTimer = [NSTimer timerWithTimeInterval:0.2 target:self selector:@selector(animate:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:animationTimer forMode:NSDefaultRunLoopMode];

A:

Okay, a couple of things here:
Why are you using an NSTimer to repeatedly fire the animation? Just have the animations repeat. If they need pause and resync you can do that with a keyed animation. By programming it all up you can let the renderer run without having to frequently synch in new information into the render tree.
You are doing:
CGImageRef imageRef     = [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]] CGImage];

for 30 objects each on a timer that fires every 0.2 seconds? Have you profiled your app? What percentage of the time is spent in image decoding? If you switch over to using imageNamed: iPhone OS will cache images so long as there is enough ram, which should reduce your decode time:
CGImageRef imageRef = [[UIImage imageNamed:[NSString stringWithFormat:@"%@.png", name]] CGImage];

Also, do your images have transparency that needs to be alpha composited? If you can avoid alpha it is a huge speed win on the older iPhones.


Q:

Show that if $A\subseteq B$, then inf $B\leq$ inf $A\leq$ sup $A \leq$ sup $B$

Is my logic correct or am I missing something?
Show that if $A\subseteq B$, then inf $B\leq$ inf $A\leq$ sup $A \leq$ sup $B$
Case 1. If $A \subset B$ then there exists $b_1,b_2\in B$ such that $b_1,b_2 \notin  A$. Let $a_1,a_2 \in A$ such that $a_1=$ inf A and $a_2$ = sup A. Suppose $b_1$=inf B and $b_2$=sup B than $b_1<a_1<a_2<b_2$ which implies inf $B<$ inf $A < $ sup $A<$ sup $B$
Case 2. If $A = B$ than every element in $A$ is in $B$. This implies that if $A$ is bounded above or below so is $B$ and vice versa. If the sup $B$ is defined to be the least upper bound and the inf $B$ is defined to be the greatest lowest bound. Than sup $B$ = sup $A$ and inf $B$ = inf $A$.
Since $A \subseteq B$ the following equality can be written as inf $B\leq$ inf $A\leq$ sup $A \leq$ sup $B$

A:

Let's proceed by contradiction.
1)  inf B $\le$ inf A
Assume, to the contrary, that inf B > inf A.  Then there is some $x$ such that inf A < $x$ < inf B, but then $x \in A $ and $x \notin B$, a contradiction since $A \subseteq B$.  (Also note here: If I were being super rigorous I would need to appeal to the definition of infimum to make sure that $x$ is indeed in $A$.  Notice the strict inequality.)
Thus,  inf B $\le$ inf A
2)  sup A $\le$ sup B
Assume, to the contrary that sup A > sup B, then there exists some $x$ such that sup B < $x$ < sup A.  However, then $x \in A$ and $x \notin B$.  Again, a contradiction for the same reason as before.
3)  inf A $\le$ sup A.  By definition of sup and inf.
All together inf B $\le$ inf A $\le$ sup A $\le$ sup B.
Maybe someone can post a comment to help a little bit, what property of the real numbers am I using when I assume existence of $x$ like I do above?  Certainly it must exist since there are no gaps in the real numbers.  That way I can say that given two real numbers $a,b$ with $a <b$ then there exists $x$ such that $a <x <b$.  Is this the Archimedian property?  something topological?


Q:

Connecting freeswitch remotely using node esl fails

Im trying to connect remotely to FreeSwitch service using ESL.
Connecting machine and FS Service both are in my local VM's, 2 different VM's
But i get below error
[WARNING] mod_event_socket.c:2639 IP 10.95.38.254 Rejected by acl "loopback.auto"

/autoload_configs/event_socket.conf.xml
<configuration name="event_socket.conf" description="Socket Client">
  <settings>
    <param name="listen-ip" value="0.0.0.0"/>
    <param name="listen-port" value="8021"/>
    <param name="password" value="ClueCon"/>
  </settings>
</configuration>

Script:
var conn = new esl.Connection('10.191.73.254', 8021, 'ClueCon', function() {

  conn.api('status', function(res) {
    console.log(' >> Connected >> ');
    console.log(res.getBody());
  });

});

A:

I added below lines into acl.config.xml and its working fine
/auto_configs/acl.config.xml
<list name="loopback.auto" default="allow">
    <node type="allow" cidr="10.95.38.0/24"/>
</list>


Q:

How do I generate a random number between two variables that I have stored?

Possible Duplicate:
Generating random integer from a range

I am trying to create a program where the computer guesses a number the user has in his/her mind. The only user input required is whether the guess was too high, too low, or correct. I'm having a problem generating a random number between two variables that store the min and max based on previous guesses. Here is my code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>

    using namespace std;

    int main()
    {
        srand(static_cast <unsigned int> (time(0)));

        int compGuess = rand() % 100 +1; //Generates number between 1 - 100
        int highestNumber = 100;
        int lowestNumber = 1;
        char ready;
        char highLowSuccess;
        bool success;
        int tries = 0;

        cout << "Please pick a number between 1 - 100. I will guess your number. Don't tell me what it is!\n\n";

        do
        {
            cout << "Are you ready? (y/n)\n\n";
            cin >> ready;

            if (ready == 'y')
            {
                do
                {
                    cout << "Is your number " << compGuess << "?\n\n";
                    cout << "High, Low or Success?";
                    ++tries;
                    cin >> highLowSuccess; //User input telling the computer whether its too high, too low, or a success

                    if (highLowSuccess == 'h') //Executes code if number guessed was too high.
                    {

                        highestNumber = compGuess - 1; //Stores variable indicating the highest possible number based on user input
                        compGuess = rand() % highestNumber +1; //Generates a new random number between 1 and the new highest possible number
                        success = false;
                    }

                    else if (highLowSuccess == 'l') //Executes code if number guessed was too low.
                    {
                        lowestNumber = compGuess + 1;//Stores variable indicating the lowest possible number based on user input
                        compGuess = (rand() % highestNumber - lowestNumber + 1) + lowestNumber // <---- Not producing the desired result
                        success = false;
                    }

                    else if (highLowSuccess == 's') //Executes code if the computer's guess was correct.
                    {
                        cout << "I guessed your number! It only took me " << tries << " tries!";
                        success = true;
                    }

                } while (success != true);
            }

            else
            {
             continue;
            }

       } while (ready != 'y');

    return 0;

    }

highestNumber is what the max should be and lowestNumber is what the min should be. I need an equation that lets me generate a random number while taking the highest and lowest possible numbers into account.
Forgive me if the answer is really simple, I'm a noob programmer. xD

A:

To generate a random number between min and max, use:
int randNum = rand()%(max-min + 1) + min;

(Includes max and min)

A:

Really fast, really easy:
srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:
#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:
int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

A:

If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:
//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);

That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...
Hope this helps
- Luke


Q:

Custom Font not working In Custom HTML email template

I have created static resource and included ttf file for gotham font, when I used below code in visualforce page it is rendering as expected. but when same I included in custom html email template it does not render in gmail,outlook
@font-face{
font-family: 'Gotham';
 src: url(/resource/GothamFont);
}
Can you please help me on this?

A:

This is not related to Salesforce, but to web-safe fonts.
Majority of Email clients have no support for custom fonts, even today.
While there are few that partially support them, Gmail unfortunately isn't.
As alternative you can look into utilizing Google Sans or Roboto in Gmail, these are supported as of late 2018.
You'll also need to beware of any custom font EULA, as typically web fonts are not licensed to be used in Emails legally.
Read more - Litmus Guide to Web Fonts in Email (2019)
And this - Web Fonts in Email (2019)


Q:

Conflict between global variables c/c++

I'm using two files ".h" in which there are 3 global variables with the same names.
We suppose to have these files:

A.h => inside it there are "union var1", "union var2" and "#define LENGTH 20".
B.h => inside it there are "union var1", "union var2" and "#define LENGTH 60".
C.h => that imports both A.h and B.h.

When I compile C.h, I have an error cause of the conflict for same variables name.
I don't want to modify their names because They are inside public libraries (I would like to use them as they are!).
This is my problem.
Can someone help me? Thanks.

A:

Quarantine each public library so that you don't need to include both header files in any single file. Files may use one library or they may use the other, but not both. You will need to create wrappers for functionality that you need, wrapping whichever library is easiest to wrap and using your wrapper, instead of the library directly, in code that uses the other library.

A:

First, header files (".h") never get "compiled", strictly speaking, so there is no such thing as When I compile C.h. Only .cpp files, which of course include these header files get compiled.
Second, if your program needs to include the two header files that reference different variables that have the same name, then you probably have some bad design problem.
Third, I think (?, don't use unions very much...) that you need to define a name for a union.
Otherwise, a solution could be to define different namespaces to distinguish the two:
// A.h
namespace aa {
    union myType { int m1; float m2; }
    myType var1;
}

.
// B.h
namespace bb {
    union myType { int m1; float m2; }
    myType var1;
}

.
// C.cpp
#include "A.h"
#include "B.h"

...
    aa::var1.m1 = 1;
    bb::var1.m1 = 2;


Q:

Interdependence of unit tests

Since recently, I am trying out unit testing to get acquainted with the practice, and to ultimately write better code. I have started on one of my big projects, with a rather large untested code base, but am only unit testing utility classes, that don't have many dependencies and are quite easy to test.
I have read quite a bit of introductory material to unit testing in general, and what often comes up is that unit tests should always test the smallest possible unit of behaviour. That is to say, that whether a test passes or fails should only depend on a very specific piece of code, such as a small method.
However, I am already finding problems to put this idea into practice. Consider for example :
@Test
public void testSomethingWithFoo() {
    Foo foo = new Foo(5);

    Bar result = foo.bar(); //Suppose this returns new Bar(42) for some reason.

    Bar expected = new Bar(42);
    Assert.assertEquals(expected, result); // Implicitly calls Bar.equals, which returns true if both Bars' constructor parameters are equal.
}

Clearly, this test depends on two elements : the foo.bar() method, but also the bar.equals(otherBar) method, which is implicitly called by the assertion.
Now, I could write an other test, which asserts that this bar.equals() method works correctly. However, say it fails. Now, my first test also should fail, but for a reason beyond its scope.
My point is that, for this particular example, nothing really is problematic; I could maybe check for equality without using equals at all. However, I feel like this sort of issue will become a real problem with more complex behaviours, where avoiding existing methods because they might not work would involve rewriting large amounts of code just for tests.
How to translate these requirements into code, without making unit tests interdependent ?
Is it even possible ? If not, should I stop bothering about this issue, and assume all methods not under the current test work ?

A:

However, say it fails. Now, my first test also should fail, but for a
  reason beyond its scope.

Test isolation is a really important thing, you are right but note also that this has a limitation.
You will necessary fall into some cases where in your unit tests, you will have to rely on other general methods of other objects such as equals/hashCode or still constructors.
This is unavoidable. Sometimes, the coupling is not an issue.
For example, using a constructor to create the object passed to the method under test or a mock value is natural and should really not be avoided !
But in other cases, the coupling with the API of another class is not desirable.
It is for example the case in your sample code as your test relies on an equals() method which the fields tested may change through the time and also be functionally different from fields to watch/assert in the tested method.
In addition, this doesn't make the fields asserted explicit.
In this kind of case, to assert fields values of a returned object by the method under test, you should assert field by field via getter methods.
To avoid writing this repetitive and error prone code, I use a matcher testing library such as AssertJ or Hamcrest (included in JUnit at a time) that provides fluent and flexible way to assert the content of an instance.
For example with AssertJ :
Foo foo = new Foo(5);
Bar actualBar = foo.bar();
Assertions.assertThat(actualBar)
          .extracting(Bar::getId) // supposing 42 is stored in id field
          .containsExactly(42);

With such a simple example, matcher testing library has no real value. You could directly do :
Foo foo = new Foo(5);
Bar actualBar = foo.bar();
Assert.assertEquals(42, actualBar.getId())

But for cases where you want to check multiple fields (very common case), it is very helpful :
Foo foo = new Foo(5);
Bar actualBar = foo.bar();
Assertions.assertThat(actualBar)
          .extracting(Bar::getId, Bar::getName, Bar::getType)
          .containsExactly(42, "foo", "foo-type);


Q:

How do I open Deja Dup as root?

I wanted to backup /var/cache/apt/archives using 'Deja Dup' but it keeps saying >>

Could not backup the following files. Please make sure you are able to open them.
/var/cache/apt/archives/lock

Any help?

A:

Configure Deja Dup for your root backup: gksu deja-dup-preferences.
Run backup then with: gksu "deja-dup --backup".

At least this worked for me. (You have to configure Deja Dup for root, too, at first - next to your configuration for the "normal" user.)
As mythsmith says: "You can do that just for system folders, and still keep your home folder configured in your user account."

A:

In 12.04 the following simple command works, if you have sudo privileges:
sudo deja-dup-preferences

A:

Start by:

Run DEJA backup GUI and configure what you want to backup and where to save your backup files, without clicking backup now, just save your backup setting and exit Deja GUI.
Start terminal ALT+CTRL+T and type this command when you are ready to start backup sudo deja-dup --backup.

GUI window will open and backup should start.


Q:

Angular 4 Events with EventEmitter

I made a service named UserEvents
@Injectable()
export class UserEvents {

public evAuthenticated: EventEmitter<string> = new EventEmitter();

public AuthUserEvent(email: string) {
this.evAuthenticated.next(email);
  }
}

I included this service with the providers in AppModule
I have a service name AuthService that include the UserEvents and emits:
this.userEvents.evAuthenticated.emit(email);

And another service that suscribe
constructor(private userEvents: UserEvents){
this.userEvents.evAuthenticated.subscribe((data: string) => this.SetUser(data));
}

private SetUser(email: string) {
   this.logger.info('Event triggered with ' + email);
}

But the suscription is never triggered.  At list, SetUser is never called.
What is wrong here?

A:

From my knowledge of Angular 2(+), EventEmitters are to be used as Component Outputs, i.e.:
 @Output() myStringOutput = new EventEmitter<string>();

If you need a triggerable event in your services, it is recommended to use RxJS Subjects, like so:
import { Injectable } from '@angular/core'
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MyService {

  private _onMyEvent = new Subject<string>();
  public get onMyEvent(): Observable { return this._onMyEvent.asObservable(); }

  public trigger(value: string) {
    this._onMyEvent.next(value);
  }
}

And elsewhere in your code, you can do something like this:
this.myService.onMyEvent.subscribe((value: string) => console.log('Triggered!', value));
this.myService.trigger('Hello World')

Plunkr.


Q:

Modeling a Radiator Heater

I have been attempting to model a radiator heater.
Now, my radiator in real life is made out of five vertical pipes with one cross beam arrayed seventeen times along a bottom pipe that carries the hot water through a system of pipes originating and ending at the boiler in the basement. Here are some pics of it up close:

And my recreation of it in my most recent render:

What I did to create my Blender radiator was fairly elementary. I took a cube, added some loop cuts in both directions, and added a Wireframe modifier. This created a skeleton, but not the interior.
While I am aware that I could use the Array modifier here to repeat a wireframed section over and over again, I am wondering if there is a less choppy solution, as the ends would still have to be separate, and then I'd have to combine and remove doubles and blah-di-blah. What I would like is a short and quick way to produce a more photorealistic radiator. It does not need to be high-poly, infact low-poly would be better, because the radiator is not the focus of the image.
Thoughts?
If it wouldn't be too much trouble, a reiteration of the following .blend file with a new radiator in your answer would be great! Note that I could not pack any Image Textures, as the .blend would have been too big for Blend Exchange.

A:

First I created this profile shape and extruded it to create the vertical pipes (CTRL + E) in Edit Mode.

Then added some loop cuts and joined them for the top, middle and bottom cross sections. Added a Subserf Modifier and some additional loop cuts to clean up some edges.
Then added an Array Modifier above the Subserf Modifier and applied it.
Then extruded the feet on the two ends and modeled the pipe to the floor.

A:

I'd still try to stick with modifiers as long as you can, but set them up in a way so removing doubles and manual fixing should not be necessary at all. Here's the blend with a modified (beware, joke) radiator:
This is the preliminary result:

I didn't bother yet to put the pipework in, but to give you my direction, I'd use the skin modifier for the pipes in a separate mesh, or alternatively an extruded curve for that. For the connection nut, the bolt factory addon comes in handy, it ships with Blender.
What I like so much about the modifier system is, that basically you only need this:

Notice in the modifier stack, that I use end caps a lot. This allows to exchange the start and end mesh of the array with a different one. So all I did, was to duplicate the inner mesh that makes the ribs, and slightly modify them. You can see that procedure when you look at the layers 12 and 13 in the blend. Make sure the merge option is set in the array, with a feasible threshold. That way, the mesh is perfectly connected everywhere (hopefully, as it is quite late here now....)


Q:

Please elaborate difference between assertArrayHasKey() and assertEquals() in the below code

I was reading a Unit Test and it contains these two functions
assertArrayHasKey() and assertEquals()
Please explain the difference between them by sitting in the context of below code.
// Test all basic required params were set
    $options = $getReportInstance->getOptions();
    $this->assertArrayHasKey('AWSAccessKeyId', $options, "Option AWSAccessKeyId doesn't exit");
    $this->assertEquals(self::APP_ACCESS_KEY, $options['AWSAccessKeyId'], "AWSAccessKeyId was not set correctly!");
    $this->assertArrayHasKey('SignatureMethod', $options, "Option SignatureMethod doesn't exist");
    $this->assertEquals(
        self::SIGNATURE_METHOD,
        $options['SignatureMethod'],
        "SignatureMethod was not set correctly!"
    );

A:

The assertArrayHasKey asserts if the array has a value with the key you put in. Does the value exist?
The assertEquales asserts if the value is the same as you expect it to be. Is the value correct?
So they both test something else. The first tests if the value is there and the second one tests if the value is the same as what you expect it to be.


Q:

How to URLEncode within aura:component

With an VisualForce page, we just call URLEncode.  Took 5 minutes for me to figure that out.
How to we do the equivalent inside an aura:component, with markup like this:
<iframe src="{!'https://example.com/Encode This'}" ..... />
This obviously does not work:
<iframe src="{!URLENCODE('https://example.com/Encode This')}" ..... />
I have spent 2 hours googling and trying different things to no avail.  This seems unreasonably hard.
Thanks

A:

There is no expression that allows you to do this. If you need encoding, do so in your controller. For example:
<aura:attribute name="iframeSrc" type="String" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<iframe src="{!v.iframeSrc}"></iframe>

...
doInit: function(component, event, handler) {
  component.set("v.iframeSrc", encodeURI("https://www.example.com/Encode This"));
}

Otherwise, you'd want to manually encode the URL:
<iframe src="https://example.com/Encode%20This" ..... />

For a full list of functions you can actually use, see Expressions Function Reference.
You'll notice it is significantly slimmer than the Visualforce formulas that you can use; most anything you'd expect to do in markup in Visualforce is done by the controller in Lightning.


Q:

Adding a Symbol to a Function

Considering the code below
namespace Add {

  type AddType = {
    (x: number, y: number): number;
  };

  const add: AddType = (x: number, y: number) => {
    return x + y;
  };
}

Is it possible to add a 'unique symbol' to the AddType, code below.
namespace AddUsingSymbol {

  declare const AddSymbol: unique symbol;

  type AddType = {
    (x: number, y: number): number;
    [AddSymbol]: void;
  };

  /* const add: AddType = (x: number, y: number) => {
    return x + y;
  }; */
  // the code above does not compile
}

Is it possible to create an instance of AddType, using the Symbol, in a safe manner without typecasting?

A:

If you don't want to use a type assertion then I'd suggest using Object.assign() to copy the symbol-keyed property into the function object, like so:
const add: AddType = Object.assign((x: number, y: number) => {
    return x + y;
}, { [AddSymbol]: undefined });

This will be considered type safe by the compiler.  Okay, hope that helps; good luck!
Playground link to code


Q:

How to check if string has no vowel after 4 consecutive chars

I want to check if a user is entering something close to a valid name. So if it's entered something like gbcvcvrt, I would want to validate it and mark this as not a real name. Something like theg+vowel should be validated as the right name.
On any length of string the code should detect four consecutive non vowel alphabets.
I don't expect anyone's name to be rhythm by the way
Consider
$String = 'therhythm';

We can't check for the first four chars, we have to go through the entire string and check four any four consecutive non-vowel alphabets regardless of where on the string they are  situated. That way we can validate $String as not valid even though the first five chars would validate it if we were checking the first four alphabets.

Should also not contain 3 consecutive vowels,
Should not contain numbers,
Non Alphabetic chars

A:

Based on your latest edit: You can use following regex for this:
^(?!.*?[^aeiou]{5})(?!.*?[aeiou]{3})[a-z]*$

Online Demo: http://regex101.com/r/vM0aN9
Breaking it down:

[^aeiou] => Match anything but vowels
(?!.*?[^aeiou]{5}) => Negative lookahead to make sure there is no case of 5 consecutive consonants
(?!.*?[aeiou]{3}) => To make sure there is no case of 3 consecutive vowels
[a-z]* => To make sure there are only letters in the input


Q:

Who is the owner of the world's only private Boeing 787 Dreamliner?

I have just stumbled across this video and I was wondering, if anyone knows who is the owner of this particular airplane (world's only private Boeing 787 Dreamliner)? I mean a man or a company -- an actual user or property owner. Not an airline / operator, because it seems to be Deer Jet.
The video itself does not reveal plane's registration or serial number, so I cannot look it up in any aviation database.
I've tried to locate it in Flightradar 24 database, based on airline / operator -- Deer Jet -- but it lists Gulfstreams and Dassault Falcons only for this operator. Neither Boeing 787 nor any other Boeing.

A:

The registration number of this aircraft is well visible in the video: 2-DEER.
According to Planespotters, this B787 was first leased by Jet Aviation Flight Services from 2014 to 2016. During this time it was registered as N28MS.
In 2016, the plane was bought by Deer Jet, a company owned by HNA and received the registration number 2-DEER. The video was published in 2017. That means 2-DEER was not privately owned, but available and furnished for private charter clients. The video title is a tad misleading.
Deer Jet was trying to sell it for 300 million US$ in 2018 (source).
In February 2020, 2-DEER was spotted still in Deer Jet livery. It appears that they couldn't find a buyer.
The registration number starting with 2- might look unfamiliar to most of us. A company called 2-REG offers these personalised registration marks. Here is an advertising text from www.weareguernsey.com that summarizes it:

2-REG is an ICAO (International Civil Aviation Organisation) registry,
well-recognised around the world for accommodating all aircraft
categories, including commercial aircraft, business jets, helicopters,
and general aviation. In 2015, 2-REG began to issue Aircraft Operating
Certificates (AOCs), and six have been issued so far.
Run by the Dutch company SGI Aviation, 2-REG pays royalties to the
Guernsey government on operating income. The registry has built its
reputation by being extremely responsive and customer-focused,
offering its worldwide coverage coupled with competitive fees, making
it the most successful registry within the aircraft leasing sector.


Q:

How to split bio into multiple bios?

I want create a block device that get a bio with request for n sector and split it into n bio with 1 sector. I used bio_split but it doesn't work and reaches BUG_ON.
Is there any function to do such thing?
If there's not can anyone help me to write a function to do that?
It's also fine to have a function that split a bio into 4k bios.

A:

The split_bio() function only works for bios with a single page (when bi_vcnt field is exactly 1).
To deal with bios with multiple pages - and I suspect you deal with these most of the time - you have to create new bios and set them up so that they contain only a single sector.
Tip: If the sector size is the same as the page size (currently 4K), and your block driver tells the kernel to supply no less than this size, than you only have to put each page from the incoming bio to the new bio. If the sector size is less then the page size, than the logic will be a bit more complicated.
Use bio_kmalloc to allocate the new bios and copy the data onto the memory pages in them manually.


Q:

gsap mouse trailing on v3

I'm trying to get the effect shown in this pen using gsap v3, but can't get it to work.
The provided pen is in older version of gsap, I tried converting it as shown below:
            const createLine = (leader, i) => {
            let line = document.createElementNS(svgns, 'line');
            line.setAttribute('data-svg-origin', '0 0');
            rootSvg.appendChild(line);

            gsap.set(line, { x: -15, y: -15, alpha: (5 - i) / 5 });

            let posX = gsap.getProperty(line, 'x');
            let posY = gsap.getProperty(line, 'y');

            gsap.to(line, 1000, {
                x: '+=1',
                y: '+=1',
                repeat: -1,
                modifiers: {
                    x: () => {
                        let x = posX + (leader.x - posX) * ease;
                        line.setAttribute('x2', leader.x - x);
                        return x;
                    },
                    y: () => {
                        let y = posY + (leader.y - posY) * ease;
                        line.setAttribute('y2', leader.y - y);
                        return y;
                    }
                }
            });

            return { x: posX, y: posY };
        };

But this produces very buggy output. How can I make this work using gsap v3.

A:

You're using static values inside of the modifier functions whereas the original is pulling values every update from the objects. Use gsap.getProperty() inside of the modifiers functions for both the line and the leader and it will behave like you want it to: Demo


Q:

Templated Using with Nested Template

The following code does not work because the inferred template parameter F is std::tuple, whereas I want it to be Foo - the former takes two template parameters and the latter takes one.
#include <tuple>

template <typename T>
using Foo = std::tuple<int, T>;

template <template <typename> class F>
void foo(F<std::string> bar) {}

void test() {
  foo(Foo<std::string>());
}

Is there any way to make type inference work with the using statement rather than turning Foo into it's own class?
#include <tuple>

template <typename T>
class Foo {
  std::tuple<int, T> bar;
};

template <template <typename> class F>
void foo(F<std::string> bar) {}

void test() {
  foo(Foo<std::string>());
}

More Info
I am using C++17's std::variant along with using to alias types that are generic on a single type and I would prefer to declare these with using statements rather than creating wrapper classes for each one. Something like this:
// Assuming Plus, Minus, etc all exist
template <typename T>
using Operation = std::variant<Plus<T>, Minus<T>, Times<T>>;

Building a Haskell-Style Functor
The point of this exercise is to build a small functor library loosely based on Haskell's functor typeclass. I have defined the "typeclass" like this:
template <template <typename> class F>
class Functor {
public:
  template <typename T, typename U>
  static F<U> fmap(std::function<U(T)> f, F<T> functor);
};

But I also wanted to add some sugar so that you can create a general mapper that will map a function over any function type without pre-specifying the functor type:
template <typename T, typename U>
struct FMap {
  FMap(std::function<U(T)> f) : f_(f) {}

  template <template <typename> class F>
  F<U> operator()(F<T> functor) {
    return Functor<F>::fmap(f_, functor);
  }

private:
  std::function<U(T)> f_;
};

template <typename T, typename U>
FMap<T, U> fmap(std::function<U(T)> f) {
  return FMap<T, U>(f);
}

This works well with a simple value-wrapper functor:
template <typename T>
class Value {
public:
  Value(T value) : value_(value) {}

  const T& value() const {
    return value_;
  }

private:
  T value_;
};

template <>
template <typename T, typename U>
Value<U> Functor<Value>::fmap(std::function<U(T)> f, Value<T> value) {
  return Value<U>(f(value.value()));
}

void test() {
  std::function<std::string(int)> fn = [](int x) {
    return std::to_string(x);
  };
  auto result = fmap(fn)(Value(42));
  // result.value() == "42"
}

Now I am trying to get it to work with a more complicated type that uses std::tuple or std::variant like in the above example.
template <>
template <typename T, typename U>
Foo<U> Functor<Foo>::fmap(std::function<U(T)> f, Foo<T> value) {
  return Foo<U>(std::get<0>(value), f(std::get<1>(value)));
}

void test() {
  std::function<std::string(int)> fn = [](int x) {
    return std::to_string(x);
  };
  // This is the desirable syntax but it doesn't build
  // fmap(fn)(Foo<int>(42, 7));

  // This builds but it's super ugly
  fmap(fn).operator()<Foo>(Foo<int>(42, 7));
}

Based on the response by SkepticalEmpiricist below, I am thinking that type aliases may not be the way to go here and instead I will have to introduce small wrapper classes - unless there is an SFINAE approach that would get this working.
This library is mostly a curiosity and a means for me to explore some more advanced template concepts - thanks for the help!

A:

So first attempt before we start digging for some SFINAE based trickery to try circumvent the unavoidable:

Alias templates are never deduced by template argument deduction

We could "deduce" the template arguments for the compiler ourselves like this:
#include <tuple>

template <typename T>
using Foo = std::tuple<int, T>;

template <template <typename ...> class F, typename T, typename ...Ts>
void foo(F<T, std::string, Ts...> bar) {}

void test() {
  foo(Foo<std::string>());
}

So now we have it compiling for your foo(Foo<std::string>()); call with Foo being the alias template over std::tuple and, more importantly, foo() is still specialized only for Foo<std::string>.
However, to support usage simultaneously of foo() for both the std::tuple alias template and the wrapper class for example, we still don't have it compiling error-free. As in, if we now comment-out the tuple-flavor Foo and bring back in the wrapper class Foo then calling our rewritten foo() will not compile.
To address the issue, let's give it a try with SFINAE to the rescue and replace the last declaration of foo() with this code:
template <template <typename ...> class F, typename T, typename ...Ts,
          typename std::enable_if_t<std::is_same<F<T, Ts...>,
              std::tuple<T, Ts...>>::value >* = nullptr>
void foo(F<T, std::string, Ts...> bar) {}

template <template <typename> class F>
void foo(F<std::string> bar) {}

Now you can call foo() for instances of both wrapper class of tuples and alias template for tuples. You could implement in the same fashion for std::variant as well.


Q:

Windows 2008 R2 DHCP Question

I could use some guidance on migrating our Windows 2003 DHCP services to Windows 2008 R2.
We have two buildings:

BuildingA contains client ranges x.x.192.x and x.x.193.x, router is x.x.192.1
BuildingB contains client ranges x.x.194.x and x.x.195.x, router is x.x.194.1

We currently have four DHCP servers:

ServerA hosts range x.x.192.x (also a DC and DNS server)
ServerB hosts range x.x.193.x
ServerC hosts range x.x.194.x (also a DC and DNS server)
ServerD hosts range x.x.195.x (also a DC and DNS server)

Four hosts essentially gives us some pseudo-split-scope fail over. What I'd like to do is consolidate the four existing DHCP servers into our three new Windows 2008 servers, while maintaining some form of fail over. For example, could I do:

ServerE hosts range x.x.192.x
ServerF hosts range x.x.193.x && x.x.194.x
ServerG hosts range x.x.195.x

This way, I have two DHCP servers per building, and I don't require a fourth: I have a valid need for three, but the fourth is seemingly overkill.
Is this even possible? What would you suggest? If there's a better way, I'm very open to suggestion. Thanks in advance.

A:

There are two basic techniques here:
1) Split-scope - Some use an 80/20 or 70/30 rule, depends on how many addresses you are working with.
2) Overlapping scopes - You give the full scope to both servers. Windows DHCP will ping an address before issuing it to see if its available, you can add a "delay" to secondary servers so they don't answer for that scope before the primary. This might get messy with client side firewalls blocking ICMP.
If it were my network I'd configure the following:
Server A - Primary DNS Bldg A, Primary DHCP, Full Scopes for Building A
Server B - Secondary DNS Bldg A and Bldg B, Secondary DHCP, Full Scope for Building A with delay, 20% scopes for building B with a smaller delay (take into account WAN latency!).
Server C - Primary DNS Bldg B, Primary DHCP Bldg B 80% of scope.
Keep your DHCP helpers in order.
Tom


Q:

Adding perspective to fake 3D animation

I'm working on a canvas-based animation, and I'm trying to get a 3D effect in a 2D canvas.
So far, things are going well! I've got my "orbiting line of triangles" working very well:

var c = document.createElement('canvas');
c.width = c.height = 100;
document.body.appendChild(c);
var ctx = c.getContext("2d");

function Triangles() {
  this.rotation = {
    x: Math.random()*Math.PI*2,
    y: Math.random()*Math.PI*2,
    z: Math.random()*Math.PI*2
  };
  /* Uncomment this for testing perspective...
  this.rotation = {
    x: Math.PI/2,
    y: 0,
    z: 0
  };
  */
}
Triangles.prototype.draw = function(t) {
  this.rotation.z += t/1000;
  var i, points;
  for( i=0; i<15; i++) {
    points = [
      this.computeRotation(Math.cos(0.25*i),-Math.sin(0.25*i),0),
      this.computeRotation(Math.cos(0.25*(i+1)),-Math.sin(0.25*(i+1)),-0.1),
      this.computeRotation(Math.cos(0.25*(i+1)),-Math.sin(0.25*(i+1)),0.1)
    ];
    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.moveTo(50+40*points[0][0],50+40*points[0][1]);
    ctx.lineTo(50+40*points[1][0],50+40*points[1][1]);
    ctx.lineTo(50+40*points[2][0],50+40*points[2][1]);
    ctx.closePath();
    ctx.fill();
  }
};
Triangles.prototype.computeRotation = function(x,y,z) {
  var rz, ry, rx;
  rz = [
    Math.cos(this.rotation.z) * x - Math.sin(this.rotation.z) * y,
    Math.sin(this.rotation.z) * x + Math.cos(this.rotation.z) * y,
    z
  ];
  ry = [
    Math.cos(this.rotation.y) * rz[0] + Math.sin(this.rotation.y) * rz[2],
    rz[1],
    -Math.sin(this.rotation.y) * rz[0] + Math.cos(this.rotation.y) * rz[2]
  ];
  rx = [
    ry[0],
    Math.cos(this.rotation.x) * ry[1] - Math.sin(this.rotation.x) * ry[2],
    Math.sin(this.rotation.x) * ry[1] + Math.cos(this.rotation.x) * ry[2]
  ];
  return rx;
};

var tri = new Triangles();
requestAnimationFrame(function(start) {
  function step(t) {
    var delta = t-start;
    ctx.clearRect(0,0,100,100)
    tri.draw(delta);
    start = t;
    requestAnimationFrame(step);
  }
  step(start);
});

As you can see it's using rotation matrices for calculating the position of the points after their rotation, and I'm using this to draw the triangles using the output x and y coordinates.
I want to take this a step further by using the z coordinate and adding perspective to this animation, which will make the triangles slightly bigger when in the foreground, and smaller when in the background. However, I'm not sure how to go about doing this.
I guess this is more of a maths question than a programming one, sorry about that!

A:

Define a focal length to control the amount of perspective. The greater the value the less the amount of perspective. Then
var fl = 200; // focal length;
var px = 100; // point in 3D space
var py = 200;
var pz = 500;

Then to get the screen X,Y
var sx = (px * fl) / pz;
var sy = (py * fl) / pz;

The resulting point is relative to the center of the veiw so you need to center it to the canvas.
sx += canvas.width/2;
sy += canvas.height/2;

That is a point.
It assumes that the point being viewed is in front of the view and further than the focal length from the focal point.


Q:

For each row in Pandas dataframe, check if row contains string from list

I have a given list of strings, like that:
List=['plastic', 'carboard', 'wood']

I have a column of dtype string in my dataframe, like that:
Column=['beer plastic', 'water cardboard', 'eggs plastic', 'fruits wood']

For each row in the column, I want to know if the row contains a word from the list, and if yes, I want to keep only the text that comes before that word, like that:
New_Column=['beer', 'water', 'eggs', 'fruits']

Is there a way to systematize this for each row of my dataframe (millions of rows)? Thanks
PS. I have tried building a function with regular expression pattern matching like this
pattern=re.compile('**Pattern to be defined to include element from list**')

def truncate(row, pattern):
    Column=row['Column']
    if bool(pattern.match(Column)):
        Column=Column.replace(**word from list**,"")
        return Column

df['New_column']=df.apply(truncate,axis=1, pattern=pattern)

A:

import pandas as pd
...
for index, row in df.iterrows():
    for word in List_name:
        row['Column_name'] = row['Column_name'].partition(word)[0] if (word in row['Column_name']) else row['Column_name']

If you want to run a working example:
import pandas as pd

List=['plastic', 'carboard', 'wood']
df = pd.DataFrame([{'c1':"fun carboard", 'c2':"jolly plastic"}, {'c1':"meh wood",'c2':"aba"}, {'c1':"aaa",'c2':"bbb"}, {'c1':"old wood",'c2':"bbb"}])

for index, row in df.iterrows():
    for word in List:
        row['c1'] = row['c1'].partition(word)[0] if (word in row['c1']) else row['c1']
        row['c2'] = row['c2'].partition(word)[0] if (word in row['c2']) else row['c2']
df


Q:

How should I translate “ethnic origin” into Japanese?

I first came across this term here. I have to say, that is some fascinating information they got there.
Wikipedia has an article on the term here. Frankly, I'm not sure the article does a good job explaining it.
Fortunately, I found this article, which does a great job at explaining it, and it goes like this:
“The ancestral race that an individual belongs to, as opposed to their current nationality. People derived from of a variety of ethnic origin types currently inhabit the United States, and which include white, black, American Indian, Asian, Pacific Islander and Eskimo.”
I have looked at Weblio, and it presents some options for translating:

For “ethnic”, I could choose 民族, 民族の, 民族的な, 人種, 人種の, 人種的な, エスニック, and maybe some other terms I missed. I guess the tricky part here is deciding if “ethnic” is a noun or adjective in this context.
For “origin”, I could choose 生まれ, 系の, 素姓, オリジン, and maybe some other terms I missed. I'm not entirely sure which term would be a good choice in this context.

I would really appreciate your help.

A:

The most technical term used in the legal world that I know would be:

「民族的出自{みんぞくてきしゅつじ}」

Less formal/tecnical would include:
・「民族的ルーツ」
・「エスニシティー」
・「民族[背景]{はいけい}」
Most informal would include:
・「人種{じんしゅ}」


Q:

Solving a Quintic polynomial

The polynomial
$F(x) = x^5-9x^4+24x^3-24x^2+23x-15$
has roots $x=1$ and $x=j$. Calculate all the roots of the polynomial.
I was told I had to use radicals or similar to solve this but after reading up on it I'm still confused about how to solve it.

A:

if $F(a)=0$, then $(x-a)|F(x)$.  also, if a polynomial with real cofficients has a complex root, then the complex conjugate is also a root.  so $F$ is divisible by $(x-1)$ and $x^2+1=(x-i)(x+i)$ (according to you).  after dividing by these, you will have a polynomial of degree 2, which you can easily factor:
$$
F/(x^2+1)=x^3-9x^2+23x-15=G
$$
$$
G/(x-1)=x^2-8x+15=(x-5)(x-3)
$$
so
$$
F(x)=(x-1)(x-3)(x-5)(x^2+1)
$$


Q:

Magento2: What's the best way to add custom payment method field?

I've set up a new payment method in Magento 2 with a custom payment method field (like "po_number" from magento/offline-payment-methods). And front end is working perfectly fine (field showing up, validation, etc.).
However, if I want to place the order Magento the WebAPI request throws the following error:
"Property \"CustomField\" does not have corresponding setter in class \"Magento\Quote\Api\Data\PaymentInterface\".
It seems that Magento validates the custom field against the core payment interface where methods like getPoNumber and setPoNumber are defined.
I already tried to add the custom field via extension attributes:
<extension_attributes for="Magento\Quote\Api\Data\PaymentInterface">
    <attribute code="custom_field" type="Vendor\Module\Api\Data\MethodInterface[]" />
</extension_attributes>

and created the interface with the specific methods:
<?php
namespace Vendor\Module\Api\Data;
use Magento\Framework\Api\ExtensibleDataInterface;
interface MethodInterface extends ExtensibleDataInterface
{
    public function setCustomField($customField);
    public function getCustomField();
}

But this doesn't work. Magento still validates against the core payment interface.
The question now is, how to get Magento to accept the custom payment method field?
Any pointers are much appreciated :)

A:

Magento2 is not well-architectured here. What I did is I passed them as extension_attributes of additional_data, then assigned that information in the assignData() method so it gets persisted. Later I retrieve such information in the capture() method and use it. You can have a look here: Openpay PaymentMethod


Q:

PivotTable with a known number of columns

I have a table that looks like this
OutputTablesID    Label    ColumnOrder
  236             text          1
  236             text          2
  236             text          3
   .                .           .
   .                .           .
   .                .           .
  236             text         25

I need the table to look like this
OutputTablesID   1>>2>>3>>4>>5>>6>>7>>8>>9>>10>>11>>12>>13>>14>>15

 236>>>>>>>>>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text

I have tried code that I used from an existing pivot table I have but I cannot use Label in the aggregate function because it is a text string.
This is my attempt at the pivot table
 Create  FUNCTION [dbo].[ColOrder]
(
)

RETURNS TABLE

AS

RETURN

(
   SELECT     OutputTablesId, Label, 1,2,3,4,5,6,7,8,9,10,11,12
    from
    (
       SELECT OCL.Label, OCL.OutputTablesId
       FROM OCL
    ) AS D
    PIVOT
    (
        sum(Label)
        FOR ColumnOrder IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
    ) AS P

Thank you for your comments and suggestions!

A:

Your code is very close but you are trying to use a sum() on a varchar which will not work.  If you change the aggregate function to max() then it should work:
select OutputTablesID, [1], [2], [3], [25]
from
(
  select OutputTablesID, Label, ColumnOrder
  from yourtable
) src
pivot
(
  max(label)
  for ColumnOrder in ([1], [2], [3], [25]) -- put other ColumnOrder values here
) piv

See SQL Fiddle with Demo
If you want to create this as a function, then you can use:
create function dbo.colorder()
returns table
as
return
select OutputTablesID, [1], [2], [3], [25]
from
(
  select OutputTablesID, Label, ColumnOrder
  from yourtable
) src
pivot
(
  max(label)
  for ColumnOrder in ([1], [2], [3], [25])  -- put other ColumnOrder values here
) piv

See SQL Fiddle with Demo
The result is:
| OUTPUTTABLESID |    1 |    2 |    3 |   25 |
----------------------------------------------
|            236 | text | text | text | text |


Q:

Adding arguments when creating a function in R

I am a beginner in R. For example i have a function called w whose code is listed below:
    w<-function(x){
       a<-x+2
       plot(a)
      }

How can i add these arguments in the function so that

Export: a number equal to 0 if result should be allowed on screen and to 1 if the result should be printed in a text file.
Tfile: name of the text file where the results will be written to;
Gfile:name of the pdf file where the graph will be written to.

A:

To include further arguments in a function, simply list them in function().
w <- function(x, export, tfile, gfile) {
    a <- x + 2
    if (export == 1) {
        write.csv(a, file = tfile)
    } else if (export == 0) {
        pdf(file = gfile)
        plot(a)
        dev.off()
    }
}

For more information on writing and debugging functions in R, see this article.


Q:

Can I insert data from MySql by trigger into MongoDB?

Lets say I have a System in place which exports data into a MySQL instance. Is there a way to react to those data changes (lets say with a trigger) and write/insert that data into my MongoDB instance?
ODBC Drivers for MongoDB exist, but I'm not sure it helps me in this case.

A:

if you looking for real-time synchronization between MySQL and MongoDB then you should use tungsten-replicator for same.
you can read more about it tungsten-replicator
also, see it on git hub project.


Q:

Instantiate model from existing model in Backbone

What is the preferred way, if any, to instantiate a Backbone model from an existing model, assuming that the model to be instantiated is of a derived type of the existing model?
The case I have in mind arises when dealing with nested models. For instance, let's say I am using DeepModel and I define a function on my "parent" model that returns this.get("childModel"). Now the child model is likely of type Backbone.Model but I would like it to be of type ChildModel which extends Backbone.Model. I have been doing this by literally copying over the interesting attributes one at a time. Surely there must be a better way...

A:

You can create new instance of the same model by using Backbone.Model#clone() method or just using new model.constructor().
var ChildModel = Backbone.Model.extend({
    ...
});

var child = new ChildModel({ key: "value" });

var new_child = child.clone();

If we see the source of clone method:
clone: function() {
    return new this.constructor(this.attributes);
},

we can use the same approach to create new instance but with our data
var new_child = new child.constructor({ new_key: "new_value" });


Q:

Why doesn't this program work?

When I was working on the C Programming Language, I wanted to do a little program to revise these previous knowledge points. And this is the program which it seems there are some problems with it.
This program is supposed to collect information from input and print it in the file "reg.txt" in a format.
However, after typing the first line and press the enter, the program quits, but I can't figure it out what's wrong with it.
#include <stdio.h>

int main()
{
    FILE *fp;
    struct profile
    {
        char *name;
        char *surname;
        int year;
        int month;
        int day;
    } people[10];
    int temp;
    int i = 0;
    char *line;

    fp = fopen("reg.txt", "a");
    while (fgets(line, 256, stdin)
    {
        sscanf(line, "%s %s %d/%d/%d", people[i].name, people[i].surname, &(people[i].year), &(people[i].month), &(people[i].day));
        ++i;
    }
    temp = i-1;

    for (i = 0; i <= temp; ++i)
        fprintf(fp, "NAME: %s %s\nBIRTHDAY: %d/%d/%d\n", people[i].name, people[i].surname, people[i].year, people[i].month, people[i].day);

    fclose(fp);
    return 0;
}

I've taken Ed Heal's advice and I was aim to check the return value of 'sscanf'. What's strange is that the program doesn't really reach the 'printf' part. I thought may there are some problems with the loop?
#include <stdio.h>

int main()
{
    FILE *fp;
    void filecopy(FILE *, FILE *);
    struct profile
    {
        char *name;
        char *surname;
        int year;
        int month;
        int day;
    } people[10];
    int temp;
    int i = 0;
    char *line;
    int j;

    fp = fopen("reg.txt", "a");
    while (fgets(line, 256, stdin) != NULL)
    {
        j = sscanf(line, "%s %s %d/%d/%d", people[i].name, people[i].surname, &(people[i].year), &(people[i].month), &(people[i].day));
        ++i;
    }
    temp = i-1;

    //for (i = 0; i <= temp; ++i)
    //  fprintf(fp, "NAME: %s %s\nBIRTHDAY: %d/%d/%d\n", people[i].name, people[i].surname, people[i].year, people[i].month, people[i].day);

    printf("%d",j);
    fclose(fp);
    return 0;
}

A:

Even after making sure line has allocated memory, you should be getting a segfault on your sscanf when it tries to write to people[0].name and people[0].surname because those pointers will be undefined.
You need to allocate memory for these strings, either statically or dynamically (with malloc).
Printing log statements can also help quite a bit to gather some insight.
#include <stdio.h>

int main()
{
    FILE *fp;
    typedef struct
    {
        char name[64];
        char surname[64];
        int year;
        int month;
        int day;
    } profile;
    profile people[10];

    int temp;
    int i = 0;
    char line[512];

    printf("Starting profile line parser...\n");
    printf("Please enter up to 10 people in the format: (name surname year/month/day)\n");
    printf("Enter EOF to exit. (Linux: CTRL+D     Windows CTRL+Z)\n");
    fp = fopen("reg.txt", "a");
    while (gets(line) != NULL)
    {
        sscanf(line, "%63s %63s %d/%d/%d", people[i].name, people[i].surname, &(people[i].year), &(people[i].month), &(people[i].day));
        ++i;
    }
    printf("Processed %d lines.\n", i);
    temp = i-1;
    for (i = 0; i <= temp; ++i)
    {
        fprintf(fp, "NAME: %s %s\nBIRTHDAY: %d/%d/%d\n", people[i].name, people[i].surname, people[i].year, people[i].month, people[i].day);
    }

    fclose(fp);
    printf("Done with profile line parser...\n");
    return 0;
}

EDIT: Because gets is deprecated, here is a fgets alternative.
Further reading on gets: Why is the gets function so dangerous that it should not be used?
EDIT: Also adding chux's buffer overflow protection.
Further reading on preventing buffer overruns with scanf: Read no more than size of string with scanf()
#include <stdio.h>

int main()
{
    FILE *fp;
    typedef struct
    {
        char name[64];
        char surname[64];
        int year;
        int month;
        int day;
    } profile;
    profile people[10];

    int temp;
    int i = 0;
    char line[512];

    printf("Starting profile line parser...\n");
    printf("Please enter up to 10 people in the format: (name surname year/month/day)\n");
    printf("Enter EOF to exit. (Linux: CTRL+D     Windows CTRL+Z)\n");
    fp = fopen("reg.txt", "a");
    while (fgets(line, 512, stdin) != NULL)
    {
        sscanf(line, "%63s %63s %d/%d/%d", people[i].name, people[i].surname, &(people[i].year), &(people[i].month), &(people[i].day));
        ++i;
    }
    printf("Processed %d lines.\n", i);
    temp = i-1;
    for (i = 0; i <= temp; ++i)
    {
        fprintf(fp, "NAME: %s %s\nBIRTHDAY: %d/%d/%d\n", people[i].name, people[i].surname, people[i].year, people[i].month, people[i].day);
    }
    printf("Done with profile line parser...\n");
    fclose(fp);
    return 0;
}


Q:

How to delete profile from Workplace?

Now it seems like there has been lot of down vote lately for my answers. So Workplace won't allow me to add any more answers to questions.
So can someone give me link or steps to delete one's profile.

A:

You can delete your account if you want, but if you're interested in participating here, it would be better to tackle the problem that's causing you to be blocked right now.  If you improve some of your downvoted posts so that they can be upvoted instead, the block will go away.  The block isn't meant to be punitive; it's there to keep people from flooding sites with low-quality posts.  We're not trying to make you go away; we're trying to put a temporary stop in place so that you can make improvements and then continue participating.
Enderland has given you some specific advice on your posts.  Please consider that, and any comments you received, and look over your posts with that in mind.

A:

Here is some context you might want to know why your answers are not being received well. Looking at your answers, it seems many of them are very short, more like "here's my thoughts" and do not necessarily comprehensively answer the question.
Specifically:

https://workplace.stackexchange.com/a/34585/2322

This is relatively presumptuous and not really worded well. I have a hard time following it, as well.

https://workplace.stackexchange.com/a/34584/2322, https://workplace.stackexchange.com/a/34566/2322, https://workplace.stackexchange.com/a/34565/2322,
https://workplace.stackexchange.com/a/34563/2322

None of these really address the question very comprehensively and doesn't explain "why is this right?" This link has some good advice on how to improve your answer.

https://workplace.stackexchange.com/a/34564/2322

Again, this is only tangentially answering the question and does not explain "why"

I think if you spend some time and focus your answers on:

Answering the question
Explaining "why is this right"

Many of them will receive upvotes and be better received.
Hope this helps!


Q:

SQLiteDatabase NullPointerException while querying the DB with a SELECT statement

i'm trying to query my database to check if a matching field value exists or not.
Pretty much using a SELECT sql statement.
I'm getting an NullPointerException error when i try to query the database even though the database is already open.
The following code is from the class holds all the SQLite methods:
public long createDBCard(String card_name, String card_type, String attributeType,
            String summonRequirements, String card_description,
            String spellSpeed, int levelStars, int rankStars, int atk_stat, int def_stat,
            String setnumber, int cardNumberPass)
    {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();

    String passedCardName = card_name;
    //long l = Long.parseLong(passedCardName);
    String returnedCardName = getCardName(passedCardName);
    long numCards = Countcards();
    String numCardmsg = String.valueOf(numCards);

    if (numCards == 51){
        Toast h1 = Toast.makeText(CarddbAdapter.this, "Error counting card records.", Toast.LENGTH_LONG);
        h1.show();
    }else if(numCards == 0){
        Toast h = Toast.makeText(this, "No cards exists", Toast.LENGTH_LONG);
        h.show();
    }else if(numCards >= 1){
        Toast b = Toast.makeText(CarddbAdapter.this, returnedCardName, Toast.LENGTH_SHORT);
        b.show();
    }else{
        Toast b = Toast.makeText(CarddbAdapter.this, "FAIL!!!!!!!!!!!!!!!!!", Toast.LENGTH_SHORT);
        b.show();
    }

    cv.put(KEY_CARDNAME, card_name);
    cv.put(KEY_CARDTYPE, card_type);
    cv.put(KEY_ATTRIBUTETYPE, attributeType);
    cv.put(KEY_SUMMONREQUIREMENTS, summonRequirements);
    cv.put(KEY_CARD_DESCRIPTION, card_description);
    cv.put(KEY_SPELLSPEED, spellSpeed);
    cv.put(KEY_LEVELSTARS, levelStars);
    cv.put(KEY_RANKSTARS, rankStars);
    cv.put(KEY_ATK_STAT, atk_stat);
    cv.put(KEY_DEF_STAT, def_stat);
    cv.put(KEY_SETNUMBER, setnumber);
    cv.put(KEY_CARDNUMBERPASS, cardNumberPass);
    return ourDatabaseW.insert(DATABASE_TABLE_CARDS, null, cv);
    //return 51;
}

public String getCardName(String passedName)  throws SQLException{
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_CARDNAME};
        Cursor c = ourDatabaseR.query(DATABASE_TABLE_CARDS, columns, KEY_CARDNAME + "='" + passedName + "'", null, null, null, null);
        if (c != null){
            c.moveToFirst();
            String name = c.getString(0);
            return name;
        }
        return "hello";
    }

LogCat Error
05-11 01:15:49.456: E/AndroidRuntime(1509): FATAL EXCEPTION: main
05-11 01:15:49.456: E/AndroidRuntime(1509): java.lang.RuntimeException: Unable to start activity ComponentInfo{cybertech.productions.yugiohlibrary/cybertech.productions.yugiohlibrary.LoadingScreen}: java.lang.NullPointerException
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.os.Looper.loop(Looper.java:123)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.app.ActivityThread.main(ActivityThread.java:3683)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at java.lang.reflect.Method.invokeNative(Native Method)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at java.lang.reflect.Method.invoke(Method.java:507)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at dalvik.system.NativeStart.main(Native Method)
05-11 01:15:49.456: E/AndroidRuntime(1509): Caused by: java.lang.NullPointerException
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.widget.Toast.<init>(Toast.java:89)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.widget.Toast.makeText(Toast.java:231)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at cybertech.productions.servicehelpers.CarddbAdapter.createDBCard(CarddbAdapter.java:144)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at cybertech.productions.yugiohlibrary.LoadingScreen.onCreate(LoadingScreen.java:37)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-11 01:15:49.456: E/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
05-11 01:15:49.456: E/AndroidRuntime(1509):     ... 11 more

In one of my Activities i use an Object of the class to call the createDBCard() method.
Any help would be appreciated.
I tried playing around with the rawQuery() method but had errors, lol.

A:

I fixed it, for now to where it returns my query result.
After debugging something else related to how i designed my open() method i found out, i guess from trying different things to solve some earlier errors, i declared the context as this instead of my pre-defined private final ourContext.
Below is the first debugged code that solved my later problem with my createDBCard() method, the NullPointerException.
My open() method after i declared my private final ourContext; before the DbHelper class with the rest of my other variables:
The one coded wrong below:
public CarddbAdapter open() throws SQLException{
        ourHelper = new DbHelper(this);
        ourDatabaseW = ourHelper.getWritableDatabase();
        ourDatabaseR = ourHelper.getReadableDatabase();
        return this;
    }

The one coded right below:
public CarddbAdapter open() throws SQLException{
        ourHelper = new DbHelper(ourContext);
        ourDatabaseW = ourHelper.getWritableDatabase();
        ourDatabaseR = ourHelper.getReadableDatabase();
        return this;
    }

As you can see i changed ourHelper = new DbHelper(this); to ourHelper = new DbHelper(ourContext);
Doing this made me realize i needed to change all the Toasts in my createDBCard() to use my pre-defined ourContext instead of this.
Thanks all for trying to help.


Q:

I am unable to install adspy_shared_utilities in Anaconda using the command conda install adspy

I want to use adspy_shared_utilities package in jupyter notebook. I have Anaconda3 installed on windows 7.
I am unable to install adspy_shared_utilities in Anaconda using the command
 conda install adspy .
Error i m getting is "Following packages are not available from current channels."

A:

@neha adspy_shared_utilities is not a python library. It is actually a collection of custom functions created by the authors of Applied Machine Learning course hosted on Coursera. The adspy_shared_utilities.py source code is given below;
Copy the below code and save it as adspy_shared_utilities.py in your python working directory.
Reference: https://wmhbvoermnyeamhbufpsmv.coursera-apps.org/edit/adspy_shared_utilities.py
import numpy
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, BoundaryNorm
from sklearn import neighbors
import matplotlib.patches as mpatches
import graphviz
from sklearn.tree import export_graphviz
import matplotlib.patches as mpatches

def load_crime_dataset():
    # Communities and Crime dataset for regression
    # https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized

    crime = pd.read_table('readonly/CommViolPredUnnormalizedData.txt', sep=',', na_values='?')
    # remove features with poor coverage or lower relevance, and keep ViolentCrimesPerPop target column
    columns_to_keep = [5, 6] + list(range(11,26)) + list(range(32, 103)) + [145]
    crime = crime.ix[:,columns_to_keep].dropna()

    X_crime = crime.ix[:,range(0,88)]
    y_crime = crime['ViolentCrimesPerPop']

    return (X_crime, y_crime)

def plot_decision_tree(clf, feature_names, class_names):
    # This function requires the pydotplus module and assumes it's been installed.
    # In some cases (typically under Windows) even after running conda install, there is a problem where the
    # pydotplus module is not found when running from within the notebook environment.  The following code
    # may help to guarantee the module is installed in the current notebook environment directory.
    #
    # import sys; sys.executable
    # !{sys.executable} -m pip install pydotplus

    export_graphviz(clf, out_file="adspy_temp.dot", feature_names=feature_names, class_names=class_names, filled = True, impurity = False)
    with open("adspy_temp.dot") as f:
        dot_graph = f.read()
    # Alternate method using pydotplus, if installed.
    # graph = pydotplus.graphviz.graph_from_dot_data(dot_graph)
    # return graph.create_png()
    return graphviz.Source(dot_graph)

def plot_feature_importances(clf, feature_names):
    c_features = len(feature_names)
    plt.barh(range(c_features), clf.feature_importances_)
    plt.xlabel("Feature importance")
    plt.ylabel("Feature name")
    plt.yticks(numpy.arange(c_features), feature_names)

def plot_labelled_scatter(X, y, class_labels):
    num_labels = len(class_labels)

    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1

    marker_array = ['o', '^', '*']
    color_array = ['#FFFF00', '#00AAFF', '#000000', '#FF00AA']
    cmap_bold = ListedColormap(color_array)
    bnorm = BoundaryNorm(numpy.arange(0, num_labels + 1, 1), ncolors=num_labels)
    plt.figure()

    plt.scatter(X[:, 0], X[:, 1], s=65, c=y, cmap=cmap_bold, norm = bnorm, alpha = 0.40, edgecolor='black', lw = 1)

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)

    h = []
    for c in range(0, num_labels):
        h.append(mpatches.Patch(color=color_array[c], label=class_labels[c]))
    plt.legend(handles=h)

    plt.show()

def plot_class_regions_for_classifier_subplot(clf, X, y, X_test, y_test, title, subplot, target_names = None, plot_decision_regions = True):

    numClasses = numpy.amax(y) + 1
    color_list_light = ['#FFFFAA', '#EFEFEF', '#AAFFAA', '#AAAAFF']
    color_list_bold = ['#EEEE00', '#000000', '#00CC00', '#0000CC']
    cmap_light = ListedColormap(color_list_light[0:numClasses])
    cmap_bold  = ListedColormap(color_list_bold[0:numClasses])

    h = 0.03
    k = 0.5
    x_plot_adjust = 0.1
    y_plot_adjust = 0.1
    plot_symbol_size = 50

    x_min = X[:, 0].min()
    x_max = X[:, 0].max()
    y_min = X[:, 1].min()
    y_max = X[:, 1].max()
    x2, y2 = numpy.meshgrid(numpy.arange(x_min-k, x_max+k, h), numpy.arange(y_min-k, y_max+k, h))

    P = clf.predict(numpy.c_[x2.ravel(), y2.ravel()])
    P = P.reshape(x2.shape)

    if plot_decision_regions:
        subplot.contourf(x2, y2, P, cmap=cmap_light, alpha = 0.8)

    subplot.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold, s=plot_symbol_size, edgecolor = 'black')
    subplot.set_xlim(x_min - x_plot_adjust, x_max + x_plot_adjust)
    subplot.set_ylim(y_min - y_plot_adjust, y_max + y_plot_adjust)

    if (X_test is not None):
        subplot.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cmap_bold, s=plot_symbol_size, marker='^', edgecolor = 'black')
        train_score = clf.score(X, y)
        test_score  = clf.score(X_test, y_test)
        title = title + "\nTrain score = {:.2f}, Test score = {:.2f}".format(train_score, test_score)

    subplot.set_title(title)

    if (target_names is not None):
        legend_handles = []
        for i in range(0, len(target_names)):
            patch = mpatches.Patch(color=color_list_bold[i], label=target_names[i])
            legend_handles.append(patch)
        subplot.legend(loc=0, handles=legend_handles)

def plot_class_regions_for_classifier(clf, X, y, X_test=None, y_test=None, title=None, target_names = None, plot_decision_regions = True):

    numClasses = numpy.amax(y) + 1
    color_list_light = ['#FFFFAA', '#EFEFEF', '#AAFFAA', '#AAAAFF']
    color_list_bold = ['#EEEE00', '#000000', '#00CC00', '#0000CC']
    cmap_light = ListedColormap(color_list_light[0:numClasses])
    cmap_bold  = ListedColormap(color_list_bold[0:numClasses])

    h = 0.03
    k = 0.5
    x_plot_adjust = 0.1
    y_plot_adjust = 0.1
    plot_symbol_size = 50

    x_min = X[:, 0].min()
    x_max = X[:, 0].max()
    y_min = X[:, 1].min()
    y_max = X[:, 1].max()
    x2, y2 = numpy.meshgrid(numpy.arange(x_min-k, x_max+k, h), numpy.arange(y_min-k, y_max+k, h))

    P = clf.predict(numpy.c_[x2.ravel(), y2.ravel()])
    P = P.reshape(x2.shape)
    plt.figure()
    if plot_decision_regions:
        plt.contourf(x2, y2, P, cmap=cmap_light, alpha = 0.8)

    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold, s=plot_symbol_size, edgecolor = 'black')
    plt.xlim(x_min - x_plot_adjust, x_max + x_plot_adjust)
    plt.ylim(y_min - y_plot_adjust, y_max + y_plot_adjust)

    if (X_test is not None):
        plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cmap_bold, s=plot_symbol_size, marker='^', edgecolor = 'black')
        train_score = clf.score(X, y)
        test_score  = clf.score(X_test, y_test)
        title = title + "\nTrain score = {:.2f}, Test score = {:.2f}".format(train_score, test_score)

    if (target_names is not None):
        legend_handles = []
        for i in range(0, len(target_names)):
            patch = mpatches.Patch(color=color_list_bold[i], label=target_names[i])
            legend_handles.append(patch)
        plt.legend(loc=0, handles=legend_handles)

    if (title is not None):
        plt.title(title)
    plt.show()

def plot_fruit_knn(X, y, n_neighbors, weights):
    X_mat = X[['height', 'width']].as_matrix()
    y_mat = y.as_matrix()

    # Create color maps
    cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#AFAFAF'])
    cmap_bold  = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#AFAFAF'])

    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    clf.fit(X_mat, y_mat)

    # Plot the decision boundary by assigning a color in the color map
    # to each mesh point.

    mesh_step_size = .01  # step size in the mesh
    plot_symbol_size = 50

    x_min, x_max = X_mat[:, 0].min() - 1, X_mat[:, 0].max() + 1
    y_min, y_max = X_mat[:, 1].min() - 1, X_mat[:, 1].max() + 1
    xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, mesh_step_size),
                         numpy.arange(y_min, y_max, mesh_step_size))
    Z = clf.predict(numpy.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot training points
    plt.scatter(X_mat[:, 0], X_mat[:, 1], s=plot_symbol_size, c=y, cmap=cmap_bold, edgecolor = 'black')
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    patch0 = mpatches.Patch(color='#FF0000', label='apple')
    patch1 = mpatches.Patch(color='#00FF00', label='mandarin')
    patch2 = mpatches.Patch(color='#0000FF', label='orange')
    patch3 = mpatches.Patch(color='#AFAFAF', label='lemon')
    plt.legend(handles=[patch0, patch1, patch2, patch3])

    plt.xlabel('height (cm)')
    plt.ylabel('width (cm)')

    plt.show()

def plot_two_class_knn(X, y, n_neighbors, weights, X_test, y_test):
    X_mat = X
    y_mat = y

    # Create color maps
    cmap_light = ListedColormap(['#FFFFAA', '#AAFFAA', '#AAAAFF','#EFEFEF'])
    cmap_bold  = ListedColormap(['#FFFF00', '#00FF00', '#0000FF','#000000'])

    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    clf.fit(X_mat, y_mat)

    # Plot the decision boundary by assigning a color in the color map
    # to each mesh point.

    mesh_step_size = .01  # step size in the mesh
    plot_symbol_size = 50

    x_min, x_max = X_mat[:, 0].min() - 1, X_mat[:, 0].max() + 1
    y_min, y_max = X_mat[:, 1].min() - 1, X_mat[:, 1].max() + 1
    xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, mesh_step_size),
                         numpy.arange(y_min, y_max, mesh_step_size))
    Z = clf.predict(numpy.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot training points
    plt.scatter(X_mat[:, 0], X_mat[:, 1], s=plot_symbol_size, c=y, cmap=cmap_bold, edgecolor = 'black')
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    title = "Neighbors = {}".format(n_neighbors)
    if (X_test is not None):
        train_score = clf.score(X_mat, y_mat)
        test_score  = clf.score(X_test, y_test)
        title = title + "\nTrain score = {:.2f}, Test score = {:.2f}".format(train_score, test_score)

    patch0 = mpatches.Patch(color='#FFFF00', label='class 0')
    patch1 = mpatches.Patch(color='#000000', label='class 1')
    plt.legend(handles=[patch0, patch1])

    plt.xlabel('Feature 0')
    plt.ylabel('Feature 1')
    plt.title(title)

    plt.show()


Q:

How to specify JSON node property values when parsing/iterating in Azure Logic Apps?

TL;DR How do I specify a specific JSON node property within Azure Logic Apps' ParseJSON > For Each step, when the designer only gives me access to the parent nodes?
I'm building a Logic App that:

Receives and parses a list of people as JSON data from an external system
Constructs a new JSON file with different structure
Posts the new file to a second external system

The JSON response from item 1 has this structure:
{
    "Success": true,
    "Message": "Completed",
    "Result": [
        {
            "EmployeeId": {
                "DisplayValue": "PW123",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        {
            "EmployeeId": {
                "DisplayValue": "PW789",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        .... removed for brevity
    ]
}

Within the designer, if I add a Data Operations > Parse JSON > For Each step, it lets me specify the properties, but at too high a level:

Notice the designer gives me EmployeeId, but I actually need EmployeeId.DisplayValue, which is both properties and their values in JSON format, rather than a simple string containing only the EmployeeId or EmailId values.
Can the JSON be read at the deeper level I require using the designer?

A:

If I am not mistaken you can do something in the lines of Parse_JSON()['EmployeeId']['DisplayValue'] <-- this is probably not the exact match, but the syntax is something like that.
They way you do this is that you either write it in code view or in the designer you start on an expression, add the blanks with dynamic content and finish by adding the ['DisplayValue'] tag.


Q:

Vk Streaming API добавления правил PHP

Здравствуйте, относительно недвано Вконтакте открыла Streaming API, но информации по ней не много 2 статьи на хабре, и документация с примерами использования на Go. С получением правил я разобрался:
function GetRules($end_point, $stream_key)
{
    $resp = 'https://'.$end_point.'/rules?key='.$stream_key;
    $resp = file_get_contents($resp);
    $resp = json_decode($resp, true);
    return $resp;
}

Но вот с добавлением правил я не понял, вот документация, и статья на хабре. Но я не понимаю как именно отправить запрос на добавление именно с  PHP и какая ссылка запроса? Прошу помочь.

A:

Ждал я ответа, и пока ждал разобрался. Вопрос не стал закрывать т.к. это относительна новая вещь и информации по ней мало. Вот код
function SetRules($end_point, $stream_key, $value, $tag)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://'.$end_point.'/rules?key='.$stream_key);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '{"rule":{"value":"'.$value.'","tag":"'.$tag.'"}}');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    $out = curl_exec($ch);
    curl_close($ch);

    echo $out; //здесь вам вернеться код 200/400 по желанию делайте return для проверки из-вне
}

Пример вызова:
SetRules('streaming.vk.com', '1234', 'test', '1');

streaming.vk.com — хост для подключения к серверу.
1234 — ключ доступа. Ключ бессрочный и прекращает действовать только после получения нового ключа.
test — Значение для правила.
1 — Тег.


Q:

How to emulate _mm256_loadu_epi32 with gcc or clang?

Intel's intrinsic guide lists the intrinsic _mm256_loadu_epi32:
_m256i _mm256_loadu_epi32 (void const* mem_addr);
/*
   Instruction: vmovdqu32 ymm, m256
   CPUID Flags: AVX512VL + AVX512F
   Description
       Load 256-bits (composed of 8 packed 32-bit integers) from memory into dst.
       mem_addr does not need to be aligned on any particular boundary.
   Operation
   a[255:0] := MEM[mem_addr+255:mem_addr]
   dst[MAX:256] := 0
*/

But clang and gcc do not provide this intrinsic. Instead they provide (in file avx512vlintrin.h) only the masked versions
_mm256_mask_loadu_epi32 (__m256i, __mmask8, void const *);
_mm256_maskz_loadu_epi32 (__mmask8, void const *);

which boil down to the same instruction vmovdqu32. My question: how can I emulate _mm256_loadu_epi32:
 inline _m256i _mm256_loadu_epi32(void const* mem_addr)
 {
      /* code using vmovdqu32 and compiles with gcc */
 }

without writing assembly, i.e. using only intrinsics available?

A:

Just use _mm256_loadu_si256 like a normal person.  The only thing the AVX512 intrinsic gives you is a nicer prototype (const void* instead of const __m256i*).
@chtz suggests out that you might still want to write a wrapper function yourself to get the void* prototype.  But don't call it _mm256_loadu_epi32; some future GCC version will probably add that for compat with Intel's docs and break your code.

You don't even want the compiler to emit vmovdqu32 ymm when you're not masking; vmovdqu ymm is shorter and does exactly the same thing, with no penalty for mixing with EVEX-encoded instructions.  The compiler can always use an vmovdqu32 or 64 if it wants to load into ymm16..31, otherwise you want it to use a shorter VEX-coded AVX1 vmovdqu.
I'm pretty sure that GCC treats _mm256_maskz_epi32(0xffu,ptr) exactly the same as _mm256_loadu_si256((const __m256i*)ptr) and makes the same asm regardless of which one you use.  It can optimize away the 0xffu mask and simply use an unmasked load, but there's no need for that extra complication in your source.
But unfortunately current GCC will pessimize to vmovdqu32 ymm0, [mem] when AVX512VL is enabled (e.g. -march=skylake-avx512) even when you write _mm256_loadu_si256.  This is a missed-optimization, GCC Bug 89346.
It doesn't matter which 256-bit load intrinsic you use (except for aligned vs. unaligned) as long as there's no masking.
Related:

error: '_mm512_loadu_epi64' was not declared in this scope
What is the difference between _mm512_load_epi32 and _mm512_load_si512?


Q:

What is smallest way to split object into array of object based on key/value pairs in Javascript?

I've got this object:
var obj = {
    family : [{name: 'will', age: 30}, {name: 'husain', age: 12}],
    friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}],
    school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]
}

convert it into this
var obj = [
    {family : [{name: 'will', age: 30}, {name: 'husain', age: 12}]},
    {friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}]},
    {school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]}
];

Write now I am using for..in to build a new array and create object with key as key for new object and so on.
I'm doing this right now
var arr = [];

for (let key in obj) {
    arr.push({key: obj[key]})
}

A:

I think Object.keys is your best option:

var obj = {
    family : [{name: 'will', age: 30}, {name: 'husain', age: 12}],
    friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}],
    school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]
}
var r = Object.keys(obj).map(x => ({[x]: obj[x]}) )

console.log(r)


Q:

C++ Storing the product of two random numbers

C++ question this time.
I'm trying to store the product between two random numbers... It's supposed to be asking what the product between two random numbers that generate based on srand(time(0)), and quitting after -1 is entered...
The following is my code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;

#include <cstdlib>
using std::rand;
using std::srand;

#include <ctime>
using std::time;

int multiplication()
{
    srand( time(0));
    int x = 0;

    while (x != -1)
    {
        int random_int;
        random_int = (rand()%10 * rand()%10);
        cout << "(Enter -1 to quit) \n";
        cout << "" << rand() % 10 << " multiplied by " << rand() % 10 <<"? \n";
        cin >> x;

        if(x == random_int)
        {
            cout << "you're right!" << endl;
        }
        else
        {
            cout << "you're wrong" << endl;
        }
    }
    return 0;
}

int main()
{
    multiplication();
}

A:

You are generating two random number to calculate the answer, and the other two different random numbers to ask the question. Chances are that they will be different!
So:
int a = rand()%10, b = rand()%10;
int random_int = a*b;
//...
cout << a << " multiplied by " << b <<"? \n";

BTW, your code has quite a few style defects...

Do not call srand() from a function. Usually it should be called from main.
If a function returns int, then return an int that means anything. If not, return void.
Check that the user input is valid: if (!(cin >> x)) or similar.
Use endl consistently.
Why the cout << ""?. It looks like a Java idiom, but in C++ does nothing.

A:

You shoud pay attention to operator precedence. Modulo operator % has the same precedence as multiplication *. Therefore when you write
rand()%10 * rand()%10

c++ will interpret that as
((rand()%10) * rand()) % 10

in other words the last modulo is applied to the result of everything else.
If you want to multiply two random numbers between 0 and 9 you should use instead
(rand() % 10) * (rand() % 10)

where the extra parenthesis ensure the correct computation sequence.


Q:

spring & web service client - Fault Detail

How could I get the Fault Detail sent by a SoapFaultClientException ?
I use a WebServiceTemplate as shown below :
WebServiceTemplate ws = new WebServiceTemplate();
ws.setMarshaller(client.getMarshaller());
ws.setUnmarshaller(client.getUnMarshaller());
try {
    MyResponse resp = (MyResponse) = ws.marshalSendAndReceive(WS_URI, req);
} catch (SoapFaultClientException e) {
     SoapFault fault =  e.getSoapFault();
     SoapFaultDetail details = e.getSoapFault().getFaultDetail();
      //details always NULL ? Bug?
}

The Web Service Fault sent seems correct :
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
  <soapenv:Fault>
     <faultcode>soapenv:Client</faultcode>
     <faultstring>Validation error</faultstring>
     <faultactor/>
     <detail>
        <ws:ValidationError xmlns:ws="http://ws.x.y.com">ERR_UNKNOWN</ws:ValidationError>
     </detail>
  </soapenv:Fault>
</soapenv:Body>

Thanks
Willome

A:

I also had the problem that getFaultDetail() returned null (for a SharePoint web service). I could get the detail element out by using a method similar to this:
private Element getDetail(SoapFaultClientException e) throws TransformerException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMResult result = new DOMResult();
    transformer.transform(e.getSoapFault().getSource(), result);
    NodeList nl = ((Document)result.getNode()).getElementsByTagName("detail");
    return (Element)nl.item(0);
}

After that, you can call getTextContent() on the returned Element or whatever you want.

A:

Check out what type of HTTP response you get when receiving Soap Fault. I had the same problem when SOAP Fault responses using HTTP 200 instead of HTTP 500. Then you get:

JAXB unmarshalling exception; nested exception is
  javax.xml.bind.UnmarshalException

When you change WebServiceTemplate connection fault settings as below:
WebServiceTemplate webServiceTemplate = getWebServiceTemplate();
webServiceTemplate.setCheckConnectionForFault(false);

then you can properly catch SoapFaultClientException


Q:

Perl: adding matching strings in RE

Here is a perl RE that will increment a number in angle brackets.
echo "aaa build<23>bbb')"|perl -p -e 's/^(.*build<)(\d+)(>.*)$/$2 + 1/e;'
24

How can I get this effect and also keep the contents of the line before and after the angle brackets? Just adding $1 and $3 does not work.
echo "aaa build<23>bbb')"|perl -p -e 's/^(.*build<)(\d+)(>.*)$/$1$2 + 1$3/e;'
Scalar found where operator expected at -e line 1, near "$1$2"
    (Missing operator before $2?)
Scalar found where operator expected at -e line 1, near "1$3"
    (Missing operator before $3?)
syntax error at -e line 1, near "$1$2 "

A:

You can use captured groups like this:
echo "aaa build<23>bbb')"|perl -pe 's/^(.*build<)(\d+)(>.*)$/$1 . ($2+1) . $3/e;'
aaa build<24>bbb')

Concatenate string variables using DOT
Do math operations using +`


Q:

How to replace 'show' with 'download' in rails routes?

This is driving me crazy. Rails is saying I don't have a controller action defined, but I clearly do in rake routes.
What am I missing here?
spec/controllers/api/v1/files_controller_spec.rb:
 describe "download action" do
   after do
     get :download, id: file.id
   end

   it "returns http status 200 OK" do
     expect(response).to have_http_status(200)
   end
 end

Failure message of no route matches action download:
 Failures:

   1) Api::V1::FilesController download action returns http status 200 OK
      Failure/Error: get :download, id: file.id

      ActionController::UrlGenerationError:
        No route matches {:action=>"download", :controller=>"api/v1/files", :id=>"2"}

config/routes.rb:
  namespace :api, defaults: { format: :json }  do
    namespace :v1 do
      resources :files, only: [:index, :create]
      get "files/:id", to: "file#download", as: "file"

    end
  end

rake routes | grep file:
     api_v1_files  GET   /api/v1/files(.:format)         api/v1/files#index {:format=>:json}
                   POST  /api/v1/files(.:format)         api/v1/files#create {:format=>:json}
       api_v1_file GET   /api/v1/files/:id(.:format)     api/v1/file#download {:format=>:json}

A:

You can add more routes to a resource with a block like so:
resources :files, only: [:index, :create] do
  member do
    get 'download'
  end
end


Q:

Unnaming a range in VB blows up (Excel 2003, VB 6.5)

I am trying to unname a range if cells if it exists. The code below finds the range with the right name, but explodes at nm.Delete line, without any explanation. How can I fix/debug it?
Thanks!
Function unefineRange(strRgeName As String)
    Dim nm As Name
    For Each nm In ThisWorkbook.Names
        If nm.Name = strRgeName Then
            nm.Delete
        End If
    Next nm
End Function

A:

I just ran this in Excel 2003 and it ran fine:
I created two named ranges, Fred and Wilma, and ran this (module 1) in the Visual Basic editor. Deleted "Wilma" with no problems.
Function undefineRange(strRgeName As String)
    Dim nm As Name
    For Each nm In ThisWorkbook.Names
        If nm.Name = strRgeName Then
            nm.Delete
        End If
    Next nm
End Function

Sub unDefineRangePlease()
   undefineRange ("Wilma")
End Sub


Q:

GCP apt-get install and update stopped working properly

I have 2 compute engine instances:
One is running for about half a year, today for the first time I get:
Err:11 http://packages.cloud.google.com/apt google-cloud-packages-archive-keyring-stretch InRelease The following signatures couldn't be verified because the public key is not available:

Another I just setup today from a clean Debian 9 image, and it doesn't let me apt-get install anything:
E: Unable to locate package php7.2-fpm
E: Couldn't find any package by glob 'php7.2-fpm'
E: Couldn't find any package by regex 'php7.2-fpm'

Didn't have that before.

A:

Regarding the second issue I believe you have to run:
$ apt-get update

apt-get update:
  Used to re-synchronize the package index files from their sources. The indexes of available packages are fetched from the location(s) specified in /etc/apt/sources.list. An update should always be performed before an upgrade or dist-upgrade.

Sometimes the packages you are interested into are not part of the standard source.list and you need to add the sources carefully doublechecking them.
For example for php7.2-fpm you need to update them:
sudo apt install apt-transport-https lsb-release ca-certificates
sudo wget -O /etc/apt/trusted.gpg.d/php.gpg
https://packages.sury.org/php/apt.gpg
sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
sudo apt update
sudo apt install php7.2 php7.2-common php7.2-cli php7.2-fpm

Regarding the first issue: it has been a temporary problem for Google Compute engine, now everything should be back to normal behaviour, but if it is not the case you can force a manual update of the old key running:
$ curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -


Q:

Getting info out of each loop for use in the next without terminating the loop (Python)

I'm sorry if this is asked elsewhere, but what searching I did didn't bring up the info I needed and I didn't quite know what other keywords to use to search further.  Please understand that I'm quite new to programming.
OK, now onto business.  I have two for loops set up.  The first cycles through a list and concatenates it with a couple of other strings inputted through variables.  The second takes the string made in the first loop and concatenates data from a different loop onto it.  However, when I execute the function, the second loop only uses the last result from the previous loop rather than attaching the data to all the strings formed from the first loop.  Here's an example:
j=0
k=0
for j in xrange(0, 2):
        for k in xrange(0, 2):
                first=(a + sign[k] + b)
                k = k+1
        second=(first + sign[j] + c)
        print(second)
        j = j+1

where a, b, c, and sign[] are variables.
The output I want is:
a + sign[0] + b + sign[0] + c
a + sign[1] + b + sign[0] + c
a + sign[0] + b + sign[1] + c
a + sign[1] + b + sign[1] + c

The output I get is:
a + sign[1] + b + sign[0] + c
a + sign[1] + b + sign[1] + c

(Well, I'm going to be using more values, but that's the general gist of it)
Is there any way I can get the data out of the first loop without stopping it for use in the second loop to make a list such as this, i.e. get the code to use sign[0] in the first instance and not just sign[1]?  Also, I would just like to reiterate that I'm quite new to coding, so please bear that in mind when responding!

A:

You need to print the elements in the inner loop, this way you print for each different value of j and k.
Also note, you don't need to manually increase j and k - it is taken care of by itself, since it is the loop variable of your for-each loop.
You could also change the size of the list, which is currently hardcoded to be 2 - to be more flexible using the len() function:
>>> for j in xrange(0,len(sign)):
...   for k in xrange(0,len(sign)):
...     first = a + sign[k] + b
...     second = first + sign[j] + c
...     print(second)
...

Output (I set a='a',b='b',c='c',sign=['0','1'])
a0b0c
a1b0c
a0b1c
a1b1c


Q:

Integrating ANTLR 4 in a C++ application

Recently I picked up a copy of The Definitive ANTLR 4 Reference and since I am sophisticated when it comes to working with grammars and languages I wanted to work on my DSL I once have written using yacc and bison. The general idea is to write a translator (with included validation for type safety(1)) which translates the DSL to JavaScript during runtime which is then executed by v8.
Although ANTLR was designed for inclusion in Java applications I would like to stay with native C++. Can ANTLR 4 produce such a C parser/lexer(2) which I can include using a C++-style wrapper? And how to do so?

(1) The book has some good examples which I will use as a template.
(2) I am not sure but I think that I read somewhere that ANTLR doesn't support output in C++, am I right?

A:

I found the ANTLR 3 C/C++ target almost unusable.  It contains so many hacks to circumvent the lack of exceptions in C that it was recommended for experts only.  Though it's Terr's call, I hope ANTLR 4 doesn't support target languages without native exceptions unless it can isolate whatever hackery is required to do so from end users.  The ANTLR 2 C++ target is cleaner than ANTLR 3's, but ANTLR 2 itself has limitations, including extremely messy licensing (making it difficult to use in commercial products).

A:

ANTLR v3 has various different targets, most notably Java (of course), C, C#, JavaScript and Python. For a full list, see: http://www.antlr.org/wiki/display/ANTLR3/Code+Generation+Targets
ANTLR v4, however, only has a Java target at this moment.

A:

In case you are still interested, version 4.7 of antlr does have a c++ target.