text:
Q: Turret firing the wrong way when I tap the left side of the screen I am rather new at all of this so I apologize if this is a terribly ignorant question.  I am attempting to make a turret that will rotate to face a tap and fire in that direction.  Some code was found in a tutorial for Ray Wenderlich's rotating turrets and I moved the turret to the bottom center of the screen and also relocated the starting point of the projectiles to the same point. This position is more akin to old missle command style games.
Unfortunately now the weapon fires correctly when I tap the right side of the screen but when I tap the left it fires down and to the right off screen, like it is flipping the command somehow.  Can anyone help me straighten this out?  Is there perhaps an alternate way to code this so that I won't have the left firing issue or do I need to input something additional to translate the coordinates so the taps register properly?
// Import the interfaces
#import "HelloWorldLayer.h"
#import "SimpleAudioEngine.h"
#import "GameOverLayer.h"
#import "Monster.h"
#import "LevelManager.h"

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"

#pragma mark - HelloWorldLayer

// HelloWorldLayer implementation
@implementation HelloWorldLayer

// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];

    // 'layer' is an autorelease object.
    HelloWorldLayer *layer = [HelloWorldLayer node];

    // add layer as a child to scene
    [scene addChild: layer];

// return the scene
return scene;
}

- (void) addMonster {

    //CCSprite * monster = [CCSprite spriteWithFile:@"monster.png"];
    Monster * monster = nil;
    if (arc4random() % 2 == 0) {
        monster = [[[WeakAndFastMonster alloc] init] autorelease];
    } else {
        monster = [[[StrongAndSlowMonster alloc] init] autorelease];
    }

    // Determine where to spawn the monster along the Y axis
    CGSize winSize = [CCDirector sharedDirector].winSize;
    int minY = monster.contentSize.height / 2;
    int maxY = winSize.height - monster.contentSize.height/2;
    int rangeY = maxY - minY;
    int actualY = (arc4random() % rangeY) + minY;

    // Create the monster slightly off-screen along the right edge,
    // and along a random position along the Y axis as calculated above
    monster.position = ccp(winSize.width + monster.contentSize.width/2, actualY);
    [self addChild:monster];

    // Determine speed of the monster
    int minDuration = monster.minMoveDuration; //2.0;
    int maxDuration = monster.maxMoveDuration; //4.0;
    int rangeDuration = maxDuration - minDuration;
    int actualDuration = (arc4random() % rangeDuration) + minDuration;

    // Create the actions
    CCMoveTo * actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(-monster.contentSize.width/2, actualY)];
    CCCallBlockN * actionMoveDone = [CCCallBlockN actionWithBlock:^(CCNode *node) {
        [_monsters removeObject:node];
        [node removeFromParentAndCleanup:YES];

        CCScene *gameOverScene = [GameOverLayer sceneWithWon:NO];
        [[CCDirector sharedDirector] replaceScene:gameOverScene];
    }];
    [monster runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];

    monster.tag = 1;
    [_monsters addObject:monster];

}

-(void)gameLogic:(ccTime)dt {
    [self addMonster];
}

- (id) init
{
    if ((self = [super initWithColor:[LevelManager sharedInstance].curLevel.backgroundColor])) {

        CGSize winSize = [CCDirector sharedDirector].winSize;
        _player = [CCSprite spriteWithFile:@"player2.png"];
        _player.position = ccp(winSize.width/2, 20);
        [self addChild:_player];

        [self schedule:@selector(gameLogic:) interval:[LevelManager sharedInstance].curLevel.secsPerSpawn];

        [self setTouchEnabled:YES];

        _monsters = [[NSMutableArray alloc] init];
        _projectiles = [[NSMutableArray alloc] init];

        [self schedule:@selector(update:)];

        [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"background-music-aac.caf"];

    }
    return self;
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if (_nextProjectile != nil) return;

    // Choose one of the touches to work with
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace:touch];

    // Set up initial location of projectile
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    _nextProjectile = [[CCSprite spriteWithFile:@"projectile2.png"] retain];
    _nextProjectile.position = ccp(winSize.width/2, 20);

    // Determine offset of location to projectile
    CGPoint offset = ccpSub(location, _nextProjectile.position);

    // Bail out if you are shooting down or backwards
    //if (offset.x <= 0) return;

    // Determine where you wish to shoot the projectile to
    int realX = winSize.width + (_nextProjectile.contentSize.width/2);
    float ratio = (float) offset.y / (float) offset.x;
    int realY = (realX * ratio) + _nextProjectile.position.y;
    CGPoint realDest = ccp(realX, realY);

    // Determine the length of how far you're shooting
    int offRealX = realX - _nextProjectile.position.x;
    int offRealY = realY - _nextProjectile.position.y;
    float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
    float velocity = 480/1; // 480pixels/1sec
    float realMoveDuration = length/velocity;

    // Determine angle to face
    float angleRadians = atanf((float)offRealY / (float)offRealX);
    float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
    float cocosAngle = -1 * angleDegrees;
    float rotateDegreesPerSecond = 180 / 0.5; // Would take 0.5 seconds to rotate 180 degrees, or half a circle
    float degreesDiff = _player.rotation - cocosAngle;
    float rotateDuration = fabs(degreesDiff / rotateDegreesPerSecond);
    [_player runAction:
     [CCSequence actions:
      [CCRotateTo actionWithDuration:rotateDuration angle:cocosAngle],
      [CCCallBlock actionWithBlock:^{
         // OK to add now - rotation is finished!
         [self addChild:_nextProjectile];
         [_projectiles addObject:_nextProjectile];

         // Release
         [_nextProjectile release];
         _nextProjectile = nil;
     }],
      nil]];

    // Move projectile to actual endpoint
    [_nextProjectile runAction:
     [CCSequence actions:
      [CCMoveTo actionWithDuration:realMoveDuration position:realDest],
      [CCCallBlockN actionWithBlock:^(CCNode *node) {
         [_projectiles removeObject:node];
         [node removeFromParentAndCleanup:YES];
    }],
      nil]];

    _nextProjectile.tag = 2;

    [[SimpleAudioEngine sharedEngine] playEffect:@"pew-pew-lei.caf"];
}

- (void)update:(ccTime)dt {

    NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
    for (CCSprite *projectile in _projectiles) {

        BOOL monsterHit = FALSE;
        NSMutableArray *monstersToDelete = [[NSMutableArray alloc] init];
        for (Monster *monster in _monsters) {

            if (CGRectIntersectsRect(projectile.boundingBox, monster.boundingBox)) {
                monsterHit = TRUE;
                monster.hp --;
                if (monster.hp <= 0) {
                    [monstersToDelete addObject:monster];
                }
                break;
            }
        }

        for (CCSprite *monster in monstersToDelete) {

            [_monsters removeObject:monster];
            [self removeChild:monster cleanup:YES];

            _monstersDestroyed++;
            if (_monstersDestroyed > 30) {
                CCScene *gameOverScene = [GameOverLayer sceneWithWon:YES];
                [[CCDirector sharedDirector] replaceScene:gameOverScene];
            }
        }

        if (monsterHit) {
            [projectilesToDelete addObject:projectile];
            [[SimpleAudioEngine sharedEngine] playEffect:@"explosion.caf"];
        }
        [monstersToDelete release];
    }

    for (CCSprite *projectile in projectilesToDelete) {
        [_projectiles removeObject:projectile];
        [self removeChild:projectile cleanup:YES];
    }
    [projectilesToDelete release];
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
    [_monsters release];
    _monsters = nil;
    [_projectiles release];
    _projectiles = nil;
    [super dealloc];
}
@end

A: I'd say you should replace your atanf with atan2f, i.e. replace
float angleRadians = atanf((float)offRealY / (float)offRealX);

with (notice that atan2f accepts Y and X separately!)
float angleRadians = atan2f((float)offRealY, (float)offRealX);

Have a look at Wikipedia article about atan2. You will see that from 0-PI/2 atanf and atan2f will give you the same result. However, as soon as you go from PI/2 towards PI, you will get negative angles using atanf while atan2f will produce correct angles.

A: I had a look at your code again and noticed other problems as well. I have changed the following pieces:

*

*"bail out" condition when shooting below (note the order change because otherwise you won't be getting shots after a bailout condition is met for the first time!)

*calculation of realY and realX - you left the code from Ray's tutorial and set the target position to always be on the right side, while in the code below it is always at the top

*removed atan/atan2 functions and used ccpToAngle(ccp(offRealX, offRealY)) instead

Below is the part of code that has changed. If you need, I can share the whole modified project but it should suffice to replace the beginning of your ccTouchesEnded method.
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_nextProjectile != nil) return;

    CGSize winSize = [[CCDirector sharedDirector] winSize];

    // Choose one of the touches to work with
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace:touch];

    CGPoint targetPosition = ccp(winSize.width / 2, 20);

    // Determine offset of location to projectile
    CGPoint offset = ccpSub(location, targetPosition);

    // Bail out if you are shooting down or backwards
    if (offset.y <= 0)
    {
    return;
    }

    // Set up initial location of projectile
    _nextProjectile = [[CCSprite spriteWithFile:@"projectile2.png"] retain];
    _nextProjectile.position = targetPosition;

    // Determine where you wish to shoot the projectile to
    int realY = winSize.height + (_nextProjectile.contentSize.height/2);
    float ratio = (float) offset.x / (float) offset.y;
    int realX = (realY * ratio) + _nextProjectile.position.x;
    CGPoint realDest = ccp(realX, realY);

    // Determine the length of how far you're shooting
    int offRealX = realX - _nextProjectile.position.x;
    int offRealY = realY - _nextProjectile.position.y;
    float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
    float velocity = 480/1; // 480pixels/1sec
    float realMoveDuration = length/velocity;

    // Determine angle to face
    float angleRadians = ccpToAngle(ccp(offRealX, offRealY));


text:
Q: Angular Ionic back button only working after I slide the pointer on It So basically, I have this simple code that should be working fine but for some reason I'm getting a rare bug.
I have a page called "home" and a sidemenu which I use to navigate to the page "mysports". When It first loads the page "mysports", it displays the ion-back-button, but whenever I try to click it, it doesn't work. When I click the ion-back-button and slide it to the left, the HTML refreshes and the ion-back-button works perfectly fine.
On my html I have this code:
<ion-header>
  <ion-toolbar>
     <ion-buttons>
        <ion-back-button text="Back"></ion-back-button>
        <ion-label>
          <ion-title class="ion-text-center">spoRts</ion-title>
        </ion-label>
     </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content>

</ion-content>

I don't have anything else only this. Didn't even touch the mysports.page.ts file.

A: You can try to put "defaultHref="your_route" inside the ion-back-button tag like this:
<ion-buttons slot="start">
    <ion-back-button defaultHref="contacts"></ion-back-button>
</ion-buttons>

I hope to help you, regards.

A: the structure of your header is wrong. When he's not right he does rare bugs. you must change it for the following:
<ion-header>
    <ion-toolbar>
        <ion-buttons slot="start">
            <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>spoRts</ion-title>
    </ion-toolbar>
</ion-header>

additionally if you want to change the text of the backbutton you can do it globally on app.module.ts:
        IonicModule.forRoot({
            backButtonText: 'Back',
            backButtonIcon: 'arrow-back-outline',
        }),

redpajama_set_name: RedPajamaStackExchange


text:
Q: How changes packet relating to Idr packet in h264 over rtp? I read  RTP Payload Format for H.264 Video RFC , if I uderstand well in video flow there are sps and pps packets(meta data) then Idr (full image) and then changes packet between last idr to current state, and again from the beginning.
I know that for each rtp packet header that wrap h264 data has sequence number .
What I don't understand , Is to changes packets (that came between Idr packets) how do they know to each Idr they relate ?
Is there in h264  header/data that write to which rtp sequence number or h264 sequence number they relate?

A: Yes. Every slice has a slice header. It's documented in iso 14496-10.


text:
Q: Create List of Words that Appear In String Without Spaces - Account For When Word Appears More Than Once As per this Codewars challenge, I need to create some simple logic for keeping track of all of the words that appear in a string.

INSTRUCTIONS
Some new cashiers started to work at your restaurant.
They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
All the orders they create look something like this:
"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"
The kitchen staff are threatening to quit, because of how difficult it is to read the orders.
Their preference is to get the orders as a nice clean string with spaces and capitals like so:
"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"
The kitchen staff expect the items to be in the same order as they appear in the menu.
The menu items are fairly simple, there is no overlap in the names of the items:

*

*Burger

*Fries

*Chicken

*Pizza

*Sandwich

*Onionrings

*Milkshake

*Coke

EDIT Following the .match() logic, I've created an array of all items that appear in the input. But I don't know the quickest way to sort them according to their order of appearance in the original string:

function getOrder(order) {

  let menu = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke'];

  let finalOrder = order.split(/(burger|fries|chicken|pizza|sandwich|onionrings|milkshake|coke)/i);
  finalOrder = finalOrder.filter((element) => element !== null || element !== "");
  finalOrder = finalOrder.map((element) => element.charAt(0).toUpperCase() + element.slice(1));
  finalOrder = finalOrder.sort((a, b) => {
    if (menu.indexOf(a) > menu.indexOf(b)) {
      return 1;
    }
    else {
      return -1;
    }
  });
  return finalOrder.join(" ").trim(/\s/);
}

console.log(getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"));

A: Instead of includes use indexOf. That takes a second parameter, the index to start searching. Loop over all burgers for example, and pass the previous index to the next indexOf call, until it returns -1, then count how often you've looped.
Alternatively, you can .match the text based on a regex that accepts all possible dishes.

A: Here is my solution to that challenge:
Explanation:
For each menu item: Count the number of occurrences of the item and add the item to the output string that many times.

*

*RegExp(i, 'gi'): Case insensitive global match for counting

*|| []: Handle matching 0 times

*.length: Only get the count of matches

*Array().fill(i): Create sized array filled with the menu item, repeated

*...: Expand array so push inserts elements individually in the array

*.join(' '): Finally, insert spaces between each match

Example:

let menu = ['Burger','Fries','Chicken','Pizza','Sandwich','Onionrings','Milkshake','Coke'];

function getOrder(input) {
  let output = [];
  menu.forEach( (i) =>
    output.push( ...Array( (input.match( RegExp(i, 'gi') ) || []).length ).fill( i ) )
  );
  return output.join(' ');
}

console.log( getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza") )

A: If you knew where in the string your word was, you could remove it, so that if you looked again in the remaining string, you'd find the duplicate.

A: You can also iterate character by character and append words as they form. To check if a word is "formed", you can use a set to store the words/menu-items that are valid:

function getOrder(input) {

  let order = [];
  const items = new Set(["burger", "fries", "chicken", "pizza", "sandwich", "onionrings", "milkshake", "coke"]);

  let curr = "";
  for (let c of [...input]) {
    curr += c;
    if (items.has(curr)) {
      order.push(curr);
      curr = "";
    }
  }
  return order.map(item => item.charAt(0).toUpperCase() + item.slice(1)).join(" ");
}

console.log(getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"));

A: Create an array containing the menu items in lower case in the order given
let testString = "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza";
let menuItemsLowerCase = ["burger","fries","chicken","pizza","sandwich","onionrings","milkshake","coke"];

Iterate over each item and replace the occurrence of each item with the item string plus a comma
for(let itemIndex=0;itemIndex<menuItemsLowerCase.length; itemIndex++){
    const item = menuItemsLowerCase[itemIndex];
    const re = new RegExp(item,"g");
    testString = testString.replace(re, item+',');
}

Remove the last comma if any
if(testString[testString.length-1] === ','){
    testString = testString.substr(0,testString.length-1);
}

Split the string onto commas and sort
let stringAsArray = testString.split(',');
stringAsArray = stringAsArray.sort(function(a,b){
    return menuItemsLowerCase.indexOf(a) - menuItemsLowerCase.indexOf(b);
});

Convert first character to upper case and join back with space as the separator
console.log(stringAsArray.map(function(item){
        return item.substr(0,1).toUpperCase() + item.substr(1);
    }
).join(' '));

A: *

*Create an array of all matching items that exist within the input string

*Turn the first letter of all items in the array to Uppercase, so that they match the items in the menu array exactly.

*Sort the items according to their order in the menu array.

*Return the array joined into a string.

function getOrder(input) {

  let menu = ['Burger','Fries','Chicken','Pizza','Sandwich','Onionrings','Milkshake','Coke'];
  let items = input.match(/(burger|fries|chicken|pizza|sandwich|onionrings|milkshake|coke)/gi);
  items = items.map((element) => element.charAt(0).toUpperCase() + element.slice(1));
  items = items.sort((a, b) => {
    if (menu.indexOf(a) > menu.indexOf(b)) {
      return 1;
    }
    else {
      return -1;
    }
  });
  return items.join(" ");
}

console.log(getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"));


text:
Q: The mean value of a selected die from an infinite series of rolls If I roll a pair of dice an infinite number of times, and always select the higher value of the two, will the expected mean of the highest values exceed 3.5?
It would seem that it must be since if I rolled a million dice, and selected the highest value each time, the odds are overwhelming that sixes would be available in each roll. Thus, the expected mean would have to be something like 5.999999999999...
However, I can't seem to figure out what the expected value would be with my example using just 2 dice. Can someone help me arrive at a number? Would it barely exceed 3.5? Is this even something that can be calculated?

A: The experiment can also be simulated. This approach is useful when enumeration is difficult (like rolling 3 dice).
# fix the seed for reproducibility
set.seed(123)

# simulate pair of dice
rolls = matrix(sample(1:6, 2000000, replace=T), ncol=2)

# compute expected value
mean(apply(rolls, 1, max))
[1] 4.471531

A: There is no need to use simulation for this, the general case is quite easy to analyse. Let $n$ be the number of dice and $X$ be the maximum roll made when rolling the $n$ dice.
It follows that
$$
P(X \leq 1) = \left(\frac{1}{6}\right)^n
$$
and in general
$$
P(X \leq k) = \left(\frac{k}{6}\right)^n
$$
for $k$ between 1 and 6. Therefore we can obtain
$$
P(X = k) = P(x \leq k) - P(x \leq k-1)=\left(\frac{k}{6}\right)^n-\left(\frac{k-1}{6}\right)^n.
$$
So we can write down the probability distribution in closed form. Doing this for $n = 2$ you obtain the expected value 4.472222.

A: Assuming each of the 36 combinations has an equal probability, we just have to add the values of each of the 36 combinations and divide by 36 to get the average:

*

*1 possibility: 11

*3 possibilities: 12, 21, 22

*5 possibilities: 13, 23, 31, 32, 33

*7 possibilities: 14, 24, 34, 41, 42, 43, 44

*9 possibilities: 15, 25, 35, 45, 51, 52, 53, 54, 55

*11 possibilities: 16, 26, 36, 46, 56, 61, 62, 63, 64, 65, 66

(1*1 + 2*3 + 3*5 + 4*7 + 5*9 + 6*11) / 36 =  4.47222..

A: I suggest just working through the trivial case to see the answer.
Possible results from rolling two dice generate a 6x6 matrix: $$\begin{bmatrix} (1,1) & (1,2) & ... \\ (2,1) & (2,2) & ... \\ (3,1) & (3,2) & ... \\ ... \end{bmatrix}$$
The expected value of the sum is 7. This is the case because the rolls are identical independent drawings, so they may be summed. The expectation of rolling a fair cubical die is 3.5.
But you are asking about maximization. Now let us enumerate the maximization from rolling two dice. Again, it is a 6x6 matrix: $$\begin{bmatrix} 1 & 2 & ... \\ 2 & 2 & ... \\ 3 & 3 & ... \\ ... \end{bmatrix}$$
Calculate the expected value, like so: $$E[x] = \Sigma(xP(x)) = 1/36(1) + 1/36(2) + ... + 1/36(6) \approx 4.47$$.
Notice that rolling $n$ dice is (in a probabilistic sense) equivalent to rolling one die $n$ times. So for rolling $n$ dice you can see how the matrix changes and how the resulting expectation changes, too.

A: Troll Dice Roller is the tool for finding dice probabilities.  He has a paper explaining the implementation, but it's pretty academic.
max(2d6) yields
1 - 2.8%
2 - 8.3%
3 - 13.9%
4 - 19.4%
5 - 25%
6 - 30.6%
Average value =    4.47222222222
Spread =       1.40408355068
Mean deviation =       1.1975308642


text:
Q: playing video from NSData without saving a file Can any one have idea how to play video from NSData actually it's base64 String file i converted it into NSData and i want play it . without saving file in phone , directly play video from NSData...have any idea please discuss with me.
thank you.

A: You can use a web player to play it,and you load the html.


text:
Q: Installing QGIS3 on Mac? Kyngchaos installer is not finding python3. I installed python3 using HomeBrew and is not located at /usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/bin/python3.6
How do I tell the QGIS installer to recognize that python3 is installed?
I had previously installed GDAL using HomeBrew, so tried reinstalling (or installing another version wherever it might end up) thinking it might help with the situation, but the QGIS3 installer still can't find python 3.
The installation error is a popup that comes up as soon as the installer is open and says "python3 QGIS requires Python 3.6."
For non Mac users, most seem to rely on Kyngchaos to provide an installer for QGIS and he has just released the installer for v3.
Update: answered my own questions below. Don't use HomeBrew unless you know enough to point the QGIS installer/QGIS to the right version (which I certainly don't), but use the python3 installer version linked to in the ReadMe.

A: I followed the link that came with the QGIS installer to https://www.python.org/downloads/ and installed python3 that way. The QGIS installer was then happy.
This seems to be contradicted by comments here:
"Because QGIS links the python library, you must install the python.org Python 3.6. You can't substitute another python 3 installation. Sorry, that's the way it is."
Posted at http://www.kyngchaos.com/blog/2018/20180315_qgis_3_must_use_python.org_python_3. If I knew how to contact William Kyngesbury, I would. He is performing a great service though.

A: Another version of pyenv and symlinking, using brew just for dependencies.
Recommended location to install pyenv is ~/.pyenv ($HOME/.pyenv), but could be any location.

*

*clone pyenv repository (maybe adapt ~/.pyenv to /path/to/pyenv)
git clone https://github.com/pyenv/pyenv.git ~/.pyenv

*setup pyenv in ~/.bash_profile (maybe adapt $HOME/.pyenv to /path/to/pyenv, be aware, that the third line must stay the final one of .bash_profile, even after future updates)
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

*restart shell
exec "$SHELL"

*install dependencies readline and xz the easy way with brew
brew install readline xz

*install Python 3.6.x containing Python.framework (maybe adapt version number)
env PYTHON_CONFIGURE_OPTS="--enable-framework" pyenv install 3.6.8

*always rehash after adding a new Python version to pyenv
pyenv rehash

*symlink Python.framework
sudo ln -s $(pyenv root)/versions/3.6.8/Python.framework /Library/Frameworks/Python.framework

Now the QGIS 3.6.0 installer from qgis.org should run fine plus macOS is well prepared for multiple Python versions, playing nice with system's Python.

A: NEW UPDATE
QGIS3 can now be installed from osgeo's homebrew tap, which saves mucking about with python symlinks... i.e.
brew tap osgeo/osgeo4mac
brew install qgis

Then type qgis in the terminal to launch, then pin the dock menu icon to simplify launching in future.
Note that the installation console logs will also provide an example for how to symlink qgis to your applications directory.

Due to some current issues, it may be necessary to run ulimit -n 1024 from terminal as a workaround for the Too many open files @ rb_sysopen - /usr/local/var/homebrew/locks/xmlto.formula.lock error. You may also need to run brew install qgis more than once for all packages to find each other.

OLD UPDATE
(This method requires updating symlinks when versions change... i.e. not ideal)
For those who use homebrew, it is probably better to just use a symlink, otherwise all kinds of havoc could emerge. e.g. the official python binary will modify your ~./bash_profile so that python3 and pip3 no longer point to brew...
In my case I've now symlinked the homebrew version (along the lines of the discussion in the answer provided by @Evenfire):
sudo ln -s /usr/local/Cellar/python/3.6.5/Frameworks/Python.framework /Library/Frameworks/Python.framework

QGIS3 then complained that certain python packages were missing, which can be installed with pip3, e.g.
pip3 install owslib PyYaml psycopg2 jinja2 pygments plotly

It might also complain about gdal, in my case I simply used brew:
brew install gdal

ORIGINAL
(This method is not recommended for brew users!)
I've also got python3 installed via brew and am running into the same difficulty.
What seems to work is to install the official python binaries which install to /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.
From trial and error, this has to be done before the 1 Install GDAL Complete.pkg package is installed, which otherwise installs against the wrong python and QGIS 3 will complain about missing python packages.
Those with time to experiment could conceivably try symlinks to get around directly using the brew (or other) python3.

A: A version using pyenv and brew:
brew install pyenv
env PYTHON_CONFIGURE_OPTS="--enable-framework CC=clang" pyenv install 3.6.5
sudo ln -s /Users/$USER/.pyenv/versions/3.6.5/Python.framework/Versions/3.6 /Library/Frameworks/Python.framework/Versions/3.6
sudo cp -R /Users/$USER/.pyenv/versions/3.6.5/Python.framework/Versions/3.6 /Library/Frameworks/Python.framework/Versions/3.6
sudo cp -r /Users/$USER/.pyenv/versions/3.6.5/lib/python3.6/lib-dynload/ /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload
sudo cp /Users/$USER/.pyenv/versions/3.6.5/lib/python3.6/lib-dynload/_struct.cpython-36m-darwin.so /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload/_struct.cpython-36m-darwin.so
#

A: If you have installed Python3 with Homebrew, you can use symlinks to comply with the installer needs (as suggested by @shongololo).
It seems, the installer needs Python3 installed at (thanks @shongololo): /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.
(Install python3 using Homebrew to follow this part)
Find the Cellar directory on your machine. Mine is at: /usr/local/Cellar.
Then find this directory: /usr/local/Cellar/python3/3.x.y_z/Frameworks/Python.framework (where 3.x.y_z is the python3 version you want to use, for me it is 3.6.4_2). This is the directory we want the installer to find. We need to link to this directory from the directory the installer is looking at by making a Symbolic Link.
Using the ln command (ln -s TARGET_FILE_TO_LINK_TO LINK_NAME):
ln -s /usr/local/Cellar/python3/3.x.y_z/Frameworks/Python.framework /Library/Frameworks/Python.framework will do the trick. You certainly need to sudo.
This has worked for me.
(The "Cellar" is a place that all your "kegs" go. Homebrew installs packages to their own directory (in the Cellar) and then symlinks their files into /usr/local/. [from Ryan Kulla's blog])

A: I faced the same issue when installing QGIS on mac.
It was failed, although I tried to softlink it with other python installed by anaconda, etc.
The way I solved the issue: download related python version in python.org and install.


text:
Q: Where can I find the built-in data types for Python 3? This is probably a really dumb question, but I'm new to programming and I want to understand how the in-built classes and their methods work. I've tried searching for builtins on my computer (I can't find it for some strange reason -- but perhaps it's that obvious and I just can't find it.), or is there something a little more low level going on there that I'm unaware of?
If it is just in a builtin python module and I'm dumb, where can this be found?
Thanks.

A: The most common implementation of Python is actually written in C. (Thus it is usually called CPython... not to be confused with Cython.) Thus, built in functions and classes are most frequently written in C. An example. As such, it's hard to get more detailed than the documentation without delving a great deal more thoroughly into the internals of Python and a language that you likely don't need or want to know at this point. The stdtypes documentation for Python 3 should include all of the detail you need for working with the language.


text:
Q: How to import data from Excel sheet to data Table in c#? I am using Asp.net with C#. I need to import data from an Excel sheet to a DataTable. The sheet has 100,000 records with four columns: Firstname, LastName, Email,Phone no.
How can I do this?

A: Use the following code:
public static DataTable exceldata(string filePath)
    {
        DataTable dtexcel = new DataTable();
           bool hasHeaders = false;
            string HDR = hasHeaders ? "Yes" : "No";
            string strConn;
            if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
            else
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            //Looping Total Sheet of Xl File
            /*foreach (DataRow schemaRow in schemaTable.Rows)
            {
            }*/
            //Looping a first Sheet of Xl File
            DataRow schemaRow = schemaTable.Rows[0];
            string sheet = schemaRow["TABLE_NAME"].ToString();
            if (!sheet.EndsWith("_"))
            {
                string query = "SELECT  * FROM [" + sheet3 + "]";
                OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                dtexcel.Locale = CultureInfo.CurrentCulture;
                daexcel.Fill(dtexcel);
            }

        conn.Close();
        return dtexcel;

    }

Source: http://www.codeproject.com/Questions/445400/Read-Excel-Sheet-Data-into-DataTable
You may also refer the following question: Importing Excel into a DataTable Quickly if you wish to import faster.

A: I'm not sure if this will work in ASP.NET but it works in WPF so maybe there's something you can take from it?
Anyway, at the global scope:
Microsoft.Office.Interop.Excel.Application xls;

Then to select and read a spreadsheet:
     private void readSheet()
    {
        // Initialise and open file picker
        OpenFileDialog openfile = new OpenFileDialog();
        openfile.DefaultExt = ".xlsx";
        openfile.Filter = "Office Files | *xls;.xlsx";
        var browsefile = openfile.ShowDialog();

        if (browsefile == true)
        {
            string path = openfile.FileName;

            xls = new Microsoft.Office.Interop.Excel.Application();

            // Dynamic File Using Uploader... Note the readOnly flag is true
            Workbook excelBook = xls.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Worksheet excelSheet = (Worksheet)excelBook.Worksheets.get_Item(1); ;
            Range excelRange = excelSheet.UsedRange;

            // Make default cell contents
            string strCellData = String.Empty;
            double douCellData;

            // Initialise row and column
            int rowCnt, colCnt = 0;

            // Initialise DataTable
            System.Data.DataTable dt = new System.Data.DataTable();

            // Loop through first row of columns to make header
            for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
            {
                string strColumn = "";
                strColumn = Convert.ToString((excelRange.Cells[1, colCnt] as Range).Value2);
                var Column = dt.Columns.Add();
                Column.DataType = Type.GetType("System.String");

                // Check & rename for duplicate entries
                if (dt.Columns.Contains(strColumn))
                    Column.ColumnName = (strColumn + ", " + colCnt);
                else
                    Column.ColumnName = strColumn;
            }
            dt.AcceptChanges();

            // Fill in the rest of the cells
            for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)
            {
                string strData = "";
                for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
                {
                    try
                    {
                        strCellData = Convert.ToString((excelRange.Cells[rowCnt, colCnt] as Range).Value2);
                        strData += strCellData + "|";
                    }
                    catch (Exception ex)
                    {
                        douCellData = (excelRange.Cells[rowCnt, colCnt] as Range).Value2;
                        strData += douCellData.ToString() + "|";
                        Console.Write(ex.ToString());
                    }
                }
                strData = strData.Remove(strData.Length - 1, 1);
                dt.Rows.Add(strData.Split('|'));

            }

            dtGrid.ItemsSource = dt.DefaultView;
            try
            {
                excelBook.Close(true, null, null);
            }
            catch (System.Runtime.InteropServices.COMException comEX)
            {
                Console.Write("COM Exception: " + comEX.ToString());
            }
            xls.Quit();
        }
    }

A: Speed Problems?
I'll note several ways to do this:

*

*ODBC (answered here)

*Interop (answered here)

These have drawbacks, they might not be fast; Interop requires excel, runs it, and can cause lots of problems with re-running it or the web server trying to run it.
please try @milan_m solution first. If it has problems come back here.
So some faster, potentially better solutions are as such.

*

*NPOI

*Save-As CSV

NPOI is available as a NuGet for C# and will read excel files very well. Yes this is a product recommendation, but you didn't ask for one. It is a well-maintained project and will be relevant for readers into the 2030s.
https://github.com/nissl-lab/npoi
You'll want to use NPOI if ODBC is too slow, and your users are uploading a different XLSX file as part of the use case. Unless there are only 2 or 3 internal power users you are in contact with, then you can require them to upload it as CSV.
What if the use case is: You just use one .XLSX file that's the same for all users, you deploy it with the app?
You didn't mention if this is the case or not and it makes a HUGE difference. you definitely will be miles ahead if you save as csv and consume that from the startup of the program. Or, if you need it in a datatable, import it to the data table at dev time and save it to XML file using a method on the dataset object (you have to put the tbl into a set to save as XML I believe ... many examples abound).
If you need to do super flexible lookups, a datatable (or object collection and linq-to-objects) is good.
However if you have to look up items at extreme speed, and not via ranges but just by exact match, load it to a dictionary or dictionaries at startup time, from a CSV or similar.
I did this for a power user who was searching a spreadsheet of about 2-3lakh / records with interop+excel ... operation went from 90 minutes to 30 seconds. Literally. Dictionary is about the fastest way to look stuff up in .Net, if you can fit that stuff in memory, that is, and don't have to reload different data all the time (so keep your RDBMS).
Oops.
Just now saw this question is 7 years old. @#$^#@!!!


text:
Q: Why do I still get "A potentially dangerous Request.Form value was detected" even after disabling it? I've just created a new MVC4 "Internet" application in Visual Studio 2012 (C#).
I went to the default /Account/Login page and typed in <b /> as the username.
The server crashed with this error:

A potentially dangerous Request.Form value was detected from the client (UserName="").

I've seen it before and got rid of it before, so I can do it again easily. I changed my Web.config to look like this:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" requestValidationMode="2.0" /><!-- Look here -->
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages validateRequest="false"><!-- Look here -->
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
</system.web>

I cleaned the solution and did a rebuild, but I still get exactly the same error when I try <br /> again.
What's wrong?

A: Modifying the Web.config file is how you would disable the setting in Web Forms.
In MVC you would apply the ValidateInput attribute to your controller method.
<HttpPost>
<ValidateInput(False)>
Public Function ActionName(model As Object) As ActionResult

End Function

Or if you prefer C#
[HttpPost]
[ValidateInput(false)]
ActionResult ActionName(Object model) {

}


text:
Q: Array sorting as per value and corresponding key I have one array like this:
        Array
        (
           [1] => 0
           [2] => 1
           [4] => 1
           [5] => 4
           [6] => 2
           [7] => 0
           [8] => 2
           [9] => 7
           [10] => 2
           [11] => 2
           [12] => 2
           [17] => 12
           [18] => 17
           [19] => 0
           [20] => 19
           [21] => 20
           [22] => 20
           [23] => 20
           [24] => 0
         )

And i want to sort array like first all the 0 value key index find and and using this key value index find in array like 0 value key index is 1,7,19,24 and now 1,7,19,24 value find in array and corresponding key is get and at last all the key sequence is get in new array. is it possible?

A: asort($cars);

example:
asort($cars);
echo "<pre>";
print_r($cars);
echo "</pre>";

A: asort($arr);
$arr = array_keys($arr);
print_r($arr);

Output:
Array
(
    [0] => 7
    [1] => 1
    [2] => 19
    [3] => 24
    [4] => 2
    [5] => 4
    [6] => 10
    [7] => 12
    [8] => 11
    [9] => 8
    [10] => 6
    [11] => 5
    [12] => 9
    [13] => 17
    [14] => 18
    [15] => 20
    [16] => 21
    [17] => 23
    [18] => 22
)

A: $newTab = array();

foreach ($tab as $k => $v)
{
    $newTab[$v][] = $k;
}

Produces:
array (size=9)
  0 =>
    array (size=4)
      0 => int 1
      1 => int 7
      2 => int 19
      3 => int 24
  1 =>
    array (size=2)
      0 => int 2
      1 => int 4
  4 =>
    array (size=1)
      0 => int 5
  2 =>
    array (size=5)
      0 => int 6
      1 => int 8
      2 => int 10
      3 => int 11
      4 => int 12
   ....


text:
Q: Threads are slow when audio is off I have 2 projects. One is built by C++ Builder without MFC Style. And other one is VC++ MFC 11.
When I create a thread and create a cycle -- let's say this cycle adds one to progressbar position -- from 1 to 100 by using Sleep(10) it works of course for both C++ Builder and C++ MFC.
Now, Sleep(10) is wait 10 miliseconds. OK. But the problem is only if I have open media player, Winamp or anything else that produces "Sound". If I close all media player, winamp and other sound programs, my threads get slower than 10 miliseconds.
It takes like 50-100 ms / each. If I open any music, it works normally as I expected.
I have no any idea why this is happening. I first thought that I made a mistake inside MFC App but why does C++ Builder also slow down?
And yes, I am positively sure it is sound related because I even re-formated my windows, disabled everything. Lastly I discovered that sound issue.
Does my code need something?
Update:
Now, I follow the code and found that I used Sleep(1) in such areas to wait 1 miliseconds. The reason of this, I move an object from left to right. If I remove this sleep then the moving is not showing up because it is very fast. So, I should use Sleep(1). With Sleep(1), if audio is on than it works. If audio is off than it is very slow.
for (int i = 0; i <= 500; i++) {
   theDialog->staticText->SetWindowsPosition(NULL, i, 20, 0, 0);
   Sleep(1);
}

So, suggestions regarding this are really appreciated. What should I do?
I know this is the incorrect way. I should use something else that is proper and valid. But what exactly? Which function or class help me to move static texts from one position to another smoothly?
Also, changing the thread priority has not helped.

Update 2:
Update 1 is an another question :)

A: Sleep(10) waits for at least 10 milliseconds. You have to write code to check how long you actually waited and if it's more than 10 milliseconds, handle that sanely in your code. Windows is not a real time operating system.

A: Sleep (10), will (as we know), wait for approximately 10 milliseconds. If there is a higher priority thread which needs to be run at that moment, the thread wakeup maybe delayed. Multimedia threads are probably running in a Real-Time or High priority, as such when you play sound, your thread wakeup gets delayed.
Refer to Jeffrey Richters comment in Programming Applications for Microsoft Windows (4th Ed), section Sleeping in Chapter 7:

The system makes the thread not schedulable for approximately the
  number of milliseconds specified. That's right—if you tell the system
  you want to sleep for 100 milliseconds, you will sleep approximately
  that long but possibly several seconds or minutes more. Remember that
  Windows is not a real-time operating system. Your thread will probably
  wake up at the right time, but whether it does depends on what else is
  going on in the system.

Also as per MSDN Multimedia Class Scheduler Service (Windows)
MMCSS ensures that time-sensitive processing receives prioritized access to CPU resources.
As per the above documentation, you can also control the percentage of CPU resources that will be guaranteed to low-priority tasks, through a registry key

A: The minimum resolution for Sleep() timing is set system wide with timeBeginPeriod() and timeEndPeriod().  For example passing timeBeginPeriod(1) sets the minimum resolution to 1 ms.  It may be that the audio programs are setting the resolution to 1 ms, and restoring it to something greater than 10 ms when they are done.  I had a problem with a program that used Sleep(1) that only worked fine when the XE2 IDE was running but would otherwise sleep for 12 ms.  I solved the problem by directly setting timeBeginPeriod(1) at the beginning of my program.
See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd757624%28v=vs.85%29.aspx


text:
Q: Import java package com.typesafe.config.impl.SimpleConfig using python with py4j I can import all from java.* using the jvm from JavaGateway of py4j
for example:
jvm.java.util.ArrayList
jvm.java.lang.System
random = jvm.java.util.Random()
random.nextInt(3)

or in this form:
from py4j.java_gateway import java_import
java_import(jvm,'java.util.*')
random = jvm.Random()
random.nextInt(3)

I need to import:
com.typesafe.config.impl.SimpleConfig
com.typesafe.config.ConfigFactory
com.typesafe.config.Config

But it doesn't work, I tried these ways:
jvm.com.typesafe.config.impl.SimpleConfig
jvm.java.com.typesafe.config.impl.SimpleConfig
jvm.java.typesafe.config.impl.SimpleConfig
java_import(jvm,'com.typesafe.config.*')
java_import(jvm,'com.typesafe.config.impl.*')
jvm.SimpleConfig
jvm.impl.SimpleConfig

all returns: py4j.java_gateway.JavaPackage
not py4j.java_gateway.JavaClass  as needed


text:
Q: Dynamically create a chain of ordered IntegrationFlows I'm creating a series of processes that use Spring Integration explicitly using the Java DSL. Each of these processes do different things but they have some of the same processing logic
Example:
get
process
deduplicate
emit

I would like to essentially create a chain of post processing integration flows that can be enabled/disabled via configuration/profiles.
Example:
get
preprocess flow 1 (if enabled)
...
preprocess flow n (if enabled)
process
postprocess flow 1 (if enabled)
...
postprocess flow n (if enabled)
emit

I'm pretty sure this doesn't exist yet in SI but thought I'd ask. The only thing i could think of would be to create a bean that created direct message channels on the fly and that, during configuration, i could give to each of the integration flows to use to get their "from" and "channel" message channels.
Example:
@Configuration
public class BaseIntegrationConfiguration {
    @Bean
    public MessageChannel preProcessMessageChannel() {
        return MessageChannels.direct().get();
    }

    @Bean
    public MessageChannel processMessageChannel() {
        return MessageChannels.direct().get();
    }

    @Bean
    public MessageChannel postProcessMessageChannel() {
        return MessageChannels.direct().get();
    }

    @Bean
    public MessageChannel emitMessageChannel() {
        return MessageChannels.direct().get();
    }

    @Bean
    public IntegrationFlow getDataFlow(MessageChannel preProcessMessageChannel) {
        return IntegrationFlows
                .from(/* some inbound channel adapter */)
                // do other flow stuff
                .channel(preProcessMessageChannel)
                .get();
    }

    @Bean
    public IntegrationFlowChainMessageChannelGenerator preProcessFlowGenerator(
            MessageChannel preProcessMessageChannel,
            MessageChannel processMessageChannel) {
        IntegrationFlowChainMessageChannelGenerator generator = new IntegrationFlowChainMessageChannelGenerator ();
        generator.startWith(preProcessMessageChannel);
        generator.endWith(processMessageChannel);

        return generator;
    }

    @Bean
    public IntegrationFlow processFlow(
            MessageChannel processMessageChannel,
            MessageChannel postProcessMessageChannel) {
        return IntegrationFlows
                .from(processMessageChannel)
                // do other flow stuff
                .channel(postProcessMessageChannel)
                .get();
    }

    @Bean
    public IntegrationFlowChainMessageChannelGenerator postProcessFlowGenerator(
            MessageChannel postProcessMessageChannel,
            MessageChannel emitMessageChannel) {
        IntegrationFlowChainMessageChannelGenerator generator = new IntegrationFlowChainMessageChannelGenerator ();
        generator.startWith(postProcessMessageChannel);
        generator.endWith(emitMessageChannel);

        return generator;
    }
}

@Configuration
@Order(1)
@Profile("PreProcessFlowOne")
public class PreProcessOneIntegrationConfiguration {
    @Bean
    public IntegrationFlow preProcessFlowOne(IntegrationFlowChainMessageChannelGenerator preProcessFlowGenerator) {
        return IntegrationFlows
                .from(preProcessFlowGenerator.getSourceChannel())
                // flow specific behavior here
                .channel(preProcessFlowGenerator.getDestinationChannel())
                .get();
    }
}

@Configuration
@Order(2)
@Profile("PreProcessFlowTwo")
public class PreProcessTwoIntegrationConfiguration {
    @Bean
    public IntegrationFlow preProcessFlowTwo(IntegrationFlowChainMessageChannelGenerator preProcessFlowGenerator) {
        return IntegrationFlows
                .from(preProcessFlowGenerator.getSourceChannel())
                // flow specific behavior here
                .channel(preProcessFlowGenerator.getDestinationChannel())
                .get();
    }
}

@Configuration
@Order(1)
@Profile("PostProcessFlowOne")
public class PostProcessOneIntegrationConfiguration {
    @Bean
    public IntegrationFlow postProcessFlowOne(IntegrationFlowChainMessageChannelGenerator postProcessFlowGenerator) {
        return IntegrationFlows
                .from(postProcessFlowGenerator.getSourceChannel())
                // flow specific behavior here
                .channel(postProcessFlowGenerator.getDestinationChannel())
                .get();
    }
}

@Configuration
@Order(2)
@Profile("PostProcessFlowTwo")
public class PostProcessTwoIntegrationConfiguration {
    @Bean
    public IntegrationFlow postProcessFlowTwo(IntegrationFlowChainMessageChannelGenerator postProcessFlowGenerator) {
        return IntegrationFlows
                .from(postProcessFlowGenerator.getSourceChannel())
                // flow specific behavior here
                .channel(postProcessFlowGenerator.getDestinationChannel())
                .get();
    }
}

The idea here being that the invokations of "getDestinationChannel" would create a new channel every time and bridge the output of the last generated channel to the configured "endWith" and every invokation to "getSourceChannel" returns the last created destination channel or, if there are none, the "startWith" channel.
As I write and think about this, I'm starting to think there is probably a better way but thought that I would put this out there for some input.
Thank you.

A: It's not currently supported directly in the DSL, but the routing slip might satisfy your needs.
If your get, dedup etc are individual flows, you can initialize the routing slip at the start of the initial flow to either include, or not, input channels for the preprocessing step(s) in the list in between the channels for the main flows.
Although there is not yet first class support in the DSL, you can use a header enricher to set up the routing slip. The header name is IntegrationMessageHeaderAccessor.ROUTING_SLIP.
EDIT
Actually, don't maintain the header yourself; scroll down the reference manual chapter about routing slip to see how to configure the HeaderEnricher using Java.


text:
Q: English language for in between What would be the correct spelling for "in between" for the following:

From the Sierra's to the sea and everywhere in between.

or

From the Sierra's to the sea and everywhere inbetween.

A: This is a matter of word choice, rather than correct spelling. The noun and adjective 'in-between' has these meanings:

in-beˈtween, n. and adj.
A. n.
     (a) An interval.  (b) A person who intervenes.
  ....
B. adj.
  Placed between.

["in-beˈtween, n. and adj.". OED Online. December 2015. Oxford University Press. http://www.oed.com/view/Entry/93227?redirectedFrom=in+between (accessed January 04, 2016).]
Your example doesn't seem to me to match any of those meanings. For your example, I would leave the "in" out altogether and use

From the Sierras to the sea and everywhere between.

A: Neither:

From the Sierras to the sea and everywhere between.

The "in" is superfluous and not needed in this context.


text:
Q: Showing the Word Count for Each Word I am having a hard time conducting a top 15 word count (Word Count for each word) for the document, Wuthering Heights (https://www.gutenberg.org/files/768/768.txt) on Google Colab. It can only include the words that start after "ccx074@pglaf.org" and end before "END OF THE PROJECT GUTENBERG EBOOK WUTHERING HEIGHTS. This is the coding that I tried.
file = open(768.txt,'r+')
wordcount = {}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] +=1
for k,v in wordcount.items():
    print(k,v)

A: You can use regex to find your desired substring:
file = open('768.txt','r')
start = 'ccx074@pglaf.org'
end = 'END OF THE PROJECT GUTENBERG EBOOK WUTHERING HEIGHTS'
import re

m = re.findall(start+'(.*?)'+end, file.read(), flags=re.S)[0]
wordcount={}
for word in m.split():
  if word not in wordcount:
    wordcount[word] = 1
  else:
      wordcount[word] +=1
for k,v in wordcount.items():
  print(k,v)

Sample output:
WUTHERING 1
HEIGHTS 1
CHAPTER 34
I 3215
1801.--I 1
have 594
just 72
returned 39
from 476
...

However, you can count the words using built-in functions. For example, this:
from collections import Counter
print(Counter(m.split()))

#Counter({'the': 4273, 'and': 4189, 'to': 3436, ...})

EDIT: To print sorted:
sorted(Counter(m.split()).items(), key=lambda x:x[1])

or reverse from high to low:
sorted(Counter(m.split()).items(), key=lambda x:x[1], reverse=True)

A: With the help from string punctuation and operator itemgetter, this could be an approach. This will get close. Note that removing the punctuation will eliminate ending (.!?), to get clean words. (Also removes apostrophes (which you probably don't want to remove)
from collections import Counter
from string import punctuation
from operator import itemgetter

d = Counter()

with open('wuthering_heights.txt', 'r') as f:
    opening = False

    for line in f:
        if line.startswith('ccx074@pglaf.org'):
            opening = True
        if opening == False:
            continue
        if line.startswith('CHAPTER'): # don't count chapter headings
            continue
        if line.startswith('***END OF THE PROJECT GUTENBERG EBOOK'):
            break

        line = line.strip()
        if len(line) == 0:
            continue

        # clean out punctuation
        line = line.translate(str.maketrans('','',punctuation))

        d.update(line.lower().split())

print('different words count', len(d)        )
#print(d.most_common(15))

for word, count in reversed(sorted(d.items(), key=itemgetter(1))):
    print(word, count)
    if count < 290:
        break

This prints:
different words count 10098
and 4693
the 4552
i 3530
to 3476
a 2301
of 2221
he 1922
you 1712
her 1544
in 1459
his 1419
it 1284
she 1269
that 1188
was 1124
my 1098
me 1047
not 932
as 931
him 917
for 836
on 809
with 804
at 783
be 724
had 687
but 673
is 649
have 629
from 485
by 451
would 442
if 440
heathcliff 413
your 404
no 384
said 368
so 357
were 354
linton 340
catherine 333
an 317
we 311
mr 309
or 307
when 307
out 305
what 301
are 295
this 290
they 283


text:
Q: ChromeOptions AddUserProfilePreference I am using Webdriver 3.3.1 with Java. I am trying to disable the pop-up asking to save passwords. Based on search results I need to use
ChromOptions.AddUserProfilePreference("","")
However, there is no AddUserProfilePreference
the only add method is addArguments.
I am using Eclipse Neon.2 and Java 1.8

A: With ChromeDriver 2.28 & Selenium 3.3.1, the following works:
final DesiredCapabilities capabilities = DesiredCapabilities.chrome();
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
Map<String, Object> prefs = new LinkedHashMap<>();
prefs.put("credentials_enable_service", Boolean.valueOf(false));
prefs.put("profile.password_manager_enabled", Boolean.valueOf(false));
chromeOptions.setExperimentalOption("prefs", prefs);
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new ChromeDriver(capabilities);

A: Add the below chrome options:
Map<String, Object> prefs =new HashMap<String, Object>();
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-extensions");
prefs .put("credentials_enable_service", false);
prefs .put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);


text:
Q: Click outside of Navbar detected I have no idea why this is not working. I have my "mainNav" class set to display {none}. My "active" class has a display {block}. My navToggle works fine before I add the window.eventlistener into my JS. But once as add the window.addeventlistener it stops working.
const navTransition = () => {
    const navToggle = document.querySelector('.nav-toggle');
    const mainNav = document.querySelector('.main-nav');
    const navLinks = document.querySelectorAll('.nav-links');

navToggle.addEventListener('click', function () {
    mainNav.classList.toggle('active');
});

window.addEventListener('click', function (evt) {
    if (!evt.target.matches('.nav-links') && (!evt.target.matches('.main-nav'))) {
        mainNav.classList.remove('active');
    };
});

};
navTransition();

    Logo

            Home

            Blog

            Contact

            About

        +

A: Your window.onclick event is causing this logic error. Every time you click on the page, it will hide the navbar. Even when you click on the .nav-toggle this will trigger the window.onclick and therefore hide the navbar. The window click event will always be triggered after the nav-toggle click event because the click event bubbles through each element and into the parent element. So the "path" of that click event will be .nav-toggle, then .navbar and finally the html, document and window. As you can see, the click events for window are triggered last - after all others, so even if the nav-toggle adds the actve class to your navbar, the window.onclick event will remove it after a few milliseconds.
To fix this you could either change the window.onclick event for a window.onmousedown, which will be triggered before the click of nav-toggle, or add a condition to your current window.onclick event to check if event.target is the nav-toggle. The latter way seems more clean to me, and I have done so in this snippet.

const navTransition = () => {
    const navToggle = document.querySelector('.nav-toggle');
    const mainNav = document.querySelector('.main-nav');
    const navLinks = document.querySelectorAll('.nav-links');

window.addEventListener('click', function (evt) {
    if(evt.target.matches('.nav-links') || evt.target.matches('.main-nav') || evt.target.matches(".nav-toggle") || evt.target.closest(".nav-toggle")) {
      return;
    }
    mainNav.classList.remove('active');
});

navToggle.addEventListener('click', function () {
    mainNav.classList.toggle('active');
});

};

navTransition();
.main-nav.active {
  display: block !important;
}
.main-nav {
  display: none;
}

    Logo

            Home

            Blog

            Contact

            About

        +


text:
Q: Maximal function associated to convex bodies Let $B$ be a centrally symmetric convex body in $\mathbb R^n.$ The maximal function associated to $B$ is defined by
$$
Mf = \sup_{r>0}(\chi_{B})_{r}*|f|.
$$
Bourgain (http://www.jstor.org/stable/info/2374532) proved that this operator is bounded on $\mathbb R^n$ for all $p>3/2$ with constant depending only on $p.$
The question is that: Is this operator bounded for $p>\lambda,$ ($1<\lambda\le 3/2$) with constant independent of the dimension? Or can we find a counterexample for that?
Any references?
Thank you.
Hahn.

A: In the case of the cube, it was shown by Bourgain (very recently) that the constants remain independent of $n$ for all $p>1$. The problem appears to be open for the case of more general centrally symmetric convex bodies. On page 3 of his recent preprint, Bourgain writes:
"While it is reasonable to believe that this statement holds in general, our argument is based on a very explicit analysis which does not immediately carry over to other convex symmetric bodies."
For $p=1$, J. Aldaz has shown that the (weak $L^1$) constant can't be taken independent of $n$ in the case of a cube.  The case of the ball is open (this problem was briefly discussed on Gil Kalai's blog here).


text:
Q: $K(\zeta)/k(\zeta)$ is Galois (proof verification) Let $K/k$ be Galois and $\zeta$ be primitive $n$-th root of unity. I want to prove that $K(\zeta)/k(\zeta)$ is also Galois.
Proof: Recall that an extension is Galois iff it is a splitting field of separable polynomial. If $K$ is  the splitting field of $f(x) \in k[x]$  then $K(\zeta)$ is the splitting field of $\frac{f(x)}{ \operatorname{gcd}(f(x), \Phi_n(x))} \in k(\zeta)$ and that's it.
Am I right? If I am wrong, please, don't right your solution.


text:
Q: Laravel 6 - Route post not found I'm trying to implement Register User in NuxtJS. However, I'm having this issue like below

vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php

In My api Route
 Route::post('register', 'V1\Auth\LoginController@register');

I'm try change it to get method and access it by 127.0.0.1:8000/api/register its work pretty fine.
i still have no idea, why i got this POST http://127.0.0.1:3000/api/register 404 (Not Found)
In My Nuxtjs
           async registerUser() {
                try {
                    await this.$axios.post(`api/register`, this.auth);
                    await this.$auth.login({
                        data: {
                            email: this.auth.email,
                            password: this.auth.password,
                        }
                    })
                    .then(res => {
                        console.log(res);
                        this.loading = false
                        // this.$router.push(`/auth/login`);
                    })
                    .catch(err => {
                        this.loading = false
                        this.$refs.form.validate(err.response.data.errors)
                        console.log(err.response);
                    })
                } catch(e) {
                    // statements
                    console.log(e);
                }

 In My Controller
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required|between:6, 25',
        ]);

        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->save();

        return response()->json(['registered' => true ]);
    }

I'll appreciate of all your Help.
Thanks.

A: You are using 3000 port http://127.0.0.1:3000/api/register in the axios, but the laravel use 8000 http://127.0.0.1:8000/api/register

A: You have to establish the API base URL In NuxtJS APP.
The reason is that Your NuxtJS app set default it's own base URL
But you have to configure backend URL for laravel API.
Example,
Try This
await this.$axios.post(`http://127.0.0.1:8000/api/register`, this.auth);


text:
Q: Vite Plugin SSR - critical style generation (VUE.js) I'm using vite-plugin-ssr + vue-router and I want to implement critical styling.
My project has a pages folder which has the following structure:
pages/SomePage/index.vue
<template>
  <div class="TestPage">
    TestPage Content
  </div>
</template>

<script>
export default {
  name: "TestPage"
}
</script>
<style lang="css" src="./critical.css"/>

pages/SomePage/critical.css
.TestPage {
    background: red;
}

I want the styles from the critical.css file to go into the <head/> tag as internal ~ <style> .SomePage {background: blue;} </style> for each route.
I tried to get inspired by the rollup-plugin-critical idea, but my knowledge is apparently not enough, because a positive result could not be achieved.
How can this be implemented?


text:
Q: Background of parent leaking when child's border radius is the same

#outer {
  width: 200px;
  height: 200px;
  background-color: white;
  border-radius: 20px;
}

#inner {
  width: 200px;
  height: 50px;
  background-color: steelblue;
  border-radius: 20px 20px 0 0;
}

body {
  background-color: steelblue;
}

You can see that the white background of the parent is leaking behind the child, even though they have the same border-radius. How can I prevent this?
Edit: Neither of the duplicate questions appropriately answer my question. The leak still happens in the first question. The second question's marked answer uses an image and Javascript, which should not be necessary to fix this.

A: You can change the CSS to obtain a similar layout without this issue:

#outer {
  width: 200px;
  height: 200px;
  background:
   linear-gradient(to bottom,steelblue 50px,white 0);
  border-radius: 20px;
}

body {
  background-color: steelblue;
}


text:
Q: Game: Algorithm for spawning enermies at game/window egdes I'm looking for an algorithm for spawning enermies at the egdes for the gameboard/window for an Android game. I'm doing the old SpaceWars/Shooting asteriods with spaceship and i need the asteroids to spawn at random locations outside the gameboard, where after they will move into the gameboard in different directions and speeds.
It's easy to place the asteroids at random locations, but the tuff part (at least for me) is to give them the right move direction based on the random location they are giving.
For example:
Gameboard = 1280 x 720
Asteroid random location = 1100, 0 (x, y)
Right move direction:
asteroid.x < gameboard.x/2 - possible move directions = south and south east
asteroid.x > gameboard.x/2 - posiible move directions = south and south west
Then the asteroid have two possible move directions (that's how i define the gameplan for now): Direct south or south west.
I could do a lot of if statements, but i'm hoping someone can help me with some kind of algorithm for the problem?

A: Maybe I got wrong your question but this is how I see the solution :
If the asteroid x-position exceeds your device width (720) then its direction should be SW otherwise it should be S.
if(asteroid.x>DEVICE_WIDTH){
    asteroid.direction="SW";
}else{
    asteroid.direction="S";
}

A: This link may help you
http://forums.create.msdn.com/forums/p/100862/599129.aspx
I think you might always need some nested if statements but this way may be a bit more clever


text:
Q: Transform UIView shape I want to transform my UIView's shape into this (the white UIView - look at the right edge) using Swift:

Any ideas how to do it? I guess I should use the transform functionality, but I don't know how exactly. Thanks in advance!

A: Update:
Here is the update, I misunderstood your question in my first answer
You need to subclass UIView and override the default draw method with your own behaviour. To Adjust the angle you can change the offsetFactor
class ShapeView : UIView {
    public var bgc = UIColor.clear
    override init(frame: CGRect) {
        super.init(frame: frame)
        //backup old background color
        self.bgc = backgroundColor!
        backgroundColor = UIColor.clear
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.bgc = backgroundColor!
        backgroundColor = UIColor.clear
    }

    override func draw(_ rect: CGRect) {
        let size = self.bounds.size

        let offsetFactor = size.width * 0.98

        //define the points
        let tl = self.bounds.origin //top left
        let tr = CGPoint(x:tl.x + size.width, y:tl.y) //top  right
        let br = CGPoint(x:tl.x + offsetFactor, y:tr.y + size.height) // bottom right
        let bl = CGPoint(x:tl.x, y:tr.y + size.height) //bottom left

        let path = UIBezierPath()
        path.move(to: tl)
        path.addLine(to: tr)
        path.addLine(to: br)
        path.addLine(to: bl)
        path.close()

        //set old background color
        bgc.set()
        path.fill()
    }
}

Image
I hope I did understand your question right.
You need to subclass UIView and override the default draw method with your own behaviour. To Adjust the spire you can change the offsetFactor
This should do the job
class ShapeView : UIView {
    public var bgc = UIColor.clear
    override init(frame: CGRect) {
        super.init(frame: frame)
        //backup old background color
        self.bgc = backgroundColor!
        backgroundColor = UIColor.clear
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.bgc = backgroundColor!
        backgroundColor = UIColor.clear
    }

    override func draw(_ rect: CGRect) {
        let size = self.bounds.size

        let offsetFactor = size.height * 0.7

        //define the points
        let tl = self.bounds.origin //top left
        let tr = CGPoint(x:tl.x + size.width, y:tl.y) //top  right
        let br = CGPoint(x:tr.x, y:tr.y + offsetFactor) // bottom right
        let bm = CGPoint(x:size.width/2, y:size.height) ////bottom middle
        let bl = CGPoint(x:tl.x, y:offsetFactor) //bottom left

        let path = UIBezierPath()
        path.move(to: tl)
        path.addLine(to: tr)
        path.addLine(to: br)
        path.addLine(to: bm)
        path.addLine(to: bl)
        path.close()

        //set old background color
        bgc.set()
        path.fill()
    }
}

Storyboard and Simulator

A: Dudes, I found an easier solution that works perfectly as an extension to UIView:
extension UIView {

    func makeItEdgy() {
       let bounds = self.bounds

        // Create path to mask the view
        let path = CGMutablePath()
        path.move(to: bounds.origin)
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
        path.addLine(to: CGPoint(x: bounds.maxX - (bounds.height / 5), y: bounds.maxY))
        path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
        path.closeSubpath()

        let maskLayer = (self.layer.mask as? CAShapeLayer) ?? CAShapeLayer()
        maskLayer.path = path

        self.layer.mask = maskLayer
    }
}


text:
Q: Mixing AngularJS with Phalcon Framework I'm building a multi-module webapp in Phalcon, basically structured as follows:
my-project/
├── apps
│   ├── admin
│   │   ├── controllers
│   │   │   └── IndexController.php
│   │   ├── Module.php
│   │   └── views
│   │       └── index
│   │           └── index.phtml
│   └── frontend
│       ├── controllers
│       │   └── IndexController.php
│       ├── Module.php
│       └── views
│           └── index
│               └── index.phtml
├── common
│   └── config
│       └── config.ini
└── public
    └── index.php

You may notice that there is a module for the Admin area and another one for the Front-end side. Now I would like to build the Admin area with AngularJS, with the traditional AngularJS app structure made of several files, folders and subfolders. So I have a two-fold question:

*

*Where is the most useful and sensible place to put the AngularJS project folder?

*How can I redirect from IndexController.php of the Admin area to the actual index.html of the AngularJS app?

Thanks in advance!

A: This does border on personal opinion, but here's how I see it:

*

*Your angularjs javascript code will need to be in the public folder (or symlinked) so it gets served, no way around that.

*To redirect you can use $this->response->redirect("http://example.com/my/ng/app", true); wherever you decide to put it

However I would say that redirecting is unnecessary. Why not put your angularjs template in the index.phtml of the view? All of your angular templates can be just phalcon views.
On a personal note, I started off doing a hybrid admin system part phalcon, part angularjs... and as I have gone on there is less and less phalcon in there; angularjs just makes a lot of it seem unnecessary. Now most of my pages start off getting their initial data from the controller to save an ajax request, and even having the templates served all in one go
<script type="text/javascript">
    var myInitialData = <?=json_encode( $dataFromController )?>;
</script>

<script type="text/ng-template" id="myTemplate">
    html for template ajax uses goes here
</script>

<div ng-controller="myController">
    <!-- controller can access data with $window.myInitialData -->
    html here
</div>

And then communicate with the phalcon controllers via json

A: phalcon.angular.bootstrap - Boilerplate for a non single page implementation of Angular, Phalcon, and Bootstrap
phalanx - A starter app with Phalcon PHP Framework and Angular
from https://packagist.org/packages/phalcon/awesome-phalcon


text:
Q: email from Apple - "Missing Push Notification Entitlement" I have been trying to submit an update to my app for 3 days now, and every time that I do I get an email from Apple stating:

Missing Push Notification Entitlement - Your app appears to include
  API used to register with the Apple Push Notification service, but the
  app signature's entitlements do not include the "aps-environment"
  entitlement.

I have tried everything that I can, including making brand new provisioning profiles, setting an entitlement.plist and everything that I do results in the same email shortly after submission. I have opened the provisioning profile I am using and it DOES include the aps-entitlement.
Xcode gives me no errors or warnings when I build or archive the app, so everytime I try something new I have to go through the same process.
Is there ANYTHING else I can do to update my app and add push notifications? I have looked at many other questions on here and on google and am tearing my hair out!
EDIT:
People continue to think that I haven't looked at other solutions. I have. From the question this has been linked to as already answered, here are the suggestions it makes:

Re-create the provisioning profile

I have done this. I also made brand new ones. I have verified that they include the aps-environment flag in them.

Re-create the provisioning profile

Again, I have done this. Many times now.

Open your Provisioning Profile in any Text Editor and search for
  "environment" and you must find: aps-environment

The profiles I am using have this.

Remove calls to the service

Not relevant as I am trying to ADD the service.

Enable the service and re-create the profile

Again, this has been done.

Re-create the provisioning profiles

And again.

Remove the library that is referencing the push notification system

As above, I am adding Push Notification, not looking to remove it as per the question linked here.
I don't want to come off as rude, but please understand that when I say I have spent 3 days looking for answers I am being serious. Not only does this question ask about REMOVING, not adding Push Notifications, I had already added information about trying these methods.
Can someone please help me, or should I just use one of my support tickets with Apple over this?

A: I have solved this, so here is the answer for others who may come across this in the future.
I had to delete the Entitlements plist I had created when trying to solve the issue earlier in the day, then recreate it through Xcode and add in the same information that was in my provisioning profile. I also had to do this on BOTH the project and the target.
I have not received the email over this submission, and the binary details on iTunes Connect now list "APS Environment: Production".
Thank you to dpassage and maddy who both attempted to help me with the question.


text:
Q: Question about the proof of $\Delta_d = 2\Delta_{\bar{\partial}} = 2\Delta_{\partial}$ in Principles of Algebraic Geometry by Griffiths and Harris. On page $115$ of Principles of Algebraic Geometry by Griffiths and Harris, in the proof of $\Delta_d = 2\Delta_{\bar{\partial}} = 2\Delta_{\partial}$, they state that
$$\sqrt{-1}(\partial\bar{\partial}^*+\bar{\partial}^*\partial) = \partial( \Lambda \partial -\partial \Lambda )+ (\Lambda \partial -\partial \Lambda)\partial = \partial \Lambda \partial - \partial \Lambda \partial.$$
I don't think the last line of equality is right, am I right?
I think it should be equal to: $\Lambda \partial \partial -\partial \partial \Lambda$, in which case why does it vanish?

A: Note that
\begin{align*}
\sqrt{-1}(\partial\bar{\partial}^* + \bar{\partial}^*\partial) &= \partial(\Lambda\partial - \partial\Lambda) + (\Lambda\partial - \partial\Lambda)\partial\\
&= \partial\Lambda\partial - \partial\partial\Lambda + \Lambda\partial\partial - \partial\Lambda\partial\\
&= \Lambda\partial\partial - \partial\partial\Lambda.
\end{align*}
As pointed out in the comments, on any complex manifold $\partial^2 = \partial\partial = 0$, so
$$\sqrt{-1}(\partial\bar{\partial}^* + \bar{\partial}^*\partial) = 0.$$
Note, the Kähler hypothesis was needed in order to use the Kähler identity
$$\sqrt{-1}\bar{\partial}^* = [\Lambda, \partial] = \Lambda\partial - \partial\Lambda.$$


text:
Q: One to many too much data returned - MySQL I have 2 related MySQL tables in a one to many relationship.
Customers: cust_id, cust_name, cust_notes
Orders: order_id, cust_id, order_comments
So, if I do a standard join to get all customers and their orders via PHP, I return something like:

*

*Jack Black, jack's notes, comments about jack's 1st order

*Jack Black, jack's notes, comments about jack's 2nd order

*Simon Smith, simon's notes, comments about simon's 1st order

*Simon Smith, simon's notes, comments about simon's 2nd order

The problem is that cust_notes is a text field and can be quite large (a couple of thousand words). So, it seems like returning that field for every order is inneficient.
I could use GROUP_CONCAT and JOINS to return all order_comments on a single row BUT order_comments is a large text field too, so it seems like that could create a problem.
Should I just use two separate queries, one for the customers table and one for the orders table?
Is there a better way?

A: If i understand your question correctly, it is better to use two query, for a results like:
Jack black
   comments
   comments
   comments
   comments

Simon Smith
   comments
   comments
   comments

A: Typically we used a few different strategies.
In one case we returned multiple result sets - one set for the parents and one for all the children.  The ORDER BY was the same, so that you could easily interleave the children for each parent in the client code.
It was also possible to return multiple result sets - one for the parents and one set of children for EACH parent (we used a cursor for the outer part of this).
Another thing we used (in SQL Server) was XML so it actually returned the hierarchical form.

A: You can run two queries, one for notes and one for the customer details.
// this will give you orders in an efficient way
SELECT cust_id, order_id, order_comments
FROM customers AS c
LEFT JOIN orders as o ON o.cust_id = c.cust_id
LIMIT xx, yy

// this will get all details from N specific customers
SELECT * FROM customers
WHERE cust_id = 'xxx' OR cust_id = 'yyy' OR cust_id = 'zzz'

And then pass the second query to an array and, as you're showing the first one, use the details from the customer that are stored in the array.
Should be pretty efficient.

A: Look. Your page is much like an question page on SO. A question first and answers below.
Noone bother to request it with one query!
Answers - yes, uses join, but to get names and id's only, not full user's info.
Nothing complicated.
Just use separate queries for the customer and for the list of orders


text:
Q: MongoDB incremental mapReduce, select only new documents, added after last mapReduce Let's say I have a collection with documents that looks like this (just simplified example, but it should show the scheme):
> db.data.find()
{ "_id" : ObjectId("4e9c1f27aa3dd60ee98282cf"), "type" : "A", "value" : 11 }
{ "_id" : ObjectId("4e9c1f33aa3dd60ee98282d0"), "type" : "A", "value" : 58 }
{ "_id" : ObjectId("4e9c1f40aa3dd60ee98282d1"), "type" : "B", "value" : 37 }
{ "_id" : ObjectId("4e9c1f50aa3dd60ee98282d2"), "type" : "B", "value" : 1 }
{ "_id" : ObjectId("4e9c1f56aa3dd60ee98282d3"), "type" : "A", "value" : 85 }
{ "_id" : ObjectId("4e9c1f5daa3dd60ee98282d4"), "type" : "B", "value" : 12 }

Now I need to collect some statistics on that collection. For example:
db.data.mapReduce(function(){
        emit(this.type,this.value);
     },function(key,values){
        var total = 0;
        for(i in values) {total+=values[i]};
        return total;
     },
{out:'stat'})

will collect totals in 'stat' collection.
> db.stat.find()
{ "_id" : "A", "value" : 154 }
{ "_id" : "B", "value" : 50 }

At this point everything is perfect, but I've stuck on the next move:

*

*'data' collection is constantly updated with new data (old documents stays unchanged, only inserts, no updates)

*I would like to periodically update 'stat' collection, but do not want to query the whole 'data' collection every time, so I choose to run incremental mapReduce

*It may seems good to just update 'stat' collection on every insert in 'data' collection and do no use mapReduce, but the real case is more complex than this example and I would like to get statistics only on demand.

*To do this I should be able to query only documents, that was added after my last mapReduce

*As far as I understand I cannot rely on ObjectId property, just store the last one and later select every document with ObjectId > stored because ObjectId is not equal autoincrement ids in SQL databases (for example different shards will produce different ObjectIds).

*I can change ObjectId generator, but not sure how to do it better in sharded environment

So the question is:
Is it any way to select only documents, added after the last mapReduce to run incremental mapReduce or may be there is another strategy to update statistic data on constantly growing collection?

A: You can get just the time portion of the ID using _id.getTime() (from: http://api.mongodb.org/java/2.6/org/bson/types/ObjectId.html).  That should be sortable across all shards.
EDIT: Sorry, that was the java docs...  The JS version appears to be _id.generation_time.in_time_zone(Time.zone), from http://mongotips.com/b/a-few-objectid-tricks/

A: You can cache the time and use it as a barrier for your next incremental map-reduce.
We're testing this at work and it seems to be working.  Correct me if I'm wrong, but you can't safely do map-reduce while an insert is happening across shards.  The versions become inconsistent and your map-reduce operation will fail.  (If you find a solution to this, please do let me know! :)
We use bulk-inserts instead, once every 5 minutes.  Once all the bulk inserts are done, we run the map-reduce like this (in Python):
m = Code(<map function>)
r = Code(<reduce function>)

# pseudo code
end = last_time + 5 minutes

# Use time and optionally any other keys you need here
q = bson.SON([("date" : {"$gte" : last_time, "$lt" : end})])

collection.map_reduce(m, r, out=out={"reduce": <output_collection>}, query=q)

Note that we used reduce and not merge, because we don't want to override what we had before; we want to combine the old results and the new result with the same reduce function.

A: I wrote up a complete pymongo-based solution that uses incremental map-reduce and caches the time, and expects to run in a cron job.  It locks itself so two can't run concurrently:
https://gist.github.com/2233072
""" This method performs an incremental map-reduce on any new data in 'source_table_name'
into 'target_table_name'.  It can be run in a cron job, for instance, and on each execution will
process only the new, unprocessed records.

The set of data to be processed incrementally is determined non-invasively (meaning the source table is not
written to) by using the queued_date field 'source_queued_date_field_name'. When a record is ready to be processed,
simply set its queued_date (which should be indexed for efficiency). When incremental_map_reduce() is run, any documents
with queued_dates between the counter in 'counter_key' and 'max_datetime' will be map/reduced.

If reset is True, it will drop 'target_table_name' before starting.

If max_datetime is given, it will only process records up to that date.

If limit_items is given, it will only process (roughly) that many items. If multiple
items share the same date stamp (as specified in 'source_queued_date_field_name') then
it has to fetch all of those or it'll lose track, so it includes them all.

If unspecified/None, counter_key defaults to counter_table_name:LastMaxDatetime.
"""

A: We solve this issue using 'normalized' ObjectIds. Steps that we are doing:

*

*normalize id - take timestap from the current/stored/last processed id and set other
parts of id to its min values. C# code: new ObjectId(objectId.Timestamp,
0, short.MinValue, 0)

*run map-reduce with all items that have id
greater than our normalized id, skip already processed items.

*store last processed id, and mark all processed items.

Note: Some boundary items will be processed several times. To fix it we set some sort of a flag in the processed items.


text:
Q: JSON -> Xcode stringformat I use this method to access my mysql database from Xcode:

NSString *URL = [NSString
  stringWithFormat:@"http://test.test:8888/test/loadUserData.php?username=%@",
  userName];
NSString *rawJSON = [[NSString alloc]
  initWithContentsOfURL:[NSURL
  URLWithString:URL]];
const char *convert = [rawJSON
  UTF8String]; NSString *responseString
  = [NSString stringWithUTF8String:convert];
if ([rawJSON length] == 0) {
      [rawJSON release];
}
SBJsonParser *parser = [[SBJsonParser
  alloc] init];
userInfo = [[parser
  objectWithString:responseString
  error:nil] copy]; SSN = [userInfo
  objectAtIndex:0];
[parser release];
return userInfo;

Everything works great. EXCEPT that I can't compare strings in the result with normal nsstrings. If I say
if ([userinfo objectAtIndex:0) == @"Dan")
{
..do something
}
Xcode never sees that it is the same value..
I don't know if there is something wrong with the format (My database is UTF-8)
And how can I convert the result so xCode can compare the response with NSStrings?
Thanks!

A: == does not compare the value of strings, it just compares their addresses.
Use
if ([[userinfo objectAtIndex:0] isEqualToString:@"Dan"]) { ... }

or something similar instead.

A: If you know for sure that you have string data on both sides of the condition you could use
if ([userinfo objectAtIndex:0] isEqualToString:@"Dan") {
    // summat...
}


text:
Q: How to add a libpcre3-dev and libpcre3 to docker image python:3.9-alpine3.13 when there is no such package? I need PCRE support for my uwsgi to running. So I planning to add libpcre3 and libpcre3-dev to my docker.
This is my Dockerfile settings:
FROM python:3.9-alpine3.13

ENV PYTHONUNBUFFERED 1

COPY ./requirements.txt /tmp/requirements.txt
COPY ./requirements.dev.txt /tmp/requirements.dev.txt
COPY ./scripts /scripts
COPY ./app /app
WORKDIR /app
EXPOSE 8000

ARG DEV=false
RUN python -m venv /py && \
    /py/bin/pip install --upgrade pip && \
    apk add --update --no-cache postgresql-client jpeg-dev libpcre3-dev libpcre3 && \
    apk add --update --no-cache --virtual .tmp-build-deps \
        build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \
    /py/bin/pip install -r /tmp/requirements.txt && \
    if [ $DEV = "true" ]; then /py/bin/pip install -r /tmp/requirements.dev.txt ; \
    fi && \
    rm -rf /tmp && \
    apk del .tmp-build-deps && \
    adduser \
        --disabled-password \
        --no-create-home \
        django-user && \
    mkdir -p /vol/web/media && \
    mkdir -p /vol/web/static && \
    chown -R django-user:django-user /vol && \
    chmod -R 755 /vol && \
    chmod -R +x /scripts

ENV PATH="/scripts:/py/bin:$PATH"

And this is the error that I get:
 > [recipe-app-api-app 7/7] RUN python -m venv /py &&     /py/bin/pip install --upgrade pip &&     apk add --update --no-cache postgresql-client jpeg-dev libpcre3-dev libpcre3 &&     apk add --update --no-cache --virtual .tmp-build-deps         build-base postgresql-dev musl-dev zlib zlib-dev linux-headers &&     /py/bin/pip install -r /tmp/requirements.txt &&     if [ false = "true" ]; then /py/bin/pip install -r /tmp/requirements.dev.txt ;     fi &&     rm -rf /tmp &&     apk del .tmp-build-deps &&     adduser         --disabled-password         --no-create-home         django-user &&     mkdir -p /vol/web/media &&     mkdir -p /vol/web/static &&     chown -R django-user:django-user /vol &&     chmod -R 755 /vol &&     chmod -R +x /scripts:
#0 4.542 Requirement already satisfied: pip in /py/lib/python3.9/site-packages (21.2.4)
#0 4.820 Collecting pip
#0 4.970   Downloading pip-22.3.1-py3-none-any.whl (2.1 MB)
#0 5.584 Installing collected packages: pip
#0 5.584   Attempting uninstall: pip
#0 5.584     Found existing installation: pip 21.2.4
#0 5.680     Uninstalling pip-21.2.4:
#0 5.688       Successfully uninstalled pip-21.2.4
#0 7.017 Successfully installed pip-22.3.1
#0 7.268 fetch https://dl-cdn.alpinelinux.org/alpine/v3.13/main/x86_64/APKINDEX.tar.gz
#0 7.753 fetch https://dl-cdn.alpinelinux.org/alpine/v3.13/community/x86_64/APKINDEX.tar.gz
#0 8.331 ERROR: unable to select packages:
#0 8.356   libpcre3 (no such package):
#0 8.356     required by: world[libpcre3]
#0 8.356   libpcre3-dev (no such package):
#0 8.356     required by: world[libpcre3-dev]
------
failed to solve: executor failed running [/bin/sh -c python -m venv /py &&     /py/bin/pip install --upgrade pip &&     apk add --update --no-cache postgresql-client jpeg-dev libpcre3-dev libpcre3 &&     apk add --update --no-cache --virtual .tmp-build-deps         build-base postgresql-dev musl-dev zlib zlib-dev linux-headers &&     /py/bin/pip install -r /tmp/requirements.txt &&     if [ $DEV = "true" ]; then /py/bin/pip install -r /tmp/requirements.dev.txt ;     fi &&     rm -rf /tmp &&     apk del .tmp-build-deps &&     adduser         --disabled-password         --no-create-home         django-user &&     mkdir -p /vol/web/media &&     mkdir -p /vol/web/static &&     chown -R django-user:django-user /vol &&     chmod -R 755 /vol &&     chmod -R +x /scripts]: exit code: 2

So there is anything that can I do to add the following package?
I already trying installing with different name and searching a lot online, and still doesn't have an idea to add those package.

A: Finally I can get my uwsgi run with installing pcre-dev package which mention by β.εηοιτ.βε on Cannot install uwsgi on Alpine
So, this is my final Dockerfile settings:
FROM python:3.9-alpine3.13

ENV PYTHONUNBUFFERED 1

COPY ./requirements.txt /tmp/requirements.txt
COPY ./requirements.dev.txt /tmp/requirements.dev.txt
COPY ./scripts /scripts
COPY ./app /app
WORKDIR /app
EXPOSE 8000

ARG DEV=false
RUN python -m venv /py && \
    /py/bin/pip install --upgrade pip && \
    apk add --update --no-cache postgresql-client jpeg-dev pcre-dev && \
    apk add --update --no-cache --virtual .tmp-build-deps \
        build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \
    /py/bin/pip install -r /tmp/requirements.txt && \
    if [ $DEV = "true" ]; then /py/bin/pip install -r /tmp/requirements.dev.txt ; \
    fi && \
    rm -rf /tmp && \
    apk del .tmp-build-deps && \
    adduser \
        --disabled-password \
        --no-create-home \
        django-user && \
    mkdir -p /vol/web/media && \
    mkdir -p /vol/web/static && \
    chown -R django-user:django-user /vol && \
    chown -R django-user:django-user ./* && \
    chmod -R 755 /vol && \
    chmod -R +x /scripts

ENV PATH="/scripts:/py/bin:$PATH"

USER django-user


text:
Q: how to normalize angle radian value to 2*pi? I have to adjust the angle's radian value between [0,2pi) if it is negative angle or too big angle than 2pi.
My code is as follows, and I haven't found the related library:
def normalize(angle) do
  rem(round(angle * 1000), round((2 * :math.pi * 1000))) / 1000
end

Is there a better way to improve it?

A: If I properly understood the intent, what you need is to add/subtract the integer number of 2πs to bring the angle to the interval. Use Kernel.floor/1 to calculate the number of full turnarounds. Luckily enough, it works for negative numbers out of the box, thanks to wise floor/1 implementation.
angle - 2 * :math.pi * floor(angle / (2 * :math.pi))


text:
Q: Is Alloy an example of Answer Set Programming I've been looking at ASP and am wondering about the relationship between these two approaches since they both use SATsolvers at the backend.although there is little or no overlap in the literature.  I'd appreciate a simple comparision of the two.
(This question was also asked on the CS StackExchange
https://cs.stackexchange.com/questions/14633/why-is-alloy-not-an-answer-set-programming-system
)


text:
Q: Checking if a byte is ascii printable I am reading in a file using binary settings:
with open(filename, 'rb') as f:

I am then reading the entire file into a variable:
x = f.read()

My problem is that I want to check if the bytes in x are ascii printable. So i want to compare the bytes to see if they are within the range of say 32-128 in decimal notation. What would be the easiest way to go about doing this?
I have toyed around with the ord() function, various hex functions since I have previously converted the bytes into hex elsewhere in my project, but nothing seems to be working.
I'm new to python but have experience in other languages. Can anyone point me in the right direction? Thanks.

A: You could check each byte against string.printable.
>>> import string
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

printable_chars = bytes(string.printable, 'ascii')
with open(filename, 'rb') as f:
    printable = all(char in printable_chars for char in f.read())

For greater efficiency, O(1) vs O(n) for the set vs string lookup, use a set:
printable_chars = set(bytes(string.printable, 'ascii'))
with open(filename, 'rb') as f:
    printable = all(char in printable_chars for char in f.read())


text:
Q: sys:1: RuntimeWarning: coroutine '' was never awaited Error with python I'm making a automated version of airgeddon or the air tools to capture handshakes for testing. There's a python lib called "pyrcrack" I'm using though it uses async functions. I'm not sure what I can do about this error as I have little experience with async as a whole.
here's the code and error
#FILE 1
    networkInterface = input(Fore.GREEN + "\n[?] Enter the network interface: ")

    Networks = Tools.FindNetworks(networkInterface)
    print(Networks)

#FILE 2

    async def FindNetworks(NetWrkInterface):
        print(Fore.GREEN + f"[!] Listening For Nearby Networks\n** 1NF0 **\nNetwork Interface ==> {NetWrkInterface}\n")
        async with airmon(NetWrkInterface) as mon:
            async with pyrcrack.AirodumpNg() as pdump:
                async for result in pdump(mon.monitor_interface):
                    return result

Error Code
sys:1: RuntimeWarning: coroutine 'FindNetworks' was never awaited


text:
Q: getAttribute(value) returns null even when the value exists when running the code locally I'm trying to debug a ASP.Net site. The code is debugged using Visual Studio 2012 and is running locally using IIS Express on my Windows 10 machine. The web application needs to be run using Internet Explorer 11.
When I run the code, I get an exception that is caught by Visual Studio, in the on-page JavaScript (in a piece of code not shown below). I know for a fact that the code is already out in production and it 100% works. However when I debug the code locally it fails to work as expected.
Here's the code in question:
var elements = document.getElementsByTagName('input');
for(var i = 0; i < elements.length; i++) {
    var value = elements[i].getAttribute('value');
    //....
}

When I run the code locally the elements[i].getAttribute('value') returns null. However when I run this same code in production it works fine. When I debug the code, I can see that the elements[i] has an actual value stored in the "value" attribute, however the above code still returns null.
I'm not allowed to change the code (due to reasons) and since my colleague is able to run the code on his machine using the same setup, I'm inclined to think it's a configuration issue on my machine in either Visual Studio or something else.
I'm open to any suggestions as to what might be the cause.

A: I tried to test your above-mentioned code and it is working fine in IE 11 browser.

<!doctype html>

<input type="text" name="FirstName" value="abc">

<input type="text" name="LastName" value="xyz">

Output:

It can be a cache related issue. I suggest you clear the cache for that site or hard refresh the page and again try to check the results.
If the issue persists then try to provide more detailed information about the issue. We will again try to check it.

A: After a bit more searching and talking to my colleagues I was advised to turn on Enterprise Mode (Tools -> Enterprise Mode) in Internet Explorer.
This, according to this article, renders the page like it would have been rendered in IE8. From what I can tell it also resolves the issue I was seeing.
I hope this can help someone in the future.