text:
Q: SKScene file rendered by SpriteView shows empty grey background/box? I'm trying to render my SKScene file using SpriteView(). Instead of displaying the scene, it just displays an empty grey background. I tried this with two different SKScene files, and they both were rendered as a grey background.
However, if I define and initialise a new SKScene completely in code (i.e. not using a SKScene file and the visual editor), and render it using SpriteView(), it works fine.
What could I be doing wrong?

Here is an example of my test code:
This is the code for rendering SKScene file. Result: Grey screen. Note GameScene is an SKScene file, with accompanying swift file.
import SwiftUI
import SpriteKit

var scene: SKScene {
    let scene = GameScene()
    scene.scaleMode = .aspectFill
    return scene
}

struct ContentView: View {
    var body: some View {

        SpriteView(scene: scene)
            .ignoresSafeArea()
    }
}

//  to view canvas
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Code for creating a SKScene completely in code. Result: displays scene properly, and interactions work.
import SwiftUI
import SpriteKit

class CodeScene: SKScene {
    override func didMove(to view: SKView) {
        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        let box = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
        box.position = location
        box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
        addChild(box)
    }
}

// A sample SwiftUI creating a GameScene and sizing it
// at 300x400 points
struct ContentView: View {
    var scene: SKScene {
        let scene = CodeScene()
        scene.size = CGSize(width: 300, height: 400)
        scene.scaleMode = .fill
        return scene
    }

    var body: some View {
        SpriteView(scene: scene)
            .frame(width: 300, height: 400)
            .ignoresSafeArea()
    }
}

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

Edit: Added Game Scene swift file:
import SpriteKit

class GameScene: SKScene {

    private var Player: SKSpriteNode!

    override func didMove(to view: SKView) {
        Player = childNode(withName: "//Player") as? SKSpriteNode
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        guard let touch = touches.first else { return }
        let touchLocation = touch.location(in: self)
        let distance = sqrt(pow(touchLocation.x - Player.position.x, 2) + pow(touchLocation.y - Player.position.y, 2))
        let speed: CGFloat = 120.0 // adjust as needed
        let duration = TimeInterval(distance / speed)
        let moveAction = SKAction.move(to: touchLocation, duration: duration)
        Player.run(moveAction)
    }

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
    }
}


text:
Q: Money-Rails Gem and Instance Currencies I am trying to use the money-rails gem in my rails 4 app.
I have a participant model which has attributes for each of currency and participation_cost in it. My objective is for users to specify a currency for each instance, and an amount of the cost of participation.
In my participant model, I have:
monetize :participation_cost, with_model_currency: :amount_currency
In my form, i ask users to select a currency and specify an amount as follows:
<%= f.input :participation_cost, label: 'What amount will you pay for participation costs?', :label_html => { :class => 'question-participants' }, placeholder: 'Whole numbers only', :input_html => {:style=> 'width: 250px; margin-top: 20px',  class: 'response-participants'} %>

<%= f.input :currency, label: 'Select your costs currency', label_html: {class: 'fundingspace'}, collection: ["AUD Australian Dollars", "GBP British Pounds", "USD US Dollars" ], prompt: "Choose one" %>

In my view, I want to display the currency and the amount. I currently have a string as follows:
  <%=  "#{@project.scope.try(:participant).try(:participation_cost)} #{@project.scope.try(:participant).try(:currency)}" %>

When I test this, I only get the number that is the participation_cost. I don't get the currency.
In my money.rb initialiser, I have:
 config.default_currency = :gbp

Can anyone help? I don't know how to use this gem. I've followed the user guide but it only gets as far as setting up the model for instance based currency selections. Has anyone successfully used it for this purpose?
Thank you

A: Steps:

*

*Add column type money
Rails 3
add_money :table_name, :participation_cost
Rails 4
add_monetize :table_name, :participation_cost
This will give you two columns
:participation_cost_pennies #pennies if GBP, cents if USD
:participation_cost_currency

*In model
The below line override default and global currency for this column and will use currency in this column
monetize :participation_cost_pennies, with_model_currency: :participation_cost_currency

*Just update your fields in form and save currency as you were saving but in participation_cost_currency column.
If you don't want pennies at end or participation_cost in currency column you can modify that in Money.rb. See here

redpajama_set_name: RedPajamaStackExchange


text:
Q: batch file read from file toa array variable I got a list in text file (names.txt) like this:
This is documment no....... etc
Sent : 20.04.2013
Details for ............. etc
Num : 1
Name : John
Surname : White
Born : 09/17/1993
Num : 2
Name : Peter
Surname : Tosh
Born : 09/14/1991
.............
.............
This documment can not............
@echo off

setlocal enabledelayedexpansion

for /F "delims=" %%a in (C:\tmp\names.txt) do (
    set /A count1+=1
    set "array!count1!=%%a"
)
set /A count1-=1

set /A count2=1
set /A count3=2

for /L %%i in (4,4,%count1%) do (
    set /A count2+=4
    set /A count3+=4
    echo !array%%i!  !array%count2%!  !array%count3%!
)

I want to list them like
Num : 1 Name :John Surname : White
Num : 2 Name :Peter Surname : Tosh
Num : 3 Name :Me Surname : Myself
..............
Just 3 data in one row but doesnt work. What I'm doing wrong?

A: The Batch file below solve the problem as stated; it does not require any array:
@echo off
setlocal EnableDelayedExpansion

set "Surname="
for /F "tokens=1,2 delims=: " %%a in (C:\tmp\names.txt) do (
   set "%%a=%%b"
   if defined Surname (
      echo Num : !Num! Name : !Name! Surname : !Surname!
      set "Surname="
   )
)

Output:
Num : 1 Name : John Surname : White
Num : 2 Name : Peter Surname : Tosh

A: Test this to see if it does what you need:
@echo off
for /F "usebackq delims=" %%a in ("C:\tmp\names.txt") do (
  set /p "=%%a "<nul
  echo "%%a" |find /i "Born" >nul && echo(
)
pause

A: How about this:
echo off
setlocal enabledelayedexpansion

set xSurname=
for /f "tokens=1,2 delims=: " %%a in (%TEMP%\names.txt) do (
    if /i '%%a'=='Num' set xNum=%%b
    if /i '%%a'=='Name' set xName=%%b
    if /i '%%a'=='Surname' set xSurname=%%b
    if not '!xSurname!'=='' (
        echo Num: !xNum! Name: !xName! Surname: !xSurname!
        set xSurname=
    )
)

Makes assumptions that the Surname line ends a block (Born: is ignored) and outputs what it has gathered to that point in the block.  Note I changed the path to %TEMP% vs C:\tmp.  You probably would do better using %TEMP% as that's set by the operating system.


text:
Q: Rsync combined with FIND and mtime I've been thinking about how I could copy files that are 0-30 days old with different file types with rsync, find and mtime.
Thefind syntax below works, but I do not get it to work with rsync.
rsync \ --files-from=<(find . -type f \( -name "*.X" -or -name "*.x1" \) -mtime -30) user@x.x.x.x:/where/to/put/files

A: It works if you use add a SRC argument (the . as source directory):
rsync --files-from=<(find . -type f \( -name "*.X" -o -name "*.x1" \) -mtime -30) . user@x.x.x.x:/where/to/put/files


text:
Q: Why is the rendering of ui::Text components which use UTF-8 strings being limited when I run my cocos2dx game on an android device? I'm developing a game in C++ on the cocos2dx game engine. I've mostly been testing it on the win32 platform but recently tried it out on android. When I did I found things were not running as expected. In case you're wondering, I'm running the apk on Android Oreo (8.0.0) on a Samsung Galaxy S7.
The first thing I noticed is that some components which were rendered on win32 weren't being rendered on android.
I'm trying to gain a better understanding of why that is but after a few days of digging through online help boards, source code and tutorials I haven't found anything particularly promising.
Here's an example of an issue:
I have a cocos2d::Scene which has a number of ui::Text components which display some text. If the ui::Text components are initialised without any UTF-8 characters, they appear to be rendered without issue.
However, if they are initialised with UTF-8 characters, some will be rendered and some won't. Even after running the adb with the jni debugger, I haven't found any helpful error messages and the program continues to run.
Here's some sample code:

using namespace cocos2d;

Scene* MainMenuScene::createScene()
{
    return MainMenuScene::create();
}

bool MainMenuScene::init()
{
    if ( !Scene::init() )
    {
        return false;
    }

 auto visibleSize = Director::getInstance()->getVisibleSize();

    auto ichi = ui::Text::create(u8"一", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto ni = ui::Text::create(u8"二", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto san = ui::Text::create(u8"三", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto yon = ui::Text::create(u8"四", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto go = ui::Text::create(u8"五", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto roku = ui::Text::create(u8"六", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto nana = ui::Text::create(u8"七", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto hachi = ui::Text::create(u8"八", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto kyuu = ui::Text::create(u8"九", "fonts/rounded-mgenplus-1c-black.ttf", 24);

    auto ichi_h = ui::Text::create(u8"いち", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto ni_h = ui::Text::create(u8"に", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto san_h = ui::Text::create(u8"さん", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto yon_h = ui::Text::create(u8"よん", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto go_h = ui::Text::create(u8"ご", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto roku_h = ui::Text::create(u8"ろく", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto nana_h = ui::Text::create(u8"なな", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto hachi_h = ui::Text::create(u8"はち", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto kyuu_h = ui::Text::create(u8"きゅう", "fonts/rounded-mgenplus-1c-black.ttf", 24);

    auto ichi_k = ui::Text::create(u8"イチ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto ni_k = ui::Text::create(u8"ニ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto san_k = ui::Text::create(u8"サン", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto yon_k = ui::Text::create(u8"ヨン", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto go_k = ui::Text::create(u8"ゴ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto roku_k = ui::Text::create(u8"ロク", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto nana_k = ui::Text::create(u8"ナナ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto hachi_k = ui::Text::create(u8"ハチ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto kyuu_k = ui::Text::create(u8"キュウ", "fonts/rounded-mgenplus-1c-black.ttf", 24);

    auto layout = ui::Layout::create();
    layout->setLayoutType(ui::Layout::Type::HORIZONTAL);
    layout->setPosition(Vec2(0, visibleSize.height));

    auto layout_kan = ui::Layout::create();
    layout_kan->setLayoutType(ui::Layout::Type::VERTICAL);
    layout_kan->setContentSize(Size(2 * kyuu_h->getContentSize().width, visibleSize.height));

    auto layout_h = ui::Layout::create();
    layout_h->setLayoutType(ui::Layout::Type::VERTICAL);
    layout_h->setContentSize(Size(2 * kyuu_h->getContentSize().width, visibleSize.height));

    auto layout_k = ui::Layout::create();
    layout_k->setLayoutType(ui::Layout::Type::VERTICAL);
    layout_k->setContentSize(Size(2 * kyuu_h->getContentSize().width, visibleSize.height));

    layout_kan->addChild(ichi);
    layout_kan->addChild(ni);
    layout_kan->addChild(san);
    layout_kan->addChild(yon);
    layout_kan->addChild(go);
    layout_kan->addChild(roku);
    layout_kan->addChild(nana);
    layout_kan->addChild(hachi);
    layout_kan->addChild(kyuu);

    layout_h->addChild(ichi_h);
    layout_h->addChild(ni_h);
    layout_h->addChild(san_h);
    layout_h->addChild(yon_h);
    layout_h->addChild(go_h);
    layout_h->addChild(roku_h);
    layout_h->addChild(nana_h);
    layout_h->addChild(hachi_h);
    layout_h->addChild(kyuu_h);

    layout_k->addChild(ichi_k);
    layout_k->addChild(ni_k);
    layout_k->addChild(san_k);
    layout_k->addChild(yon_k);
    layout_k->addChild(go_k);
    layout_k->addChild(roku_k);
    layout_k->addChild(nana_k);
    layout_k->addChild(hachi_k);
    layout_k->addChild(kyuu_k);

    layout->addChild(layout_kan);
    layout->addChild(layout_h);
    layout->addChild(layout_k);

    this->addChild(layout);

    return true;
}

Here's what that looks like on win32:

Here's what that looks like on android:

The order of instantiation of the ui::Text components appears to affect how many of them are rendered and prioritisation for rendering appears to depend on the order of instantiation. However, occassionally a later instantiated ui::Text will be displayed when those instantiated before it aren't.
Here's what happened when I instantiated the same ui::Text components in the following order:
    auto ichi = ui::Text::create(u8"一", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto ni = ui::Text::create(u8"二", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto san = ui::Text::create(u8"三", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto yon = ui::Text::create(u8"四", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto go = ui::Text::create(u8"五", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto roku = ui::Text::create(u8"六", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto nana = ui::Text::create(u8"七", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto hachi = ui::Text::create(u8"八", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto kyuu = ui::Text::create(u8"九", "fonts/rounded-mgenplus-1c-black.ttf", 24);

    auto ichi_k = ui::Text::create(u8"イチ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto ni_k = ui::Text::create(u8"ニ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto san_k = ui::Text::create(u8"サン", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto yon_k = ui::Text::create(u8"ヨン", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto go_k = ui::Text::create(u8"ゴ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto roku_k = ui::Text::create(u8"ロク", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto nana_k = ui::Text::create(u8"ナナ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto hachi_k = ui::Text::create(u8"ハチ", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto kyuu_k = ui::Text::create(u8"キュウ", "fonts/rounded-mgenplus-1c-black.ttf", 24);

    auto ichi_h = ui::Text::create(u8"いち", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto ni_h = ui::Text::create(u8"に", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto san_h = ui::Text::create(u8"さん", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto yon_h = ui::Text::create(u8"よん", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto go_h = ui::Text::create(u8"ご", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto roku_h = ui::Text::create(u8"ろく", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto nana_h = ui::Text::create(u8"なな", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto hachi_h = ui::Text::create(u8"はち", "fonts/rounded-mgenplus-1c-black.ttf", 24);
    auto kyuu_h = ui::Text::create(u8"きゅう", "fonts/rounded-mgenplus-1c-black.ttf", 24);

Here's what that looks like on android:

Other potentially relevant information:

*

*Increasing the amount of other ui components appears to decrease the
amount of UTF-8 initialised ui::Text components which are rendered.

*The ui:Text components which are rendered and those which aren't
appears to remain consistent for a set block of code. In other words,
the GUI output doesn't seem to vary with the same code on different
runs.

*ui::Text components which don't use UTF-8 strings seem not to be
affected and are always displayed.

*Removing the u8 prefix from the strings gives the same results on
android (missing components but those which are rendered are shown as
expected) and leads to characters being represented by ???'s on
win32.

*When I compile on win32 there is no such issue and all ui::Text
components are displayed regardless of which character set is used.

*I'm specifically using Japanese characters (including kanji, hiragana
and katakana) but presumably this is an issue for all UTF-8
characters.

I would like to know why this is happening and what I can do to circumvent it without resorting to hacks.
I will continue to look further into the documentation and source code to try and better understand the root of the issue, but I get the sense that this might be something to do with Android's guarded internals. Ahem.
So far I've been reading through android's documentation on the JNI, NDK and OpenGL and worming my way through all the potentially relevant cocos2dx and android classes I can. I also read through the sections of C++ programming pertaining to strings and locales but it doesn't seem like there's much I'd be able to do without bypassing the cocos2dx framework.
I wonder if the issue might be caused by some JNI restriction or buffering bug. Or perhaps it's something to do with versioning or hardware. Maybe it's something to do with the app being run in debug mode? Also I'm aware that Java uses UTF-16 for its strings internally so I suppose that could also be throwing a spanner in the works somewhere...

A: This issue appears to have stemmed from a couple of bugs in the Cocos2dx game engine. Please see the Github issue posted in the comments for fixes.


text:
Q: iOS Core Data - Relationships I'm guessing this is a basic question and hopefully someone will be able to point me in the right direction to some sample code, so my question….
I want/have created a core data model that has a parent child relationship, one to many, what I would like to know is what is the correct way to insert child records if the parent already exists.  What I'm struggling to understand is how the parent relationship is created when only inserting child records.
Hopefully this makes sense, thanks for any help.

A: So you'll have Parent and Child. Child will contain a Parent *parentobject while Parent will contain a NSSet *children. Whenever you set the relationship correct in the Datamodel the relationship will be applied automatically when you fill the children set with Child objects.
Please check Articles here

A: Here You have a series of 3 tutorials: RayWenderlich: Core Data Tutorial
Here a sample app: iPhoneCoreDataRecipes with a more complex data model
Here a Core Data tutorial – One to Many Relationship
Sorry I not respond to your question in his totally. I'm also starting with Core Data, so If You find a good intermediate tuturial, please let me know.
EDIT:
A nice article: Core Data Class Overview


text:
Q: Problema creando un "In-Line editor" en angular 7 Hola mi problema es que tengo una tabla de comentarios:
HTML

            {{comment.user}} Has Say:

                edit

Quisiera saber como puedo usar el evento (click) para que al hacer click en el texto edit este se pueda modificar en la misma linea. Tengo un ckeditor creado, donde podría coger los datos que se están seleccionando. Pero mi idea es crear algo un poco mas intuitivo, donde al hacer click en edit el texto en cuestión se vuelva editable.

  edit

Hacedme saber si necesitáis que ponga parte del TS aquí y muchísimas gracias!

A: Como te decía, lo que puedes realizar es que tomas el id de la fila que estas iterando en tu ciclo o directiva *ngFor de Angular. Al tomarlo lo que generas es un cambio de sección, lo que antes era solo un texto ahora será un input o textarea. El ejemplo a continuación de lo que deberías hacer:
COMPONENTE HTML

      #
      Nombre
      Código
      Precio
      Descripción
      Opción

        {{producto.id_producto}}

        {{producto.nombre_producto}}

        {{producto.codigo_producto}}

        {{producto.precio_producto}}

{{producto.descripcion_producto}}

        <textarea rows="5">
          {{producto.descripcion_producto}}
        </textarea>

        <button (click)="evaluarCampo(producto)" *ngIf="campo">Editar</button>
        <button (click)="evaluarCampo(producto)" *ngIf="producto.id_producto == id_producto">Cancelar</button>

COMPONENTE TYPESCRIPT
export class AppComponent  {
  //Variables a implementar
  id_producto:any;
  campo:boolean = true;

  //Arreglo
  productos: any[] = [
    {
      'id_producto':'1',
      'nombre_producto': 'Apple iPhone X',
      'codigo_producto':'COD0001',
      'precio_producto':'25000',
      'descripcion_producto':'Desde un principio el objetivo de Apple fue crear un iPhone que fuera todo pantalla. Un dispositivo tan envolvente que prácticamente desapareciera al usarlo. Tan inteligente que respondiera a un toque, a una palabra o a una mirada.',
    },
    {
      'id_producto':'2',
      'nombre_producto':'Laptop Gamer HP - CX0001la',
      'codigo_producto':'COD0002',
      'precio_producto':'35000',
      'descripcion_producto':'La nueva HP Pavilion Gaming cuenta con la última tecnología en gráficos NVIDIA® GeForce® GTX™ y procesador Intel® para juegos, creación de contenidos y aplicaciones de alta productividad.',
    },
    {
      'id_producto':'3',
      'nombre_producto':'Laptop Alienware 15',
      'codigo_producto':'COD0003',
      'precio_producto':'45000',
      'descripcion_producto':'Experimente los juegos en un nivel completamente nuevo con la próxima generación de GPU NVIDIA GeForce GTX serie 10. Aproveche la potencia suficiente para alimentar las tarjetas gráficas de 100 W, así como los procesadores i5 HQ de la serie overclocking, que permiten juegos de 4k y están listos para la realidad virtual.',
    },
  ];

  //Metodo de evaluacion o accion del campo
  evaluarCampo(producto)
  {
    const id = producto.id_producto;

    console.log("ID: ", id);
    //Evaluamos el valor del campo, para saber que debemos mostrar
    if (this.campo == true)
    {
      //Ocultamos el campo
      this.campo = false;
      //Mandamos la variable con la que vamos a comparar el id de la fila
      this.id_producto = id;
    }
    else
    {
      //Dado que es verdadero, quiere decir que debemos mostrar el campo de texto
      this.campo = true;
      this.id_producto = '';
    }
  };
}

MEJORA
Para evitar que el campo se oculte en cada una de las iteraciones de la directiva, lo que debes realizar es el cambio del condicional que esconde el párrafo:
--- Antes: Le decíamos que ocultara todos los campos que estuvieran con el valor booleano (campo)

{{producto.descripcion_producto}}

--- Después: Lo que le decimos es que no me vaya a ocultar la sección que sea diferente al identificador (id_producto) seleccionado por el cliente.

{{producto.descripcion_producto}}

EJEMPLO FUNCIONAL
Te dejo un ejemplo de lo que adjunté en la respuesta, para que lo puedas modificar y/o adicionar de acuerdo a lo que tu propongas. clic aquí

Nota: Es solo un ejemplo de lo que debes realizar teniendo en cuenta lo que estás pidiendo en tu pregunta. Ya tendrías que jugar un poco con la lógica que requieras.


text:
Q: How to detect if a user received a text message? Is there a way to detect, from your app, if the user received a text message. If this would be possible, what steps would have to be done to implement it?

A: No, you can't. There is no public API available to monitor the messaging app activities. So you can't never detect whether SMS Sent or Received.

A: AppDelegate's method applicationWillResignActive should do the trick (Though it will also be called for other things than just SMS messages).
It's called for incoming SMS messages, quoted right from Apple's documentation:

This method is called to let your app know that it is about to move from the active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the app and it begins the transition to the background state. An app in the inactive state continues to run but does not dispatch incoming events to responders.

This is something we've used historically to pause our game when a text comes in. I haven't confirmed it works in iOS12 but at the time of posting this was definitely valid, Apple's docs even still state the SMS-message text for this callback, which leads me to believe it's valid.


text: Q: SiriKit Payment to an organization? Someone asked this same question and it got closed for being too vague, but I have this exact problem and it hasn't been answered anywhere else. SiriKit Payment doc says it works User-to-User, but is there any way to make this pay a bill for services? In other words, can the receiving "user" be a bank or somehow be re-routed to a bank or a server for payment processing?


text:
Q: How to do exception handling in flux Exception is thrown from one flux but second flux is not able to catch it. Is there anything missing in this code?
            public static void main(String[] args) {
                Flux<Integer> fluxFromJust = Flux.just(1, 2,3,4,5);
                fluxFromJust.doOnNext(t -> {
                    try {
                        test();
                    } catch (Exception exception) {
                       //System.out.println("------hello-------");
                    }
                }).subscribe();
            }

            public static void test() throws Exception{
                Flux<Integer> fluxFromJust = Flux.just(1, 2,3,4,5)
                        .concatWith(Flux.error(new RuntimeException("Test")))
                        .concatWith(Flux.just(6))
                        .map(i->i*2)
                        .onErrorMap(e -> new Exception(e) );
                fluxFromJust.subscribe();
            }
        }```
Catch of the calling function is not called. Is there anything missing?


text:
Q: Row-Wise Pattern Replace with Replacement Value Coming from Another Column My data is like this:
Item | Process
ABC  | XYZ-ABC
AC   | XYZ-AC
AD   | XYZ-AD
AEM  | XYZ-AEM
AF   | XYZ-AF
AG   | WXY-AG
AHSG | WXY-AHSG
AI   | WXY-AI
AJ   | WXY-AJ

The Process column starts with a certain string, to which the value in the Item column is appended. Only the starting string should be retained. The values in the Item column and their lengths can vary. I want to do a row-wise gsub() where the pattern is the value in Item, the replacement is '' (blank) and the target is the Process column.
I cannot just strip everything after the "-" in Process because the delimiter can change. I don't care if the delimiter is left behind, as long as the rest gets removed. Also, the length of the starting string in Process can vary.
Here is what I've tried so far using data.table:
myData[grep(Item, Process), gsub(Item, "", Process)]

This works for the first row, but all remaining rows remain unchanged. I understand that this is because gsub() can take only a single pattern, and I'm providing multiple. I'm looking for a very efficient and quick way of achieving this. My data can have > 4 million rows. This is going to happen in a Shiny application, and I don't want to keep users waiting while this happens. Please help!

A: If you want to do this in row-wise manner you can use str_replace from stringr which is vectorised over both string and pattern
stringr::str_replace(df$Process, df$Item, "")
#[1] "XYZ-" "XYZ-" "XYZ-" "XYZ-" "XYZ-" "WXY-" "WXY-" "WXY-" "WXY-"

Or str_remove which is an alias for str_replace(string, pattern, "")
stringr::str_remove(df$Process, df$Item)

data
df <- structure(list(Item = c("ABC", "AC", "AD", "AEM", "AF", "AG",
"AHSG", "AI", "AJ"), Process = c("XYZ-ABC", "XYZ-AC", "XYZ-AD",
"XYZ-AEM", "XYZ-AF", "WXY-AG", "WXY-AHSG", "WXY-AI", "WXY-AJ"
)), class = "data.frame", row.names = c(NA, -9L))


text:
Q: How do I import other modules in a script typescript I am a typescript newbie. I don't know how to reference (import) a module in a script
In my index.html file I am referencing
<script src="main.js"></script>

and in the main.ts file I am trying to import another typescrtipt module
import greet from './greeter';
greet();

and in the greeter.ts file I am exporting a function
export default function greet(): void {
  console.log('Hello World');
}

But in the browser console I see an error that says Uncaught ReferenceError: exports is not defined
Here's my tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

I tried changing the "module" property to "es2015" but it does not work.

A: Okay, I figured out that I don't need to import that module. I can just add another script tag before the existing script tag which links to the greeter.js
<script src="greeter.js"></script>

and then I do not need to export in greeter.ts or import in main.ts


text:
Q: Can I display/create jsTree on button click? I have a div id="result" that I use to display results of users actions. I put there plain text and html too. After each user action this div is overwritten with new results.
Now I want to display inside this div an instance of jsTree I have working jsTree that loads nicely on page load but it doesn't load after

 is inserted inside my result div.
I tried two lines below but none worked.
 $("#tree").jstree("loaded");
 $("#tree").jstree("refresh");

Any idea how to make the jsTree to be displayed a after button click? Please play on jsfiddle where you can see one tree already and I want another to be displayed after clicking the button. I am after the tree not the text.
I think I need to reload or refresh the tree after I place jstree div inside html.

A: tree2 was not created in the first place since
 was not there when you call '$("#tree2").jstree'.
So when you press the button, first tree is correctly refreshed but tree2 is not shown for the reason above.
At button pressed, you have to recreate tree2 by calling '$("#tree2").jstree', or you can just hide
 when you call $("#tree2").jstree. I just updated your fiddle ( http://jsfiddle.net/fmn6g/10/) so you can try.

A: To make it happen on a Button Click, just do this:

Remember to change button-id to the actual id of the button.
Hope this helps.


text:
Q: Where to find out database table object in simple JPA repository I am new to Spring Boot and trying to work with JPA repository. I am trying to find out where does spring SimpleJpaRepository class save database table at runtime to perform further retrieve operation. I have below service class to retrieve user based on username. In eclipse I am trying inspect userRepository at line 9 but I don't know where I can find the values fetched from DB table by spring. I know that User class will have the details I am trying to find out but I want to see where these details are in userRepository. Any help is much appreciated.
package com.hellokoding.auth.service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService{

@Autowired
private UserRepository userRepository;

@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
    User user = userRepository.findByUsername(username); //line 9
    if (user == null) throw new UsernameNotFoundException(username);

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()){
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
}
}

A: You are looking at the wrong library. Spring Data JPA is just a frontend for JPA (most likely Hibernate). In there you want to look for implementations of the EntityManager interface.


text:
Q: Unable to insert values into bytea type attribute while migrating from postgres 7.4 to postgres 9.2 I am migrating an application from postgres 7.4 to postgres 9.2. The query which worked fine for inserting bytea type attribure values in postgres 7.4 is throwing PSQLException with the below error in postgres 9.2.
ERROR:  syntax error at or near "\"
LINE 1: ...07\000\000\001\002\000\000|\012\000\000\'\007\000...(Error is shown near the single quote)
*** Error ***
ERROR: syntax error at or near "\"
SQL state: 42601
Character: 39081
I have read the postgres documentation about bytea_output which can be set to 'escape' to output the content of the attribute in escape format. It is also mentioned that bytea type attributes can accept both escape and hex format.
As the application was previously using postgres 7.4, we are using escape format. I wonder why this error is thrown if bytea can accept both escape and hex format in postgres 9.2. Please help in resolving this error.

A: bytea_output tells the format of bytea content in output columns, not when submitted as part of a SQL statement. As you guessed, it's probably not relevant here.
However, what may be relevant is the fact standard_conforming_strings has been set ON by default with PG 9.1 (I don't think it even existed in 7.4) so you can no longer use backslash to escape a single quote inside a literal.
See the compatibility flags and explanations in 9.2 doc: Previous PostgreSQL Versions, especially backslash_quote, escape_string_warning and standard_conforming_strings.
Short of fixing your app, the easy way out of the problem is to set standard_conforming_strings to off, and escape_string_warning to off if the amount of warnings in the logs is problematic (actually this warning is mostly useful in the process of fixing your app to standard strings conformance).
This can be done globally in the postgresql.conf file, which is located in the data directory. See Setting Parameters in the doc.

standard_conforming_strings=off
escape_string_warning=off


text:
Q: Find the distance from the point to the line
Find the distance from the point $P(3,-1,4)$ and the line whose parametric equations are: $x=-2 + 3t$, $y=-2t$, and $z=1+4t$

I'm not completely sure how to solve this so I first gave the parameter $t$ some initial values:
$t=0 = Q(-2,0,1)$
$t=1 = R(1,-2,5)$
$\overrightarrow {QR} = \langle 1+2, -2-0,5-1\rangle = \langle 3,-2,4 \rangle$
$\overrightarrow {QP} = \langle 3+2, -10-, 4-1\rangle = \langle 5, -1,3 \rangle$
$\overrightarrow {QR} \times \overrightarrow {QP} = -2i+11j+7k$
$d=\frac{|\overrightarrow {QR} \times \overrightarrow {QP}|}{|\overrightarrow {QR}|} = \frac{\sqrt{166}}{\sqrt{21}}$
Is this correct?

A: Let $S(-2+3t,-2t,1+4t)$ be a point on the line such that $PS$ is perpendicular to the line.
Then, we have $\vec{PS}=(-2+3t-3,-2t-(-1),1+4t-4)=(3t-5,-2t+1,4t-3)$. This is perpendicular to the vector $(3,-2,4)$, we have
$$(3t-5)\cdot 3+(-2t+1)\cdot(-2)+(4t-3)\cdot 4=0\iff t=1.$$
Thus, the minimum distance is the distance between $S(1,-2,5)$ and $P(3,-1,4)$, i.e.
$$\sqrt{(1-3)^2+(-2+1)^2+(5-4)^2}=\color{red}{\sqrt{6}}.$$

A: Applying distance formula gives: $D=\sqrt{(-2+3t-3)^2+(-2t+1)^2+(1+4t-4)^2}$
$$D^2=29t^2-58t+35$$
$$\frac{d}{dx}D^2=58t-58$$
So minimum distance when $t=1$.
Subbing this back in gives: $D_{min}=\sqrt{6}$.

A: HINT
You can solve tis problem in two ways :
1) For a generic point of the line
$$
\begin{bmatrix}
-2+3t\\
-2t\\
1+4t
\end{bmatrix}
$$
take the squared distance from $P$ and you have a function: $f(t)=\overline{PX}^2$. Find the minimum of this function and this is the searched distance.
2)
Take the plane orthogonal to the line and passing thorough $P$ ,i.e. the plane:
$$
\begin{bmatrix}
3\\
-2\\
4
\end{bmatrix}\cdot
\begin{bmatrix}
x-3\\
y+1\\
z-4
\end{bmatrix}=0
$$
the searched distance is the distance between $P$ and the intersection point of this plane with the line.


text:
Q: How could Finn know about Han Solo, given Finn's upbringing? In The Force Awakens, we learn that

*

*Luke has vanished and is now the stuff of myth and legend

*Han also vanished from the spotlight, having left the Republic/Resistance and is living on the DL as a smuggler or something

How could Finn identify Han Solo as a war hero of the Galactic Civil War if  he was raised from (near) infancy by the First Order? Related sub-question: Shouldn't Han also be the stuff of myth and legend now as well? (e.g. If Rey thought Luke was just a myth, shouldn't she think the same of Han?)

A: First Order rose from the ashes of the empire. Everything that happened, was passed on to the new "employees". Anything about Han, Leia, Rebels, Luke; all enemies of the new First Order/formerly the Empire would have been ingrained the troopers heads.
Remember in Attack of the Clones-while describing what clones are capable of, the director told Obi-Wan that his clones were trained from birth, to obey any order without question. Even though the new stormtroopers aren't clones, they would need to be taught everything from the First Order's point of view.

A: Finn has apparently had access to entertainment programmes (of a historical nature) as well as the more mundane First-Order weapons and tactical training.

As madness ebbed and surged around him, he wandered through the
village, feeling himself more a participant in a historical drama than
in an actual battle. The horrific and all too common red stains on the
ground contradicted his denial. This wasn't like his training at all,
he told himself numbly. Unlike in simulations, reality bled.
Star Wars: The Force Awakens - Official Novelisation

What's most interesting is that in his personal study of "ancient history" he clearly views the heroes as being the Rebellion, not the Empire. An early (and evidently overlooked) seed of his own future rebellious nature.

"Huh?" If he had been bemused before, Finn was now thoroughly bewildered. Without thinking, he addressed the shaggy mass lumbering along in front of him.   "Wasn't he a war hero? In the fight against the Old Empire?"
Star Wars: The Force Awakens - Official Novelisation

There's also some indication that Han's activities may have been covered as part of Finn's overall combat training, especially since Han was involved in several iconic battles against the Empire.

For the better part of a week, they studied and were repeatedly tested
on different historical battles, many from the Clone Wars, some even
earlier.
Star Wars: Before the Awakening


text:
Q: get posts equal to two meta_values I'm trying to retrieve all posts where the meta_key status is equal to either correct or wrong. at the moment i've created below php variable however it shows all posts also posts where the meta_key is not equal to correct or wrong. What am i doing wrong?
$args = array(
    'numberposts' => -1,
    'post_status' => 'publish',
    'cat' => '4,5,6',
     'meta_query' => array(
        array(
            'meta_key' => 'status',
            'meta_value' => 'wrong'
        ),
        array(
            'meta_key' => 'status',
            'meta_value' => 'correct'
        )
    )

);

$the_query = new WP_Query( $args );

A: Try this:
$args = array(
'numberposts' => -1,
'post_status' => 'publish',
'cat' => '4,5,6',
 'meta_query' => array(
    array(
        'meta_key' => 'status',
        'meta_value' => array('wrong','correct')
        'compare' => 'IN'
    )
)

);


text:
Q: Android webview - how to pass a large binray file to Javascript I have a mobile app that wraps around the web-app, using webview.
The web-app has a button to open a large .zip file (e.g. 100 MB).
The user clicks a button, and selects a .zip file.
This triggers an onChange function with a variable of type File (Blob), which includes attributes like:

*

*file name

*file size

*file type (application/zip)

The javascript code then parses the .zip file, extracts specific data within it and uses it within the web-app.
This works well within the web-app, when the app is called via the Chrome browser.
For example when operated in chrome browser on an Android phone, I can pull the .zip file and open it in the web-app.
I want to do the same but using the mobile app.
I am able to pick up the .zip file using a File Chooser, but I have problems to fetch the file from the Javascript code.
When calling fetch(fileUri) from the Javascript side I'm getting errors.
I'm using the following uri
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
The fetch succeeds but returns a blob with size of 165 (i.e. not the actual size of the file) which hosts the error message:
{
      "error": "Not Found",
      "message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
}

The program flow is like so:

*

*I select a .zip file via FileChooser.

*In onActivityResult, the uri value is /document/msf:12858 (seen via uri = intent.getData();)

*The uri needs to be mapped into a real path file url, such that the fileUrl will be passed to Javascript (via webview).

*Javascript will then fetch the file using the fileUrl.

I searched how to get the real path file url when selecting a file with FileChooser, and found
this, and this links.
I wasn't able to get the real file path, so I decided to read the file and write it to another location, so I can get a file path. (this is not efficient and done just to check the functionality).
I create the new file using the following code:
InputStream stream = context.getContentResolver().openInputStream(uri);
File file2 = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "file2.zip");
writeBytesToFile(stream, file2);

I don't see any errors when creating the file, and when creating the file, the number of bytes that are read and written to the new file are as expected.
For file2, I get a value of:
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
Then, within the Javascript code I fetch this file path.
But I'm getting a Blob with the "file-not-found" content as above.
So:

*

*How can I verify that the file is indeed created and that the path can be fetched from Javascript?

*How can I get the real file path of the original selected file, so I don't have to read and write the original file to new location just to get the file path?

Thanks

EDIT1:
I have "Intent intent" and not "Intent data" in the signature of onActivityResult.
I replaced String filePath = intent.getData() with
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        try {
            intent_to_resolve = new JSONObject();
            if (resultCode == RESULT_OK) {

                // try1
                String filePath1 = intent.getData().toString();
                Log.d("Verbose", "filePath1: " + filePath1);

                // try2
                String filePath2 = intent.toString();
                Log.d("Verbose", "filePath2: " + filePath2);
    ...

I'm getting the following value for filePath:
filePath1: content://com.android.providers.downloads.documents/document/msf%3A12858
filePath2: Intent { dat=content://com.android.providers.downloads.documents/document/msf:12858 flg=0x43 }


text:
Q: Reflect a point vector in a conical surface and determine average resultant vector. Consider a point $P~(P_x,P_y,0)$ which lies somewhere in the Cartesian region $x > 0. $
Consider a simple 3D cone surface with half angle $\gamma$, originating at point $\mathcal{O}$ $(0,0,0)$ whose axis is the x-axis $(x,0,0)$.
The cone may be considered as consisting of a bundle of straight line segments originating at point $\mathcal{O}$ and each making an angle $\gamma$ with the x-axis.
I wish to "reflect" the point P perpendicularly across each of these lines to produce a set of points.  These points can be connected back to origin point $\mathcal{O}$ to produce a second set of lines which describe a cone-like surface.
I require a formula to calculate the "average" vector V obtained by averaging the x,y,z components of the second set of lines.
I have used basic (high school) trigonometric formulae and simple calculus to derive an expression for the average vector as follows:-
$V_x =   P_x (1 - 2 sin^2(\gamma$))
$V_y = - P_y (1 - cos^2(\gamma)sin(\gamma$))
$V_z =   0$.
I have tested the above expression with a simple computer model.
The formula for $V_x$ and $V_z$ seem to be accurate to 1 in 30 trillion, which is nice.
But the formula for $V_y$ seems to be in error as accurate to only 1 in 4000.
When I try the alternative formula:
$V_y =  - P_y  (1 - cos^2(\gamma)sin^2(\gamma))$
This agrees with the computer model to within 1 in 40 trillion, which is nice.
But I cannot presently see how to derive the adjusted formula for $V_y$.
I wish to know if this sort of problem is addressed elsewhere and if there is a derivation available.

A: Tl;dr: my answer is
$$\begin{split}
V_x &= P_x(1 - 2\sin^2\gamma),\\
V_y &= -P_y\cos^2\gamma,\\
V_z &= 0.
\end{split}$$

Let's take just one line and reflect your point across it. Line is described by its vector $\textbf{a}$ so reflected point $Q$ is given by this formula:
$$\textbf{q}=2\frac{\textbf{p}\cdot\textbf{a}}{|\textbf{a}|^2}\textbf{a} - \textbf{p},$$
where $\textbf{p}$ and $\textbf{q}$ are just position vectors of points $P$ and $Q$ respectively.
Next, let's parametrize $\textbf{a}$. We can do it as follows: $\textbf{a}=(\cos\gamma, \sin\alpha\,\sin\gamma, \cos\alpha\,\sin\gamma)$. It can easily be seen that when $\alpha$ goes from $0$ to $2\pi$, the end of vector $\textbf{a}$ draws exactly a circle on your cone surface. Moreover, $|\textbf{a}|=1$.
Considering that $\textbf{p}\cdot\textbf{a} = P_x\cos\gamma + P_y\sin\alpha\,\sin\gamma$, we have
$$\textbf{q}=\begin{bmatrix}
2(P_x\cos\gamma + P_y\sin\alpha\,\sin\gamma)\cos\gamma -P_x\\
2(P_x\cos\gamma + P_y\sin\alpha\,\sin\gamma)\sin\alpha\,\sin\gamma -P_y\\
2(P_x\cos\gamma + P_y\sin\alpha\,\sin\gamma)\cos\alpha\,\sin\gamma
\end{bmatrix}.$$
Let's prepare it for the final step:
$$\begin{align}
\textbf{q}_x &= \sin\alpha\cdot 2P_y\sin\gamma\,\cos\gamma + P_x(2\cos^2\gamma - 1),\\
\textbf{q}_y &= \frac{1-\cos 2\alpha}{2}\cdot 2P_y\sin^2\gamma + \sin\alpha\cdot2 P_x\cos\gamma\,\sin\gamma - P_y,\\
\textbf{q}_z &= \frac{1}{2}\sin2\alpha\cdot 2P_y\sin^2\gamma + \cos\alpha\cdot 2P_x\sin\gamma\,\cos\gamma.
\end{align}$$
Last thing to note is that averaging any of $\sin\alpha,\cos\alpha,\sin2\alpha,\cos2\alpha$ over $[0, 2\pi]$ gives you $0$ because it's the multiple of a period for each of those functions. So
$$\begin{split}
V_x &= P_x(2\cos^2\gamma - 1) = P_x(1 - 2\sin^2\gamma),\\
V_y &= P_y\sin^2\gamma - P_y = -P_y\cos^2\gamma,\\
V_z &= 0.
\end{split}$$


text:
Q: Exported variable in bashrc file not visible when running as another user On Ubuntu 20.04LTS:

*

*Create a dummy user.

*Create a short script that appends an exported variable to the new user's .bashrc, then sources that .bashrc and tries to use the variable.

*Run the script as the new user.

Why is the variable not set?
> adduser --gecos ',,,' --disabled-password foouser
[...output...]
> cat > /tmp/bootstrap.sh <<EOF
  echo 'export FOO=foo' >> /home/foouser/.bashrc
  . /home/foouser/.bashrc
  echo 'sourced foouser bashrc'
  set | grep FOO
EOF
> chmod a+x /tmp/bootstrap.sh
> su - foouser -c /tmp/bootstrap.sh
[...output does not include FOO...]
> deluser --remove-home foouser

A: Your problem is that .bashrc is configure explicitly to only run for interactive shells. Look at the top of /home/foouser/.bashrc:
# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

If you add a set -x to your /tmp/bootstrap.sh script, you will see when you execute it the following:
+ echo 'export FOO=foo'
+ . /home/foouser/.bashrc
++ case $- in
++ return
+ echo 'sourced foouser bashrc'
sourced foouser bashrc
+ set
+ grep FOO

There you can see it hits the return command in the case statement.
You can force an interactive shell with the -i option:
root@ed3085a447ad:/# su - foouser -c 'bash -i -c /tmp/bootstrap.sh'
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
sourced foouser bashrc
FOO=foo


text:
Q: MongoDB query on an indexed field takes forever to return a simple count I have a collection with over 1 billion documents. Some of them have the field extra.id but a majority don't. I have an index set as described below. When I run a simple query to get the count of documents with extra.id set, the query takes ages to complete. Actually, I have never waited long enough for it to complete. I'd expect <1s response and what I get instead is >15min (before I kill it). I am running MongoDB 3.4.7 on Ubuntu while connecting from a Windows client.
What is going on? I thought partial filter expression was going to help here because the query should simply return the count of indexed documents.
Query
db.handles.find({"extra.id":{$exists:true}}).count()

Index
{
    "v" : 1,
    "name" : "extra.id_1",
    "ns" : "pull.handles",
    "background" : true,
    "partialFilterExpression" : {
        "extra.id" : {
            "$exists" : true
        }
    }
}


text:
Q: How to call both C++ and C from Cython? I followed the directions (http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html) to wrap a C++ library with cython.  Part of this is telling Cython to generate C++.  That worked nicely; so far so good.
But now, in my cython code, I need to call some C libraries.  Since Cython is generating C++, when I refer to the C library, it mangles the name, so it fails when it tries to link.
I would prefer not to recompile all my C code as C++.  Is there any way to get Cython to deal with both C and C++ at the same time?


text:
Q: Laravel 5.2 datepicker For days, I'm trying to get Datepicker functionality in my web application (based on Laravel 5.2). Can't get it to work.
In the head section of my layout file I add:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.1/css/bootstrap-datepicker.css">

and at the bottom I have

In the view file I have

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

I'm seeing the date field but when I click on it, it simply tries to open the dateselector, but it appears empty (so no dates inside)
Suggestions welcome!
Note: screenshot here

A: As said above, it looks like you need to add bootstrap CSS to your app.
If you intend to use datepicker (or any other bootstrap elements) in more than 1 view then I would add it to your layout view, it will make life a lot easier than adding it to each file.
If you have added the files locally to your project to public/assets/css then call them with the below.
<link rel="stylesheet" type="text/css" href="{{asset('assets/css/bootstrap.min.css')}}"/>
<link rel="stylesheet" type="text/css" href="{{asset('assets/css/bootstrap-responsive.min.css')}}"/>

OR
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

A: You might need to add bootstrap.css as well. The styling of the elements in the calendar takes from that stylesheet.

A: Include bootstrap styles and javascript files. they are required to use bootstrap-datepicker.


text:
Q: Yii2 photo gallery Photo->Likes relation So basically, I have a photo application and the relation between photos and likes is hasMany(). How can I make the relation to be ordered by count(number_of_likes) for each photo?
TABLE `Likes` (
  `id_lk` int(11) NOT NULL AUTO_INCREMENT,
  `idusr_lk` int(11) NOT NULL,
  `idpht_lk` int(11) NOT NULL,
  PRIMARY KEY (`id_lk`),
  KEY `idusr_lk` (`idusr_lk`),
  KEY `idpht_lk` (`idpht_lk`),
  CONSTRAINT `Likes_ibfk_1` FOREIGN KEY (`idusr_lk`) REFERENCES `users_usr` (`id_usr`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Likes_ibfk_2` FOREIGN KEY (`idpht_lk`) REFERENCES `photos_pht` (`id_pht`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

the php code of the relations:
Photo model
public function getLikes()
{
    return $this->hasMany(Likes::className(), ['idpht_lk' => 'id_pht']);
}

Likes model
public function getPhoto()
{
    return $this->hasOne(Photo::className(), ['id_pht' => 'idpht_lk']);
}

I know that you can add an orderBy clause after the relations, but I just simply don't know if i am allowed to write an SQL query there and if I am, how am I supposed to write it?

A: Well what you require is that you don't have to build the query manually every time and still able to call the result set which has

*

*All photos along with the number of likes they have using the existing relation getLikes().

*They should be ordered according to the number of likes they have.
Well what i suggest wont just use Photo::find()->all() to do the job but yes if you are ok with doing Photo::find()->byLikes()->all() then you can use the following approach

*

*Create ActiveQuery Class PhotoQuery for the Photo model.

*Override the find() method inside your Photo Model to use the newly generate/created PhotoQuery class.

You can use Gii to generate the default PhotoQuery class or you can create manually like the below one.
Adjust the namespaces accordingly.
<?php

namespace app\models;

/**
 * This is the ActiveQuery class for [[Photo]].
 *
 * @see Photo
 */
class PhotoQuery extends \yii\db\ActiveQuery
{
    /**
     * {@inheritdoc}
     * @return Photo[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * {@inheritdoc}
     * @return Photo|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}

Now what you need to do is to add a new method in the PhotoQuery with the name byLikes()
/**
 * @return mixed
 */
public function byLikes()
{
    return $this->alias('p')
        ->select(['p.*', new \yii\db\Expression('count(l.idpht_lk) as likeCount')])
        ->joinWith(['likes l'])
        ->groupBy('p.id_pht')
        ->orderBy('likeCount desc');
}

and then add the following method in your Photo model to use PhotoQuery class instance.
/**
 * {@inheritdoc}
 * @return PhotoQuery the active query used by this AR class.
 */
public static function find()
{
    return new PhotoQuery(get_called_class());
}

Now you can call the query like Photo::find()->byLikes()->all() and it will return the results ordered by total number of likes along with the likes count, where at the same time you can still call Photo::find()->all() to get only the photo specific result set if you want to somewhere in the future.
Hope it helps.

A: In your table Likes you have to add a field where you can store the number of likes for each photo, for example: number_of_likes.
Then you can run a query like this to get the number of like for each photo on descending order:
SELECT idusr_lk, idpht_lk, number_of_likes
FROM photos_pht
INNER JOIN Likes
ON photos_pht.id_pht = Likes.idpht_lk
ORDER BY  Likes.number_of_likes DESC


text:
Q: Primality test based on initial conditions alone. Let $m=252601$. Suppose we discover that
$$3^{126300} ≡ 67772 \pmod{252601}$$
$$3^{252600} ≡ 1\pmod{252601}$$
Is then $252601$ prime? composite? Or can we not decide for sure from the information given?

A: Hint: $a^{\frac{p-1}{2}} \equiv \pm 1\pmod p$ for any prime $p$ and a positive integer $a$ smaller than $p$.

A: Hint: $\,252601\mid 67772^2\!-1 = (67772-1)(67772+1)\ \Rightarrow\ \gcd(252601, 67772\pm1) > 1.$
In fact $\ \gcd(252601, 67772\!+\!1) = 41,\ \ \gcd(252601, 67772\!-\!1) = 6161,\ \ 41\cdot 6161 = 252601.$
Finding nontrivial square roots of $\,1\,$ is the key idea behind many integer factorization algorithms.


text:
Q: How do I use Alexa's Dialogue Directives in Java? There is barely any information online that I can find in relation to this topic.
I dont know how to access intents, or use them to return a response given certain parameters are met with that intent. Im trying to create a dialogue that can be as simple as,
Me: "Add a unit"
Alexa: "What shoult the unit be called?"
Me: "Engineering"
Alexa: "Ok, added the unit Engineering."
Currently all I know how to do is perform an action once the skill is called upon, regardless of what is said. So for example, I could literally say,
Me: "Alexa, open StudyPal"
Alexa: "Something that is returned whenever the skill is activated"
or...
Me: "Alexa, ask StudyPal about my units"
Alexa: "Something that is returned whenever the skill is activated"
Any help would be appreciated. For reference, this is some of my code...
public class StudyPalHandler implements RequestStreamHandler {
private final Skill skill;
private final JacksonSerializer serializer;

public StudyPalHandler() {
    skill = new StandardSkillBuilder()
            .addRequestHandler(new StudyPalExtraHandler())
            .build();
    serializer = new JacksonSerializer();
}

@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
    String request = IOUtils.toString(inputStream);
    RequestEnvelope requestEnvelope = serializer.deserialize(request, RequestEnvelope.class);
    ResponseEnvelope responseEnvelope = skill.invoke(requestEnvelope);
    byte[] response = serializer.serialize(responseEnvelope).getBytes(StandardCharsets.UTF_8);
    outputStream.write(response);
}
}

public class StudyPalExtraHandler implements RequestHandler {
@Override
public boolean canHandle(HandlerInput handlerInput) {
    return true;
}

@Override
public Optional<Response> handle(HandlerInput handlerInput) {
    return handlerInput.getResponseBuilder().withSpeech("Something that is returned whenever the skill is activated").build();
}
}

A: You should use canHandle() method of the associated handler class to check whether that particular handler can handle that request.
Ex: If you want handle a StudyPalIntent, then
public class StudyPalIntentHandler implements RequestHandler {

@Override
public boolean canHandle(HandlerInput input) {
    return input.matches(intentName("StudyPalIntent"));
}

@Override
public Optional<Response> handle(HandlerInput input) {
    return input.getResponseBuilder()
            .withSpeech("your response speech here")
            .withReprompt("your re prompt here")
            .build();
}

From the sdk source code you can use dialog diretives like this
return input.getResponseBuilder()
   .withSpeech("your response speech here")
   .withReprompt("your re prompt here")
   .addDelegateDirective(updatedIntent)
   .build();

Other dialog directives helper methods are
addElicitSlotDirective(String slotName, Intent updatedIntent)
addConfirmSlotDirective(String slotName, Intent updatedIntent)
addConfirmIntentDirective(Intent updatedIntent)

Check this ResponseBuilder.java class


text:
Q: Android NSD. Have errors when trying to resolve I'm making android quiz with local network multiplayer where host should send message to all clients. I'm using this sample of NsdChat.
But when I try to reslove service I get this errors.
E/NsdServiceInfo: While parsing txt records (pos = 1): Zero sized txt record
E/NsdHelper: Resolve Succeeded. name: NsdChatHost, type: ._http._tcp, host: /"myIP", port: "myPort", txtRecord:
E/NsdService: Unique id with no client mapping: 71
E/NsdService: Unhandled { when=-4ms what=393242 obj=com.android.server.NsdService$NativeEvent@157683e target=com.android.internal.util.StateMachine$SmHandler }

It's my resolve listener.
public void initializeResolveListener() {
        mResolveListener = new NsdManager.ResolveListener() {
            @Override
            public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
                Log.e(TAG, "Resolve failed" + errorCode);
            }
            @Override
            public void onServiceResolved(NsdServiceInfo serviceInfo) {
                Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
                if (serviceInfo.getServiceName().equals(mServiceName)) {
                    Log.d(TAG, "Same IP.");
                    return;
                }
                mService = serviceInfo;
            }
        };
    }


text:
Q: Is it true that the text-to-speech functionality would make my mac run slower? I have been having some issues with my macbook running very slow.  I read an article which stated that disabling the text-to-speech functionality could make the mac faster. Is that true?
For a year I have been using that functionality to "read" blog posts. Now, on chrome I need to go edit -> speech -> start speaking (there is no shortcut). If I re active the text-to-speech would my mac still run slow

A: I have never heard of the "text-to-speech" feature causing a slow down. But other things certainly can. Here is a link to what one Apple user has suggested. There are a number of things to try!
https://discussions.apple.com/docs/DOC-6921


text:
Q: Zoomable and Panable Collection of Objects I'm pretty new to iphone development, so this is more of a high-level question. The simplest description of what I am looking to do is create a zoomable/panable field on which I can place a bunch of circle objects. The number of these circles is likely to be in the hundreds, and ideally when the user zooms in close enough, more information can be displayed. From stuff I've read, it seems like UIScrollView provides the simplest way of making a zoomable/panable view but I'm not sure it's the best way to handle a view that includes a hundred graphic objects. I'm trying to figure out if I should progress further down that path or look into things like CALayers, Core Graphics, etc. Any guidance or advice would be greatly appreciated. Thanks in advance,
Roman

A: I suggest you to use UIScrollView, because it will save a lot of time for handling proper zooming/scrolling. So the workflow is next:
1. Zoom you scroll view
2. In delegate's callback scrollViewDidEndZooming:withView:atScale:  you can obtain the scale and determine the level of detail that you need.
3. redraw the visible region (using Core Graphics) with appropriate level of detail (number of circles etc.)
So you should use the mix of Core Graphics and UIKit.


text:
Q: Failing to read String value from an excel column SSIS script task reading only numeric values of excel but fails to read the alphanumeric values present in the same column
I've tried using IMEX=0, IMEX=1 and IMEX=2. But the Alphanumeric values are being generated as NULL in my SQL server table.
//Excel Connection String
string ConStr;
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR +
";IMEX=0\"";

If the 1st 8 column 'A' values are integer (0,1,2,3,4,5,6,7) and then comes alphanumeric (A,B,ABQX345) values in below rows, then it should read all the values as it is and insert into SQL Server table as
0,1,2,3,4,5,6,7,A,B,ABQX345

A: This issue is related to the OLEDB provider used to read excel files: Since excel is not a database where each column has a specific data type, OLEDB provider tries to identify the dominant data types found in each column and replace all other data types that cannot be parsed with NULLs.
There are many articles found online discussing this issue and giving several workarounds (links listed below).
But after using SSIS for years, I can say that best practice is to convert excel files to csv files and read them using Flat File components.
Or, if you don't have the choice to convert excel to flat files then you can force excel connection manager to ignore headers from the first row bu adding HDR=NO to the connection string and adding IMEX=1 to tell the OLEDB provider to specify data types from the first row (which is the header - all string most of the time), in this case all columns are imported as string and no values are replaced with NULLs but you will lose the headers and a additional row (header row is imported).
If you cannot ignore the header row, just add a dummy row that contains dummy string values (example: aaa) after the header row and add IMEX=1 to the connection string.
SchemaMapper Excel Import class
In addition, it is good to check the following class which is a part of SchemaMapper project, I implemented the logic mentioned above in order to fix this problem:

*

*SchemaMapper - MsExcelImport.cs
Helpful links

*

*SSIS Excel Data Import - Mixed data type in Rows

*Mixed data types in Excel column

*Importing data from Excel having Mixed Data Types in a column (SSIS)

*Why SSIS always gets Excel data types wrong, and how to fix it!

*EXCEL IN SSIS: FIXING THE WRONG DATA TYPES

*IMEX= 1 extended properties in ssis


text:
Q: Is every rotation invariant set in the real plane a union of circles? Suppose we have a set $S$ in $\mathbb{R}^2$ which is fixed by every rotation about the origin. Must it be the case that $S$ is a union, possibly an empty union, of circles centered at the origin? I am counting the origin itself as a circle of radius $0$.

A: Yes, because then$$S=\bigcup_{s\in S}\{(x,y)\in\mathbb R^2\mid x^2+y^2=\lVert s\rVert^2\}.\tag1$$In fact, if $s\in S$, then it is clear that $s\in\{(x,y)\in\mathbb R^2\mid x^2+y^2=\lVert s\rVert^2\}$. Therefore,$$S\subset\bigcup_{s\in S}\{(x,y)\in\mathbb R^2\mid x^2+y^2=\lVert s\rVert^2\}.\tag2$$On the other hand, if $p\in\bigcup_{s\in S}\{(x,y)\in\mathbb R^2\mid x^2+y^2=\lVert s\rVert^2\}$, then$$p\in\{(x,y)\in\mathbb R^2\mid x^2+y^2=\lVert s\rVert^2\},$$for some $s\in S$. But then $p$ can be obtained from $s$ under a rotation around the origin. And therefore $p\in S$. It follows from this and from $(2)$ that $(1)$ holds.


text:
Q: How to convert result string to column database I have a question:
This query
SELECT 'ID_' + ISNULL (cast (fields.ID AS VARCHAR), '') AS FIELD_ID
FROM MYTABLE fields
WHERE fields.id = 1

ID_1 returns me as a string, I need to use that ID_1 in another query that is a column in the table that I need to find its value
the complete query would be like this:
SELECT TOP (1) (SELECT 'ID_' + ISNULL (cast (fields.ID AS VARCHAR), '') AS FIELD_ID
                FROM MYTABLE fields
                WHERE fields.id = 1) as value
FROM MYTABLE2

A: IS this where you are going with it?
select * from targettable
join (

    SELECT 'ID_' + ISNULL (cast (fields.ID AS VARCHAR), '') AS FIELD_ID
    FROM MYTABLE fields
    WHERE fields.id = 1

) a
on targettable.FIELD_ID = a.FIELD_ID

A: Use Dynamic SQL
DECLARE @SQL nvarchar(1000)
DECLARE @Column nvarchar(1000)

SET  @Column = SELECT TOP 1 'ID_' + ISNULL (CAST(fields.ID AS VARCHAR), '')
               FROM MYTABLE
               WHERE fields.id = 1
SET @SQL = 'SELECT TOP 1' + @Column + ' FROM MYTABLE2'
EXEC (@SQL)


text:
Q: Notifying when screen is off I'm trying to generate a notification which vibrates the phone and plays a sound when the screen is off (cpu turned off). According to the Log messages, the notification is being sent, but the phone doesn't vibrate or play the sound until I turn the screen on again. I tried holding a 2 second temporary wakelock (PowerManager.PARTIAL_WAKE_LOCK), which I thought would be ample time for the notification to be played, but alas, it still doesn't.
Any pointers to get the notification to run reliably? I'm testing this on an G1 running Android 1.6.
Code I'm using:
notif.vibrate = new long[] {100, 1000};
notif.defaults |= Notification.DEFAULT_SOUND;

notif.ledARGB = Color.RED;
notif.ledOnMS = 1;
notif.ledOffMS = 0;
notif.flags = Notification.FLAG_SHOW_LIGHTS;

notif.flags |= NOTIF_FLAGS; //static var

if (!screenOn) { //var which updates when screen turns off/on
    mWakeLock.acquire(2000);
}

manager.notify(NOTIF_ID, notif);

A: You can make your own receiver that extends to BroadcastReceiver which can perform your notification when it receives INTENT.ACTION_SCREEN_OFF
@Override
public void onReceive(Context context, Intent intent) {
  Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  long milliseconds = 1000;
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        // vibrate the phone
            v.vibrate(milliseconds);
        // any other code here
     }
}


text:
Q: Is this sending the right value back? Not working in test Java SO i made a CharSequence[] array with all the two consecutive uppercase letters. Why is this code not returning the correct values?
public static boolean containConsecCaps(String passw)
{
    CharSequence[] consec = {"AA","AB","AC","AD","AE","AF", ... "ZZ"};
    boolean contain = false;
    String pass = passw;
    for (int i = 0; i <= 675; i++)
    {
        contain = pass.contains(consec[i]);
        if (contain == true)
            break;
    }
    return contain;
}

and in the main string, this syntax:
while (consec != false)
          {
              //Consec.setPassword(password.getPassword());
              consec = Consec.containConsecCaps(password.getPassword());
              if (consec == false)
                  break;
              else
                  password.setPassword(reader.readLine("Error. Please enter a password with no consecutive letters:        "));
          }

now everything else in the three classes work. This is the only problem and it seems to get stuck in the else. Why is it not testing all of the array char's then returning true or not?
It gets stuck in a loop if i enter: AApassword.1 , which fits all the other criteria, except the two consecutive capitals. So then i enter: aApassword.1 , which should fit ALL of the criteria, but it still prints out the else statement, instead of breaking the while loop.
Can anyone help me?


text:
Q: Getting a virtual field in Ecto calculated during a SQL Join Query This may be more of SQL question rather than an Elixir/Etco Question.
I have many to many relationships of User-Transactions-Merchant, where the user has many Merchants through Transactions and the Merchant has many customers through Transactions. That is pretty typical. I can get all of a merchant's customers through Ecto by doing something like this:
def find_merchant_customers(%{"merchant_id" => id}) do
  merchant = Repo.get(Merchant, id)
  Repo.all assoc(merchant, :customers)
end

If I want to find a balance for a user with a specific merchant, I have SQL query like this which sums up the transactions and produced a balance for that merchant.
def customer_balance(user_id: user_id, merchant_id: merchant_id) do
  q = from t in Transaction,
    select: fragment("SUM(CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END)", t.type, t.amount, t.amount),
    where: t.user_id == ^user_id and t.merchant_id == ^merchant_id
  balance = Repo.one(q) || 0
  do_balance(balance, "asset")
   |> Money.new(:USD)
end

The question
How do I combine the two operations into one query such that the Join retrieves a list of users and populates the virtual attribute of Balance in the user. I know I could just run the first query and get the list of users then transform that data by retrieving each of the balances for each user, although that seems very inefficient. An alternative might be to understand how to assign the select fragement( to an attribute within the query as a sub-query. Any guidance would be helpful.
My User Model
defmodule MyApp.User do
  @moduledoc """
  User struct for user related data
  """
  import MyApp.Validation
  use MyApp.Model
  use Coherence.Schema

  schema "my_app_users" do
    field :email, :string
    field :first_name, :string
    field :last_name, :string
    field :role, :integer
    field :birthdate, Ecto.Date
    field :address1, :string
    field :address2, :string
    field :city, :string
    field :state, :string
    field :zip, :string
    field :status, :boolean, default: true
    field :verified_email, :boolean, default: false
    field :verified_phone, :boolean, default: false
    field :mobile, :string
    field :card, :string
    field :sms_code, :string
    field :balance, Money.Ecto, virtual: true
    field :points, :integer, virtual: true

    coherence_schema

    has_many :transactions, MyApp.Transaction
    has_many :merchants, through: [:transactions, :merchant]

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:email, :first_name, :last_name, :password_hash, :role, :birthdate, :address1, :address2, :city, :state, :zip, :status, :mobile, :card, :sms_code, :status, :merchant_id, :verified_email, :verified_phone])
    |> validate_required_inclusion([:email, :mobile])
    |> validate_format(:email, ~r/(\w+)@([\w.]+)/)
  end

  defp put_password_hash(changeset) do
    case changeset do
      %Ecto.Changeset{valid?: true, changes: %{password: password}} ->
        put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(password))
      _ ->
        changeset
    end
  end

My Merchant Model
defmodule MyApp.Merchant do
  @moduledoc """
  Merchant Struct

  Merchant has an owner of a User - Which must exist
  """
  use MyApp.Model
  use Arc.Ecto.Schema

  schema "my_app_merchants" do
    field :name, :string
    field :email, :string
    field :address1, :string
    field :address2, :string
    field :city, :string
    field :zip, :string
    field :state, :string
    field :status, :boolean, default: true
    field :description, :string
    field :image, MyRewards.Avatar.Type
    field :phone, :string
    field :website, :string

    has_many :transactions, MyApp.Transaction
    has_many :customers, through: [:transactions, :user]

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:name, :email, :address1, :address2, :city, :zip, :state, :status, :description, :phone, :website, :status, :category_id, :user_id])
    |> cast_attachments(params, [:image])
    |> validate_required([:name])
    |> validate_format(:email, ~r/(\w+)@([\w.]+)/)
  end
end

Query Functions
  def find_merchant_customers(%{"merchant_id" => id}) do
    merchant = Repo.get(Merchant, id)
    Repo.all assoc(merchant, :customers)
  end

  def customer_balance(user_id: user_id, merchant_id: merchant_id) do
    q = from t in Transaction,
        select: fragment("SUM(CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END)", t.type, t.amount, t.amount),
        where: t.user_id == ^user_id and t.merchant_id == ^merchant_id
    balance = Repo.one(q) || 0
    do_balance(balance, "asset")
      |> Money.new(:USD)
  end

A: Move the fragment into a macro to keep the code clear:
  defmacro balance_amount(transaction) do
    quote do
      fragment("CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END",
        unquote(transaction).type, unquote(transaction).amount, unquote(transaction).amount)
    end
  end

Create a subquery with %{user_id, merchant_id, balance}
  def user_merchant_balance do
    from t in Transaction,
    select: %{user_id: t.user_id, merchant_id: t.merchant_id, balance: sum(balance_amount(t))},
    group_by: [t.user_id, t.merchant_id]
  end

Join to the subquery from the main query, use the map update syntax %{|} to populate the virtual field:
  def merchant_customers(merchant_id) do
    from u in User,
    join: b in subquery(user_merchant_balance()), on: u.id == b.user_id,
    where: b.merchant_id == ^merchant_id,
    select: %{u | balance: b.balance}
  end

Edit: In Ecto 2.2, the balance field can be cast to Money.Ecto.Type
  def merchant_customers(merchant_id) do
    from u in User,
    join: b in subquery(user_merchant_balance()), on: u.id == b.user_id,
    where: b.merchant_id == ^merchant_id,
    select: %{u | balance: type(b.balance, Money.Ecto.Type)}
  end


text:
Q: Swift : CollectionView ScollToItem is crashing in iOS version 12 We were struggling to fix the crash from 2 days but no luck, surprisingly other versions are working fine with the CollectionView ScrollToItem method where in iOS 12 crashing at the same line and showcase the reason invalid indexPath
but we do have a valid indexPath because I could see there is a number of images are loaded on collectionView. Hence confused about this case, was this a known problem in iOS 12, or do we have any fix for it
please help to close this issue, and thanks in advance
Giving below crash reason
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: <NSIndexPath: 0x7f841e46feb0> {length = 2, path = 0 - 1}'


text:
Q: glBlendFunc and alpha blending I'm writing a application where a user is allowed to toggle between different shaders, and combinations of them. Thus i want to draw the exact same scene a multiple time.
In the end, all the passes should be combined into one single output. To combine all the passes i thought about using glblendfunc, but i dont get the result I want to have.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//use first shader
draw();
if (secondShaderWished) {
    //use second shader
    draw()
}

In each draw call i draw a texture which does have alpha values, e.g. transparent regions. The Endresult i get is that I see mainly the effect of the last render pass, but on the boundary (where the alpha-values slightly drop off) I do see the first shader effects.
What I do think is that i should use a second glBlendFunc which allows to blend the two passes, but I cant think of a way to not touch any of the alpha values, which would destroy the wished effect.
What should I do? Is there something else then alphablending?
Edit: My goal is to combine one or more passes. I want to mix the colors (most probably adding them together), wehereas the color in each path is calculated via the following blending function across different layers: glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
EDIT:
Hi again! I'm working on this problem but I get stuck. I dont understand how i can properly set the sampler2d in any shader... What am I doing wrong?
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _FBO)
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, _Tex);
glViewport(0, 0, viewportSize.x(), viewportSize.y());
draw();
GLuint texLocation = glGetUniformLocation(_shader->getProgramID(),"pass0");
glUniform1i(texLocation, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

A: Due to your comment, you could just render each pass indivually into a texture (best done using FBOs), using your needed blend function. Then you can blend the different passes together in a single pass by just drawing a screen-sized quad and averaging all the passes's textures together in the fragment shader.
EDIT: According to your comment. You render these passes individually directly into a texture (that is bound as an FBO attachment) each. Then you use a fragment shader like this one with a screen-sized quad, assuming you have three passes:
uniform sampler2D pass0;
uniform sampler2D pass1;
uniform sampler2D pass3;
uniform vec2 screenSize;

void main()
{
    vec2 texCoord = gl_FragCoord.xy / screenSize;
    gl_FragColor = (1.0/3.0) * (texture2d(pass0, texCoord) +
                                texture2d(pass1, texCoord) +
                                texture2d(pass2, texCoord));
}

EDIT: Alternatively you can use a simple 1-texture fragment shader (that just looks up a color from a single texture and puts it out) and draw multiple textured quads using Tobias's blending configuration. This may also scale better if the number of passes is not known a-priori.

A: I think you don't want to use the alpha-values of the textures as a blend factor but rather a constant factor that gives you a 1:1 blending.
You have to distribute the blending factors on all texture layers. So a white pixel on all textures would add up to exactly 1.
float factor = 1.0f / numTextures;
glBlendColor(factor, factor, factor, factor);
glBlendFunc(GL_CONSTANT_COLOR, GL_ONE);

For 3 layers that would become:
             source        dest
1st pass: (tex1 * 1/3) + (0 * 1)
2nd pass: (tex2 * 1/3) + (tex1 * 1/3 * 1)
3rd pass: (tex3 * 1/3) + ((tex2 * 1/3 + tex1 * 1/3) * 1)

Also remember that alpha-blending is an order-dependent operation.


text:
Q: My bitmap gets rotated in Android after scaling it This is my code. This question is somewhat related from this question: Trying to scale down a Bitmap in Android not working
I commented out the options.inSampleSize and I still get the rotation (counter-clockwise 90 degrees seemingly). This seems like a fairly simple scaling down of an image, from Google documentation, and I'm not sure how I'm getting a rotated image.
Bitmap myBitmap = null;
        @Override
        protected byte[] doInBackground(Object... params) {

            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            //myImageByteArray is 4016 wide
            myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options);
            if (options.outHeight > options.outWidth) {
                //options.inSampleSize = calculateInSampleSize(options, 640, 960);
            } else {
                //options.inSampleSize = calculateInSampleSize(options, 960, 640);
            }

            options.inJustDecodeBounds = false;

            //myImageByteArray is 4016 wide
            myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options);

            //This log statement outputs around 1000 now.
            Log.d("bitmap", myBitmap.getWidth()+"");
            ByteArrayOutputStream bAOS = new ByteArrayOutputStream();
            myBitmap.compress(CompressFormat.JPEG, 50, bAOS);

}

The byte[] is originally from Commonsware CWAC Camera library, and I've tried taking a look at: Android Reduce Size Of Camera Picture
UPDATE:
I have started pulling away more code to try to make it more apparent where this rotation could be coming from. I have it narrowed down to this. (This code still causes rotation)
Bitmap myBitmap = null;
        @Override
        protected byte[] doInBackground(Object... params) {
            final BitmapFactory.Options options = new BitmapFactory.Options();

            myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options);
            ByteArrayOutputStream bAOS = new ByteArrayOutputStream();
            myBitmap.compress(CompressFormat.JPEG, 50, bAOS);

}

A: It's probable that the issue here is that the image is not being rotated per-se, but that the image is being displayed with a rotation and your transform is clearing (or at least not carrying forward) the metadata the OS would use to show it oriented correctly. There's not a lot you can do about that, because the OS doesn't put that data in the image itself
If that's not the case, then what you have is byte-order issue. One format is giving you data left-to-right and the other is top-to-bottom. You need to reorder the bytes.


text:
Q: one-to-many inline select with django admin I have a standard many-to-one relationship set up. There are a bunch of fields, but for our purposes here, the relevant model is:
class Class(models.Model):
    name = models.CharField(max_length=128)

class Student(models.Model):
    class = models.ForeignKey(Class)
    name = models.CharField(max_length=128)
    address = models.CharField(max_length=128)
    # ...etc

I created an admin, and it works great. it even automatically has the ability for me to set the Class when I am editing a Student. However, when I go to create/edit a Class, all I get is an input box for the name.
Is there a way to add a box/field where Students can be added as members of Class from the Class admin page? I can make a form inline, but that is to create new Students. I already have all my Students created and am just looking for a quick method to add multiple existing Students to different Class'.

A: There is! You want InlineModelAdmin (see InlineModelAdmin documentation here)
Sample code in brief:
class StudentAdminInline(admin.TabularInline):
    model = Student

class ClassAdmin(admin.ModelAdmin):
    inlines = (StudentAdminInline, )
admin.site.register(Class, ClassAdmin)

A: Here is "custom form" solution as Luke Sneeringer suggested. Anyway, I'm suprised by absence of out-of-the-box Django solution to this (rather natural and probably common) problem. Am I missing something?
from django import forms
from django.db import models
from django.contrib import admin

class Foo(models.Model):
    pass

class Bar(models.Model):
    foo = models.ForeignKey(Foo)

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo

    bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all())

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['bars'].initial = self.instance.bar_set.all()

    def save(self, *args, **kwargs):
        # FIXME: 'commit' argument is not handled
        # TODO: Wrap reassignments into transaction
        # NOTE: Previously assigned Foos are silently reset
        instance = super(FooForm, self).save(commit=False)
        self.fields['bars'].initial.update(foo=None)
        self.cleaned_data['bars'].update(foo=instance)
        return instance

class FooAdmin(admin.ModelAdmin):
    form = FooForm

A: Probably, this will help:
I used the described approach, but changed methods save and save_m2m in the following way:
from django import forms
from django.db import models
from django.contrib import admin

class Foo(models.Model):
     pass

class Bar(models.Model):
     foo = models.ForeignKey(Foo)

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo

    bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all())

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['bars'].initial = self.instance.bar_set.all()

    def save_m2m(self):
        pass

    def save(self, *args, **kwargs):
        self.fields['bars'].initial.update(foo=None)
        foo_instance = Foo()
        foo_instance.pk = self.instance.pk
        # Copy all other fields.
        # ... #
        foo_instance.save()
        self.cleaned_data['bars'].update(foo=instance)
        return instance

class FooAdmin(admin.ModelAdmin):
    form = FooForm

A: In 2021, there is no straight solution to this problem.
What I did is using ManyToMany with symmetrical=False. Read more one Django official doc about symmetrical. Only in that case, you can select multiple entities in django-admin
parent_questions = models.ManyToManyField('self', related_name='parent_questions',
                                         blank=True, symmetrical=False)

A: You could also run the student names trough a second model so that they are a ForeignKey. For example after the original code post add:
class AssignedStudents(models.Model):
    assigned_to = models.ForeignKey(Class, on_delete=models.CASCADE)
    student = models.ForeignKey(Student, on_delete=models.CASCADE)

Then add the inline to the admin like Luke Sneeringer said. You end up with a drop down list that you can select the student names from. Although, there is still the option to create new students.

A: Something that works for me in Django 3.0.9
In models.py
from django import forms
from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)
    course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.name

class CourseForm(forms.ModelForm):

    students = forms.ModelMultipleChoiceField(
        queryset=Student.objects.all(), required=False
    )
    name = forms.CharField(max_length=100)

    class Meta:
        model = Student
        fields = ["students", "name"]

    def __init__(self, *args, **kwargs):
        super(CourseForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields["students"].initial = self.instance.student_set.all()

    def save_m2m(self):
        pass

    def save(self, *args, **kwargs):
        self.fields["students"].initial.update(course=None)
        course_instance = Course()
        course_instance.pk = self.instance.pk
        course_instance.name = self.instance.name
        course_instance.save()
        self.cleaned_data["students"].update(course=course_instance)
        return course_instance

In admin.py
from django.contrib import admin
from .models import Student, Course

class StudentAdmin(admin.ModelAdmin):
    pass

class CourseAdmin(admin.ModelAdmin):
    form = CourseForm

admin.site.register(Student, StudentAdmin)
admin.site.register(Course, CourseAdmin)

A: If the intention is to have students exist independently from a class, and then be able to add or remove them from a class, then this sets up a different relationship:

*

*Many students can be a part of one class.

*One student can be a part of many classes

In reality this is describing a Many-To-Many relationship. Simply exchanging
class Student(models.Model):
    class = models.ForeignKey(Class) ...

for
class Student(models.Model):
    class = models.ManyToManyField(Class)...

will give the desired effect in Django admin immediately
Django Many-to-many


text:
Q: Run "mvn package" fail in shell First, I can run mvn package in Ubuntu command line. A part of result as below:
[INFO] --- exec-maven-plugin:1.2.1:exec (build-native) @ affinity ---
g++ -O3 -Wall -shared -fPIC -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/i386/server  -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/jrockit/ -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/i386/jrockit/ -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ppc64le/server -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ppc64le/jrockit/ -ljvm -lrt -I /usr/lib/jvm/java-8-openjdk-amd64/include -I /usr/lib/jvm/java-8-openjdk-amd64/include/linux -I ../../../target/classes/../jni software_chronicle_enterprise_internals_impl_NativeAffinity.cpp net_openhft_ticker_impl_JNIClock.cpp -o ../../../target/classes/libCEInternals.so
[INFO]
[INFO] --- maven-bundle-plugin:4.2.1:manifest (default) @ affinity ---

Then, I write a execute.sh as below:
cd work
mvn package

When I run execute.sh. I got:
[INFO] --- exec-maven-plugin:1.2.1:exec (build-native) @ affinity ---
mkdir -p ../../../target/classes/jni
javah -force -classpath ../../../target/classes -d ../../../target/classes/../jni software.chronicle.enterprise.internals.impl.NativeAffinity net.openhft.ticker.impl.JNIClock
g++ -O3 -Wall -shared -fPIC -L/usr/java/default/jre/lib/amd64/server -L/usr/java/default/jre/lib/i386/server  -L/usr/java/default/jre/lib/amd64/jrockit/ -L/usr/java/default/jre/lib/i386/jrockit/ -L/usr/java/default/jre/lib/ppc64le/server -L/usr/java/default/jre/lib/ppc64le/jrockit/ -ljvm -lrt -I /usr/java/default/include -I /usr/java/default/include/linux -I ../../../target/classes/../jni software_chronicle_enterprise_internals_impl_NativeAffinity.cpp net_openhft_ticker_impl_JNIClock.cpp -o ../../../target/classes/libCEInternals.so
software_chronicle_enterprise_internals_impl_NativeAffinity.cpp:21:10: fatal error: jni.h: No such file or directory
   21 | #include <jni.h>
      |          ^~~~~~~
compilation terminated.
net_openhft_ticker_impl_JNIClock.cpp:21:10: fatal error: jni.h: No such file or directory
   21 | #include <jni.h>
      |          ^~~~~~~
compilation terminated.
make: *** [/mnt/c/Users/yhryy/Desktop/TryRealProj/projects/Java-Thread-Affinity-ea/work/affinity/src/main/c/Makefile:41: ../../../target/classes/libCEInternals.so] Error 1
[INFO] ------------------------------------------------------------------------


text:
Q: Is it possible to use 2 different retry beans for one service activator depending on an Exception thrown? I would like to do a serious retry for the service-activator only in case of a ConnectionException, for other exceptions I would like not to use a retry or a very light retry.  What configuration can I use?  The essence of my configuration is below:
<int:channel id="sDZCreationErrorChannel">
    <int:interceptors>
        <int:wire-tap channel="errorLogger"/>
    </int:interceptors>
</int:channel>

<int:channel id="sDZConnectionErrorChannel">
    <int:interceptors>
        <int:wire-tap channel="errorLogger"/>
    </int:interceptors>
</int:channel>

<int:chain input-channel="sDZCreationErrorChannel" output-channel="outboundMailChannel">
    <int-mail:header-enricher>
        <int-mail:to value="${integration.sdz.email.to}"/>
        <int-mail:subject value="${integration.sdz.email.subject.creation}"/>
    </int-mail:header-enricher>
    <int:transformer ref="integrationEmailTransformer" method="transformToEmail"/>
</int:chain>

<int:chain input-channel="sDZConnectionErrorChannel" output-channel="outboundMailChannel">
    <int-mail:header-enricher>
        <int-mail:to value="${integration.sdz.email.to}"/>
        <int-mail:subject value="${integration.sdz.email.subject.noconnection}"/>
    </int-mail:header-enricher>
    <int:transformer ref="integrationEmailTransformer" method="transformToEmail"/>
</int:chain>

<int:channel id="sDZCreationChannel">
    <int:queue/>
</int:channel>

<!-- Processing Creation Chain -->
<int:chain input-channel="sDZCreationChannel" output-channel="debugLogger"
    auto-startup="#{environment.getProperty('sd.zoo.enabled') == 'connect'}">
    <int:poller fixed-delay="500" />
    <int:filter ref="sDZIntegrationExistingRequestSentFilter" method="filter"/>
    <int:transformer ref="sDZCreationTransformer" method="transformOrder"/>
    <int:service-activator ref="sDZCreationServiceImpl" method="activateConfirmationCodes">
        <int:request-handler-advice-chain>
            <ref bean="retryAdvice"/>
        </int:request-handler-advice-chain>
    </int:service-activator>
</int:chain>

<int:exception-type-router input-channel="errorChannel" default-output-channel="integrationDeadLetterErrorChannel">
    <int:mapping exception-type="com.smartdestinations.connect.integration.exception.sdz.SDZCreationResponseException" channel="sDZCreationErrorChannel"/>
    <int:mapping exception-type="com.smartdestinations.connect.integration.exception.sdz.SDZConnectionException" channel="sDZConnectionErrorChannel"/>
</int:exception-type-router>

A: No, you can't use one retry advice alongside with other. The <request-handler-advice-chain> strategy is to wrap one advice into another with the order how they are configured within the <request-handler-advice-chain>. So, if you declare one retryAdvice and then another, the first one won't be reached until the second will finish its work.
I don't see the whole picture yet how to easy achieve your requirements, but I really sure that you should deal with custom RetryPolicy, where you can reach a target exception via:
public boolean canRetry(RetryContext context) {
    Throwable t = context.getLastThrowable();
    ...
}

Pay attention to that useful RetryContext object.
There is also interested hook as a RetryListener abstraction with which you can set some additional attributes into that RetryContext. For example in the SI RequestHandlerRetryAdvice:
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
    context.setAttribute("message", messageHolder.get());
    return true;
}


text:
Q: How do I get the current caret position? I have written a simple ST2 plugin that should just insert a timestamp at the current caret position. However, I am unable to find out how to get the current position.
I have
def run(self, edit):
    timestamp = "%s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    pos = ???
    self.view.insert(edit, pos, timestamp)

What should pos be?

A: Try with
pos = self.view.sel()[0].begin()

This gets the start point of the current selection (if nothing is selected, start and end of selection are the current cursor position).
If you want this to work with multiple selection, you have to iterate on all selections returned by self.view.sel():
for pos in self.view.sel():
    self.view.insert(edit, pos.begin(), timestamp)


text:
Q: text response from get request into a python pandas data frame excluding begin and end lines I am new to python, I am working on code that performs a get request from an api and returns the response in a text format and when I use
print(response.text)

I get the response in the below format -
ResponseBegin
Name|Age|Gender|Country
"ABC"|23|M|USA
"ABCD"|21|F|CAN
ResponseEnd

Can anyone please advise how to convert this into a pandas dataframe and also remove the ResponseBegin and ResponseEnd lines at the beginning and ending making the second row as the column header using | as a delimiter.
Thank you very much for your advise.
Thank you

A: It's more helpful if you do not show what print(response.text) contains, but just what response.text contains, since the print function is doing some formatting for human readability.
But I will assume that response.text is just a single string that looks like this:
'ResponseBegin\nName|Age|Gender|Country\n"ABC"|23|M|USA\n"ABCD"|21|F|CAN\nResponseEnd'

Notice the \n, which is the "newline" character.
There are several ways to solve this, but the easiest (fewest lines of code) I think is to export it to a CSV file and then read it in:
with open('mydf.csv', 'w') as fh:
   fh.write(response.text)

import pandas as pd
df = pd.read_csv('mydf.csv', sep='|', skiprows=1, skipfooter=1)

You can read more about read_csv for all of its handy tools, but here I am using:

*

*sep: the thing to use as a separator, | in your case

*skiprows/skipfooter: the number of lines at the beginning or end to skip