text:
Q: Framer-motion drag not respecting previously updated props A simple use-case is to allow a user to either click buttons to paginate in a slider, or drag. Both events call the same paginate function with a param to either go forward or back--simple stuff.
However, the trigger from drag seems to cause bizarre behavior where the slider wants to start the animation from several slides back as if it ignores the updated props. This doesn't happen when using the buttons and both use the same simple paginate call.
Any tips appreciated.
Minimal example:
export default function App() {
  const [position, setPosition] = useState<number>(0);

  const paginate = (direction: Direction) => {
    setPosition((prev) => {
      return direction === Direction.Forward
        ? Math.max(-800, prev - 200)
        : Math.min(0, prev + 200);
    });
  };

  return (
    <div className="App">
      <Slider>
        <Wrapper
          animate={{ x: position }}
          transition={{
            x: { duration: 1, type: "tween" }
          }}
          drag="x"
          dragConstraints={{
            top: 0,
            left: 0,
            right: 0,
            bottom: 0
          }}
          onDragEnd={(e, { offset, velocity }) => {
            const swipe = swipePower(offset.x, velocity.x);

            if (swipe < -swipeConfidenceThreshold) {
              paginate(Direction.Forward);
            } else if (swipe > swipeConfidenceThreshold) {
              paginate(Direction.Back);
            }
          }}
        >
          <Slide>1</Slide>
          <Slide className="alt">2</Slide>
          <Slide>3</Slide>
          <Slide className="alt">4</Slide>
          <Slide>5</Slide>
        </Wrapper>
      </Slider>
      <button onClick={() => paginate(Direction.Back)}>prev</button>
      <button onClick={() => paginate(Direction.Forward)}>next</button>
    </div>
  );
}

Codesandbox Demo

A: I have to say, this problem is quite interesting. However, I think I figured out a way for you to handle this. One thing I noticed is that if you comment out
onDragEnd={(e, { offset, velocity }) => {
            // const swipe = swipePower(offset.x, velocity.x);
            // if (swipe < -swipeConfidenceThreshold) {
            // paginate(Direction.Forward);
            // } else if (swipe > swipeConfidenceThreshold) {
            // paginate(Direction.Back);
            // }
          }}

the entire onDragEnd prop function, this example still doesn't work, since by the looks of things, the draggable component is not respecting your offset.
I realized that at this point, the problem is the internal state of the component is out of sync with your state. And would you look at that, the Framer Motion API actually provides a way to inspect this.
https://www.framer.com/api/motion/motionvalue/#usemotionvalue
It's the hook useMotionValue() which allows us to see what's actually happening. Turns out, our value is being set wrong when the user starts dragging:
useEffect(
    () =>
      motionX.onChange((latest) => {
        console.log("LATEST: ", latest);
      }),
    []
  );

We can see this, because the state "jumps" to 200 as soon as we start dragging.
So fixing in theory is easy, we just need to make sure to let that value "know" about our offset, and that way it's gonna start with the proper offset in mind!
Anyway, that was my thought process, here's the solution, all you need to do is set the left constraint to make it work:
dragConstraints={{
            top: 0,
            left: position,
            right: 0,
            bottom: 0
          }}

And tada! This makes it work. Here's my working solution: https://codesandbox.io/s/lingering-waterfall-2tsfi?file=/src/App.tsx


text:
Q: Convert SQL query to LINQ I have a beginners LINQ2SQL question. I have this huge (but not complex) SQL statement:
SELECT Artikel.ArtikelID,
       Artikel.CategorieID,
       Artikel.ImageFile,
       Artikel.RetailPrijs,
       ISNULL(ShopArtikel.VerkoopsPrijs, Artikel.VerkoopsPrijs) AS VerkoopsPrijs,
       Artikel.ArtikelCode,
       Artikel.InAssortimentSinds,
       ArtikelTaal.ArtikelNaam,
       ArtikelTaal.ArtikelOmschrijving
FROM   Artikel
INNER JOIN ArtikelTaal ON Artikel.ArtikelID = ArtikelTaal.ArtikelID
INNER JOIN ShopArtikel ON Artikel.ArtikelID = ShopArtikel.ArtikelID
INNER JOIN Categorie ON Artikel.CategorieID = Categorie.CategorieID
INNER JOIN CategorieTaal ON Categorie.CategorieID = CategorieTaal.CategorieID
INNER JOIN Shop ON ShopArtikel.ShopId = Shop.ShopID
INNER JOIN CategorieGroepShop ON Shop.ShopID = CategorieGroepShop.ShopId
INNER JOIN Taal ON ArtikelTaal.TaalCode = Taal.TaalCode AND CategorieTaal.TaalCode = Taal.TaalCode
INNER JOIN CategorieGroepTaal ON Taal.TaalCode = CategorieGroepTaal.TaalCode AND CategorieGroepShop.CategorieGroepId = CategorieGroepTaal.CategorieGroepID
INNER JOIN CategorieGroep ON Categorie.CategorieGroepID = CategorieGroep.CategorieGroepID AND CategorieGroepTaal.CategorieGroepID = CategorieGroep.CategorieGroepID AND CategorieGroepShop.CategorieGroepId = CategorieGroep.CategorieGroepID
WHERE (Shop.ShopID = 23) AND
      (Taal.TaalCode = 'dut') AND
      (Artikel.Onzichtbaar = 0) AND
      (Artikel.NietBestelbaar = 0) AND
      (Categorie.Onzichtbaar = 0) AND
      (Artikel.Voorraad >= Artikel.LevertijdDrempel)

and I am converting this to LINQ and have this:
var allProducts = from artikelen in dc.Artikels
join sa in dc.ShopArtikels on artikelen.ArtikelID equals sa.ArtikelID
join at in dc.ArtikelTaals on artikelen.ArtikelID equals at.ArtikelID
join cat in dc.Categories on artikelen.CategorieID equals cat.CategorieID
join catt in dc.CategorieTaals on cat.CategorieID equals catt.CategorieID
join catg in dc.CategorieGroeps on cat.CategorieGroepID equals catg.CategorieGroepID
join catgt in dc.CategorieGroepTaals on catg.CategorieGroepID equals catgt.CategorieGroepID
join sh in dc.Shops on sa.ShopId equals sh.ShopID
join catgs in dc.CategorieGroepShops on sh.ShopID equals catgs.ShopId
join tl in dc.Taals on new { tc1 = at.TaalCode, tc2 = catgt.TaalCode } equals new { tc1 = tl.TaalCode, tc2 = tl.TaalCode }
where sh.ShopID == shop.BLL.Business.ShopController.CurrentShop.Id
select dc.Artikels;

but I have the idea that I made some (minor) mistakes while joining.
any ideas please!
EDIT
I have rewritten the LINQ query to this:
var allProducts = from artikelen in dc.Artikels
join at in dc.ArtikelTaals on artikelen.ArtikelID equals at.ArtikelID
join sa in dc.ShopArtikels on artikelen.ArtikelID equals sa.ArtikelID
join cat in dc.Categories on artikelen.CategorieID equals cat.CategorieID
join catt in dc.CategorieTaals on cat.CategorieID equals catt.CategorieID
join sh in dc.Shops on sa.ShopId equals sh.ShopID
join catgs in dc.CategorieGroepShops on sh.ShopID equals catgs.ShopId
join tl in dc.Taals on new { tc1 = at.TaalCode, tc2 = catt.TaalCode } equals new { tc1 = tl.TaalCode, tc2 = tl.TaalCode }
join catgt in dc.CategorieGroepTaals on new { tl.TaalCode, catgs.CategorieGroepId } equals new { catgt.TaalCode, catgt.CategorieGroepID }
join catg in dc.CategorieGroeps on new { cat.CategorieGroepID, catgt.CategorieGroepID, catgs.CategorieGroepId } equals new { catg.CategorieGroepID, catg.CategorieGroepID, catg.CategorieGroepID }
where sh.ShopID == 230
select dc.Artikels;

but I have a syntax error after "dut" }
Edit 2:
changed the join and replaced "dut" with the corresponding field in the database.
still have the error after the first }
it says: type inference failed in the call to 'Join'

A: Some of the SQL joins have multiple join conditions, which you didn't put in the LINQ query.

A: If this is something that will be frequently run then you should rewrite it as a stored procedure.  I believe it is too convoluted and complex for a LINQ statement - too hard to see what's going on.

A: There is a tool for it, but I didn't try it. May be it's usefull for you.
http://www.sqltolinq.com/

A: It looks like the error line is actually a "Where" cause but not "Joining".
You can actually split the whole long Linq statement into smaller Query.
so for this case, its better to split it like this:
var at = from a in dc.ArtikelTaals
           where a.TaalCode == "dut"
           select a;

var catt = from c in dc.CategorieTaals
           where c.TaalCode == "dut"
           select c;

.....

and you can join the IQueryable "at" and "catt" in your complex query later.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Null TokenId error while processing an input text I am working on a netbeans module to parse html markups by following this tutorial.
For the keyword html, I wrote following javacc file.
options {
  JAVA_UNICODE_ESCAPE = true;
  ERROR_REPORTING = false;
  STATIC = false;
  COMMON_TOKEN_ACTION = false;
  TOKEN_FACTORY = "Token";
  JDK_VERSION = "1.8";
  BUILD_PARSER = false;
}

PARSER_BEGIN(HTMLParser)

package org.html.jcclexer;

import java.io.*;

/**
 * Grammar to parse Java version 1.5
 * @author Sreenivasa Viswanadha - Simplified and enhanced for 1.5
 */

public class HTMLParser {}

PARSER_END(HTMLParser)

/* WHITE SPACE */

TOKEN :
{
  < WHITESPACE:
  " "
| "\t"
| "\n"
| "\r"
| "\f">
}

TOKEN   : { < HTML : "html" > }

It colors my html word perfectly but then it gives error:
java.lang.IllegalArgumentException: Token id must not be null. Fix lexer org.html.lexer.HTMLexer@1e6bbd25

test.html contains following word only:
html
I am not sure it's error due to my .jj file or something else.


text:
Q: Cannot access WSUS AutoUpdate Results registry key of CERTAIN x64 OS I have been testing a Powershell script to monitor the last install datetime of downloaded patches from WSUS on all my machines in the domain.
I found the path from http://technet.microsoft.com/en-us/magazine/gg153542.aspx
The paths which I use are:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Detect\
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Download\
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Install\
In all the paths above, there is a variable called LastSuccessTime which I use.
When I ran my script against all the machines, I cannot get anything from:
Windows 2008 R2 64-bit
Windows 2003 Enterprise 64-bit
Windows XP 64-bit
Windows Vista 64-bit
However, I was also get the registy info from Windows 7 64-bit or Windows 2003 32-bit.
The really weird things are:
1) I was able to use regedit to manually remote access those 64-bit machines and confirm that the path was valid and there is a LastSuccessTime field there.
So, I can confirm that the same path applies to all OSes.
2) On those 64-bit machines, I was able to fetch other registry entries without any problem.
3) I reran the script and this time shortening the path to see where the access was aborted.
It is in here
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate
where the access was denied.
Could there be a restriction on reading the ...\WindowsUpdate registry folder while WSUS is active for 64-bit machines?

A: As it turns out, it has to do with the following:
1)  The Powershell ISE was running on 32-bit machine and it was trying to remotely scan a 64-bit Windows OS.
2)  WSUS running on a 64-bit Windows OS is a 64-bit app.
3)  32-bit Powershell ISE and 32-regedit cannot remotely "see" the following WSUS entries:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results
You can only "see" as far as:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion
The WindowsUpdate subkey is invisible to 32-bit app.
To solve the problem, always running Powershell on a 64-bit Windows OS and you can remotely "see" both 32-bit and 64-bit Windows OS.


text:
Q: content navigator P8 stepprocessor property order We have a FileNet 5.1 system with Content Navigator as the UI. From content navigator we use the default workflow stepprocessor to display workflow steps.
We use the IBM EDS service to add additional properties(like mandatory fieds) to these stepprocessors.
This service loads JSON files to augment the workflow fields.
I now have a question what determines the order of the property in how th content navigator/eds determines the fields.
Thanks.

A: It turns out it is not possible to manipulate the property order out of the box. The solution: make a custom stepprocessor where you can manipulate it yourself.


text:
Q: How to make Java Set? Can anyone help me?
example

*

*A {1,2,3}

*B {1,4,5}

Code snippet:
a.intersect(b).print()
// Result 1 . twin between two object

a.merge(b).print()
// Result 1,2,3,4,5

It is valid if I write code below?
If not, which part I have to fix?
public static void main(String[] args) {
    // TODO code application logic here
   Set<Integer> a = new TreeSet<Integer>();
   a.add(1);
   a.add(2);
   a.add(6);
   a.remove(2);
   a.add(1); //gak berpengaruh karena sudah ada yang 1 sebelumnya
   //mengapa begituu ? karena et adalah collection yang tidak dapat memiliki elemen kembar.
   System.out.println("A = " + a);

   Set<Integer> b = new TreeSet<Integer>();
   b.add(2);
   b.add(6);
   b.add(1);
   System.out.println("B = " + b); //hasilnya 1,2,6.
   //loh?? kok bisa ? krn sy pake TreeSet, jadi udah terurut.

   b.retainAll(a); //ini rumus intersect XD
   for (Integer i: b)
   {
       System.out.print(i);
   }
}

}

A: Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals;  wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:
// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!


text:
Q: How to get Translation working on CakePHP? After reading and watching tutorials online, I can't get translations to work on CakePHP.
My website is in English by default but I want the option to switch it in French.
There's an empty "i18n" table in the database. There are also a Locale/default.pot and Locale/cake.pot files. I used PoEdit to generate a Locale/fra/default.po file (+ default.mo).
I read that I must type
Configure::write('Config.language', 'fra')

in Config/bootstrap.php and it didn't work.
What am I missing?


text:
Q: Why objects which placed close without any indent, have a space between each other in FabricJS I need to build a frame for my image in Fabric JS. This frame should be built dynamically to fit any size of the image.
To do this I use two images:

*

*http://i.imgur.com/3VqKv1O.png - image for side

*http://i.imgur.com/w41HYN3.png - image for corner

I've developed an algorithm, which does it and it works! That's great.
But I have a problem with the positioning of pieces of the frame.
As you can see in my example, there is strange space between pieces and they placed not on the same level by Y axis. I'm very surprised because these pieces have the same height and they have correct values for left and top.
Anybody knows what can be a reason of this problem?
Thanks in advance
JS Fiddle https://jsfiddle.net/Eugene_Ilyin/gzjxhLtm/9/

var sideObj = new fabric.Rect(),
  frameSideTopImage = new fabric.Image(new Image(), {type: 'image'}),
  frameCornerTLImage = new fabric.Image(new Image(), {type: 'image'}),
  imageSize = 172,// Size of the image (width = height).
  leftOffset = 100,
  topOffset = 100;

// Load image for corner.
fabric.util.loadImage('http://i.imgur.com/w41HYN3.png', function (img) {
  // Set image and options for top left corner.
  frameCornerTLImage.setElement(img);
  frameCornerTLImage.setOptions({
   strokeWidth: 0,
    left: leftOffset,
    top: topOffset
  });

  // Load image for side.
  fabric.util.loadImage('http://i.imgur.com/3VqKv1O.png', function (img) {
    frameSideTopImage.setElement(img);

    // Create canvas for pattern.
    var canvasForFill = new fabric.StaticCanvas(fabric.util.createCanvasElement(), {enableRetinaScaling: false});
    canvasForFill.add(frameSideTopImage);

  // Configure top side for the frame.
    sideObj.setOptions({
     strokeWidth: 0,
      objectCaching: false,
      originX: 'left',
      originY: 'top',
      left: imageSize + 100,
      top: 100,
      width: 800,
      height: imageSize,
      fill: new fabric.Pattern({
        source: function () {
          canvasForFill.setDimensions({
            width: imageSize,
            height: imageSize
          });
          return canvasForFill.getElement();
        },
        repeat: 'repeat-x'
      })
    });

    var canvas = new fabric.Canvas('c');
    var frame = new fabric.Group([sideObj, frameCornerTLImage], {
        strokeWidth: 0,
        width: 800 * 3,
        height: imageSize * 3,
        scaleX: 1/3,
        scaleY: 1/3,
      }
    );
    canvas.add(frame);
    canvas.renderAll();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.7/fabric.js"></script>
<body>
  <canvas id="c" width="1000" height="1000"></canvas>
</body>

A:

var sideObj = new fabric.Rect(),
  frameSideTopImage = new fabric.Image(new Image(), {type: 'image'}),
  frameCornerTLImage = new fabric.Image(new Image(), {type: 'image'}),
  imageSize = 172,// Size of the image (width = height).
  leftOffset = 100,
  topOffset = 100;

// Load image for corner.
fabric.util.loadImage('http://i.imgur.com/w41HYN3.png', function (img) {
  // Set image and options for top left corner.
  frameCornerTLImage.setElement(img);
  frameCornerTLImage.setOptions({
    left: leftOffset,
    top: topOffset
  });

  // Load image for side.
  fabric.util.loadImage('http://i.imgur.com/3VqKv1O.png', function (img) {
    frameSideTopImage.setElement(img);

    // Create canvas for pattern.
    var canvasForFill = new fabric.StaticCanvas(fabric.util.createCanvasElement(), {enableRetinaScaling: false});
    canvasForFill.add(frameSideTopImage);

 // Configure top side for the frame.
    sideObj.setOptions({
      objectCaching: false,
      originX: 'left',
      originY: 'top',
      left: imageSize + 100,
      top: 100,
      width: 800,
      strokeWidth:0,
      height: imageSize,
      fill: new fabric.Pattern({
        source: function () {
          canvasForFill.setDimensions({
            width: imageSize,
            height: imageSize
          });
          return canvasForFill.getElement();
        },
        repeat: 'repeat-x'
      })
    });

    var canvas = new fabric.Canvas('c');
    canvas.add(sideObj);
    canvas.add(frameCornerTLImage);
    canvas.renderAll();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.7/fabric.js"></script>
<body>
  <canvas id="c" width="1000" height="1000"></canvas>
</body>

set strokeWidth:0 , strokeWidth is by default 1, so it creates a border of width 1 .


text:
Q: Berkeley Pacman CornersProblem I've been working on Berkeley's Pacman project for their A.I. course. I'm running into an issue figuring out how to find a path so that pacman touches all four corners of the pacman board. It uses a general breadth-first search algorithm. It only returns a path when there is one goal state, and not four.
The project for this particular question states:
In corner mazes, there are four dots, one in each corner. Our new search problem is to find the shortest path through the maze that touches all four corners (whether the maze actually has food there or not). Note that for some mazes like tinyCorners, the shortest path does not always go to the closest food first! Hint: the shortest path through tinyCorners takes 28 steps.
Implement the CornersProblem search problem in searchAgents.py. You will need to choose a state representation that encodes all the information necessary to detect whether all four corners have been reached.
BFS:
fringe = util.Queue()
fringe.push( (problem.getStartState(), [], 0) )
visited = set()

while not fringe.isEmpty():
    curState, curAction, curCost = fringe.pop()

    if curState in visited:
        continue
    visited.add(curState)

    if problem.isGoalState(curState):
        return curAction

    for state, action, cost in problem.getSuccessors(curState):
        fringe.push( (state, curAction + [action], cost ) )

return []

util.raiseNotDefined()

Search Agent Start State:
def getStartState(self):
    """
    Returns the start state (in your state space, not the full Pacman state
    space)
    """
    "*** YOUR CODE HERE ***"
    return self.startingPosition
    util.raiseNotDefined()

SearchAgent Goal State
"""
Returns whether this search state is a goal state of the problem.
"""
"*** YOUR CODE HERE ***"

// TODO
util.raiseNotDefined()

I'm stuck on the returning the goal state so that the test passes. Currently, the function returns:
*** FAIL: test_cases/q5/corner_tiny_corner.test

*** Corners missed: [(1, 1), (1, 6), (6, 1), (6, 6)]

*** Tests failed.

Or I return only 1 out of the 4 corners.

A: What defines the goal state? When all 4 corners are touched.
Given that you have all 4 corner coordinates already, you can use a simple Python list to store the corners as you pass the state along in the successor, removing from the list of corners when you reach that state. (The check itself would go in the getSuccessors() function since you pass along a state containing your current position).
Then it should be simple for your goal condition to check this list.


text:
Q: Is it possible to update a mongodb collection (using Mongoose) in a post method? I am in a situation where I need to do 2 things:
1) Create 50+ collections and fill them with documents
2) Based on the info in each document I am adding, edit an existing collection.
The main usage first was the first step which works fine. Because I was adding collections to the DB I used a post method. Now I need to update another collection and in this case a put or even a patch http method will be better suited.
What is the correct way to approach this? Currently I am using the model.findOne and mode.Update but nothing is getting updated. I am wondering if it is due to the fact that it is a post method and not a put method
Code:
After I add tokens which works I call the function
                      // This adding works fine
                      new tokenModel(tokenSchema).save();
                      // This function is handling the update in a different collection
                      addTraitsToGame(tokenData);

And the function is:
const addTraitsToGame = (tokenData) => {
// Game is another collection I want to update
Game.findOne({ "opensea.game.address": tokenData.asset_contract.address })
  .then(existingGame => {
    if (existingGame) {
      newArrayToReplaceExistingOne= [];
      try {
        // Not really relevant, this is how I fill a new object that will be pushed to the new array
        for (let i = 0; i < someLength; i++) {
          let tokenTrait = tokenData.traits[i];
          let gameTrait = existingGame.opensea.traits.find(trait => trait.type === tokenTrait.trait_type);
          if (gameTrait && gameTrait.form === "values") {
            gameTrait.attributes[tokenTrait['trait_type']] = tokenTrait['trait_count']
            // This is the relevant line, filling up the array with objects
            newArrayToReplaceExistingOne.push(gameTrait);
          }
        }
        // Updating here!
        Game.update(
          { "opensea.game.address": tokenData.asset_contract.address },
          {
            $set: {
              "opensea.game.traits": traitsWithCount
            }
          },
          function (err, user) {
            if (err) return handleError(err);
            else {
              console.log("Update should have been successful");
            }
          }
        );
      }
      catch (err) {
        console.log(err);
      }
    }
  });

}
Nothing is updated after that.

A: You can also use
model.findOneAndUpdate({_id:req.body.id},{key you need to update:"updated value"},(req,res)=>{
 your code here.
}

Hope it could help.


text:
Q: How Would I Pronounce (In Topology), Dual of V* Operations Descriptions I am looking at operations for addition and scalar multiplication while reading about the dual of a vector space. Symbols are chained together in long lines (which is what makes this much more difficult to know how to pronounce), and I am wondering how I would read these aloud?
LaTeX of the operations seems to be described by what follows, but I will add PNG images too:
$$a\underset{\rightarrow}{v} : \mathsf{V} \rightarrow \mathsf{K}\ \ :\ \ \vec{x} \mapsto (a\underset{\rightarrow}{v})[\overset{\rightarrow}{x}] := a(\underset{\rightarrow}{v}[\vec{x}])$$
$$\underset{\rightarrow}{v} + \underset{\rightarrow}{w} : \mathsf{V} \rightarrow \mathsf{K}\ \ :\ \ \vec{x} \mapsto (\underset{\rightarrow}{v} + \underset{\rightarrow}{w})[\vec{x}] := \underset{\rightarrow}v[\vec{x}] + \underset{\rightarrow}w[\vec{x}]$$


text:
Q: App icon not being created when i change the launcher activity from LoginActivity to Main2Activity When i change from Case 1 to Case 2 . The app icon is not being created, but the activity is running.
CASE1:Manifest File When LoginActivity is launcher activity
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".RegisterActivity"
        android:label="@string/title_activity_register"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".Main2Activity"
        android:label="@string/title_activity_main2"
        android:theme="@style/AppTheme.NoActionBar"
        >

    </activity>

</application>

CASE2:Manifest File When Main2Activity is launcher activity
 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".Main2Activity"
        android:label="@string/title_activity_main2"
        android:theme="@style/AppTheme.NoActionBar"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".RegisterActivity"
        android:label="@string/title_activity_register"
        android:theme="@style/AppTheme.NoActionBar" />

    <activity
        android:name=".LoginActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">

    </activity>

</application>

A: Activity and Application label should be same for the activity to have an icon created.
EDIT CODE FOR CASE2:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
    android:name=".Main2Activity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar"
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity
    android:name=".RegisterActivity"
    android:label="@string/title_activity_register"
    android:theme="@style/AppTheme.NoActionBar" />

<activity
    android:name=".LoginActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">

</activity>


text:
Q: Filling a column with the amount of duplicated values in another column I have a df like this:

month
outcome
mom.ret

10/20
winner
0.2

10/20
winner
0.9

11/20
winner
0.6

11/20
winner
0.2

11/20
winner
0.9

10/20
loser
0.6

10/20
loser
0.2

10/20
loser
0.9

11/20
loser
0.6

I would like to add another column, which has 1 / by the counts of times the value "winner" or "loser" appears per each month on the column outcome. The expected output for the example df is:

month
outcome
mom.ret
q

10/20
winner
0.2
1/2

10/20
winner
0.9
1/2

11/20
winner
0.6
1/3

11/20
winner
0.2
1/3

11/20
winner
0.9
1/3

10/20
loser
0.6
1/3

10/20
loser
0.2
1/3

10/20
loser
0.9
1/3

11/20
loser
0.6
1/1

I thought of using the function count to count how many times the values are repeated, but then I need to specify that the "count" should be done per each date. Any ideas?

A: You can use this code to achieve what you want, assuming your original DataFrame is called df:
counts = df.groupby(['month', 'outcome'], as_index=False).count()
counts = counts.rename(columns={'mom.ret': 'q'})
# Use this line if you want the float value of the division 0.5
# counts['q'] = 1/counts['q']
# Use this line if you want the string '1/2'
counts['q'] = counts['q'].apply(lambda x: f'1/{x}')
result = pd.merge(df, counts)

The result looks like this:
month   outcome mom.ret q
0   10/20   winner  0.2 1/2
1   10/20   winner  0.9 1/2
2   11/20   winner  0.6 1/3
3   11/20   winner  0.2 1/3
4   11/20   winner  0.9 1/3
5   10/20   loser   0.6 1/2
6   10/20   loser   0.2 1/2
7   11/20   loser   0.9 1/2
8   11/20   loser   0.6 1/2

A: Use df['q'] = 1/df.groupby(['month', 'outcome']).transform('count').

A: Updated answer:
@timgeb's required a groupby of just the month for me. To output a fraction instead of a decimal, I used the handy humanize library.
import humanize      # pip install humanize # if needed

df['q'] = 1 / df.groupby(['month', 'outcome'])['month'].transform('count')
df['q'] = df['q'].apply(lambda x : humanize.fractional(x))

Note that you can't just use .count() with the groupby - you need the transform method to return a Series of the same length as the original DataFrame.
Using Python 3.9.7, pandas 1.4.1
Code to make the original df (I left out the mom.ret column that wasn't germane).
import pandas as pd

df = pd.DataFrame(
    {
        "month": [
            "10/20",
            "10/20",
            "11/20",
            "11/20",
            "11/20",
            "10/20",
            "10/20",
            "10/20",
            "11/20",
        ],
        "outcome": [
            "winner",
            "winner",
            "winner",
            "winner",
            "winner",
            "loser",
            "loser",
            "loser",
            "loser",
        ],
    }
)


text:
Q: Displaying an array result with rails Here is my problem:
Everything works but I have a display that resembles ["1","2","3"]. I would like 1 2 3. I tried all to_ functions but that does not change ..
Thanks for your time.
model.rb:
validates :check, presence: true
validate :check_must_be_3

  private
    def checks_must_be_3
      if !check != 3
        errors[:base] << "You must select exactly 3 checks"
      end
    end

html:
<%= simple_form_for @answer do |f| %>

Choose 3 answers

    <% (1..5).each do |x| %>

          <input type="checkbox" name="answer[check][]" id="optionsCheckbox<%= x %>" value="<%= x %>" />
          <%= x %>

    <% end %>
    <%= f.button :submit, "Submit", class: "btn btn-primary" %>
<% end %>

controller:
private

def answer_params
    params.require(:answer).permit(check:[])
end

answer is a string in db.

A: Just add below lines on your result
'["1", "2", "3"]'.split("[").pop().split("]").first.tr!('"', '')

Not the best way but will work for you
One other solution is
 '["1", "2", "3"]'.reverse.chop.reverse.chop.tr!('""', '')


text:
Q: Solution of equality $N'(t)=f(N(t)) N(t)$ have the following property: $\lim_{t\to\infty} N(t)=K$- proof Check that if $f$ is such a differentiable and strictly increasing function that $f(K)=0$, then the solution of equality $N'(t)=f(N(t)) N(t)$ have the following property: $\lim_{t\to\infty} N(t)=K$.
It's the fact that $N'(t)>0$, when $N(t)<K$,
and $N'(t)<0$, when $N(t)>K$.
The problem is kind of relates to Verhulst Model.
I need help with this exercise, any will be appreciated.


text:
Q: JSX template literals for an inline style I'm trying to add an inline style on an element which includes variables.
Hard-coding the values works:
<circle style={{ strokeDasharray: "75, 25" }} ></circle>

But I need a way for both of the numbers in this style to pull from variables.
I've tried a variety of curly braces and backticks - I think I need template literals, but am not sure how the syntax works for them inside of the double curly braces that this inline style seems to require.
This one
<circle style={`{strokeDasharray: "${ percent }, 25"}`} ></circle>

fails with message: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.
This one
<circle style={{`strokeDasharray: "${ percent }, 25"`}} ></circle>

causes the build to fail completely.
This one
<circle style={{strokeDasharray: "`${ percent }`, 25"}} ></circle>

builds, but no inline style is added at all.
In addition to using the percent variable for the first numeric value, I need to calculate the second numeric value - it will always be 100 minus the percent variable.

A: style={{strokeDasharray: `${percent},${100 - percent}`}}

A: The key thing here is that the code within the outer {} is pure JavaScript code (specifically, an expression [not a statement]). With the style property, you specify an object:
<circle style={yourObjectHere} />

In your case, you're specifying an object literal, just like any other object literal in JavaScript. So you have the property name, a colon, and the property value. Since part of the value is from a variable, you use the usual ways of creating a concatenated string:
<circle style={{strokeDasharray: percent + ", 25"}} />

or
<circle style={{strokeDasharray: `${percent}, 25`}} />

etc.
(If you're wondering why I used /> instead of ></circle>, it's because even non-void elements are typically self-closed in JSX. JSX isn't quite SVG or HTML or even XHTML, it's its own beast.)

You probably  want to calculate the second number as well, as Михаил Мишин shows, so with the above that's:
<circle style={{strokeDasharray: percent + ", " + (100 - percent)}} />

or
<circle style={{strokeDasharray: `${percent}, ${100 - percent}`}} />


text:
Q: Time Parsing Library Similar to JIRA Time Format I'm looking for a parsing library for strings of the format "2y 1M 3w 4d 12h 20m 10s" (2 years, 1 month, 3 weeks, 4 days, 12 hours, 20 minutes, and 10 seconds). Parsing them into Millis would likely be the shortest path forward. Essentially, I am looking to add/subtract the parsed string from a timestamp.

A: Solution courtesy @shmosel:
import org.joda.time.format.PeriodFormatterBuilder

val pf = new PeriodFormatterBuilder()
      .appendYears()
      .appendSuffix(" y", "y")
      .appendSeparator("", " ")
      .appendMonths()
      .appendSuffix(" M", "M")
      .appendSeparator("", " ")
      .appendWeeks()
      .appendSuffix(" w", "w")
      .appendSeparator("", " ")
      .appendDays()
      .appendSuffix(" d", "d")
      .appendSeparator("", " ")
      .appendHours()
      .appendSuffix(" h", "h")
      .appendSeparator("", " ")
      .appendMinutes()
      .appendSuffix(" m", "m")
      .appendSeparator("", " ")
      .appendSeconds()
      .appendSuffix(" s", "s")
      .toFormatter()

    // Is there a more idiomatic way to add
    val buffer = pf.parsePeriod(bufferPeriod)

Note that order matters (10y 10s is valid, 10s 10y is not).


text:
Q: find successor in AVL tree there is avl tree with nodes, and each node has only 3 fields:
1.right child
2.left child
3.value(key)
notice that it doesnt have such field "parrent" or "father".
my question is: in case we want to know the successor of EVERY node in the tree,
and without use any LinkedList or any collection, what is the method to do so?

A: You could do something like this
// Returns the last node in the inorder traversal of tree,
// or prev if tree is null.
Node printSuccessors(Node tree, Node prev) {
  if (tree == null) {
    return prev;
  }
  Node lastLeft = printSuccessors(tree.leftChild(), prev);
  if (lastLeft != null) {
    System.out.println("The successor of " + lastLeft.key()
      + " is " + tree.key());
  }
  return printSuccessors(tree.rightChild(), tree);
}

and then call printSuccessors(root, null).


text:
Q: how to retrieve an array in this OOP case? [php] While I know how to solve this in procedural PHP, I'm having difficulites with OOP. Some lines of code are shortened (e.g. html).
So, a user enters a number, which object $army1 passes to the constructor while creating itself. My constructor fills an array with for loop ($filled_army), but I don't know how to retrieve it the right way (so I could print it out after), since constructors don't have return values?
Adding print_r($filled_army); in constructor will print out the values, just to mention.
Also, if this problems shouldn't be solved through __construct, can someone help me how to do it through my own methods within class? I'm guessing it should be done with getters & setters, but I also had problems with using them, since one variable is passed in index.php, while other variable ($filled_army), is property of class...
index.php
<form>
  <input type="number" name="size">
</form>

<?php
    $army1 = new Army($_GET['size']);
    // $army1->getArmy(); ??
?>

army.class.php
<?php
class Army {
  public $filled_army = [];
  public size;
  //...
  public function __construct($size){
        $this->size = $size;
        $arrayOfSoldiers = [10,20,30];

        for($i=0; $i<$size; $i++)
        {
            $filled_army[$i] = $arrayOfSoldiers[mt_rand(0, count($arrayOfSoldiers) - 1)];
        }
    }
}
?>

A: Since you have declared the $filled_army property as public, it will be available right after instantiating using standard object notation in PHP, for example:
$army1 = new Army($_GET['size']);
$army1->filled_army; // Now contains your array;

However, setting the property's visibility to public means that any code can modify the property, not only the object it was created by. Usually, to work around this we set properties to either protected or private, and then use getters/setters:
class Army
{
  private $filled_army = [];
  private $army_size   = 0;

  private static $_soldiers = [ 10, 20, 30 ];

  function __construct($size)
  {
    $this->army_size = $size;

    for($i = 0; $i < $size; $i++)
    {
      $this->filled_army[] = self::$_soldiers[ mt_rand(0, count(self::$_soldiers) - 1) ];
    }
  }

  // Getter for the army:
  public function getArmy()
  {
    return $this->filled_army;
  }

  // Getter for the size:
  public function getArmySize()
  {
    return $this->army_size;
  }
}

Now, we can access the getArmy() method (or similarly the getArmySize() method):
$army1 = new Army($_GET['size']);
$army1->getArmy();     // Returns the army
$army1->getArmySize(); // Returns the value of $_GET['size'];

It's also worth noting that PHP supports Magic Getters/Setters which may be useful for your project.
Also note that we do not need a visibility modifier for the constructor function (__construct() in PHP is always publicly visible).


text:
Q: PaddleOCR Error flag 'flagfile' was defined more than once Am encountering an issue running PaddleOCR on M1 Macbook
ERROR: flag 'flagfile' was defined more than once (in files '/Users/paddle/xly/workspace/f2bafd01-b80e-4ac8-972c-1652775b2e51/Paddle/build/third_party/gflags/src/extern_gflags/src/gflags.cc' and '/tmp/gflags-20211021-3963-1mi18ai/gflags-2.2.2/src/gflags.cc').

A: This is related to the new version 2.6. With 2.5 you can use the wheel with the M1 (maybe you will need to debug some of the dependencies).
The good news is I've just installed PaddleOCR 2.6.1.2 on my Mac, right now.
You have two options:

*

*You can upgrade to Python 3.10 (I am using 3.10.8) and then this error is gone

*You can stick to Python 3.9 or lower and install PaddleOCR manually

If you want to continue with Python 3.9 or lower, then instead of installing via pip or conda, you do it manually by building the egg locally (it is an egg and not a wheel because it is using setuptools).
Assuming you already have a conda env or similar (mine has Python 3.10 and paddlepaddle 4.2.1, you'll probably need to install setuptools), you proceed as follows:
git clone https://github.com/PaddlePaddle/PaddleOCR.git
cd PaddleOCR
conda install --file requirements.txt
python setup.py install

After this you can use PaddleOCR on that environment.
Dependencies that can bring on some issues are Shapely, PyMuPDF, protobuf... Anyway I believe this whole issue will be fixed in the next release and then we will be able to use the wheel as-is.

A: MAC M1 chip can't follow Paddle's document step by step. I solve it by downloading the source code and recompiling it
https://juejin.cn/post/7189617837424672805


text:
Q: Use the axioms of ZFC to prove the cartesian product A x B is a set I'm given that x, y, and A, B are sets, and must prove that the Cartesian product
A x B := {(x, y) | x $\in$ A and y $\in$ B} is a set.
I'm certain that I need to use AC somehow, but I'm having trouble understanding what exactly it would even mean for me to apply it, or how I should go about it.
Here is what believe to understand about AC: if I have a set, say Z = {a, b, c} then applying AC means that I have a function:
f:Z $\mapsto$ $\cup$Z, i.e., f:{a, b, c} $\mapsto$ {{a}, {b}, {c}}
And we have that $\forall$z $\in$ Z (f(z) $\in$ z)
Unfortunately I'm having trouble seeing the consequences of this and how I can extend it to prove that the Cartesian product between A and B is indeed a set. But it could be as well that I've totally misinterpreted the axiom and so obviously can't draw any meaningful conclusions. I would really appreciate if someone could clear the air for me and hopefully set me in the right direction.

A: Use the definition of a pair along with Comprehension.
No need for Choice.


text:
Q: SQL Update, Set value has ' (single quote) and '' Double quote How do i proceed? I'm doing an update but the value has ' and " quotes,
How do I proceed?
This is how my query looks like
Update Users
set info = '[user{"LinkAction('togglemore', 'companies','jobs')","IsVisible":true}]'
where user like '%admin%'

How do i make the SET to consider everything in the ' single quote '

A: You can use two single quote ''
 Update Users
    set info = '[user{"LinkAction(''togglemore'', ''companies'',''jobs'')","IsVisible":true}]'
    where user like '%admin%'

sqlfiddle : http://sqlfiddle.com/#!18/402e8/1


text:
Q: Mybatis : "less than" issue in Select annotations I am using java7, spring 3 and mybatis
Pom.xml
<org.mybatis-version>3.2.8</org.mybatis-version>
<org.mybatis-spring-version>1.2.2</org.mybatis-spring-version>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${org.mybatis-version}</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>${org.mybatis-spring-version}</version>
</dependency>

While using annotation based Select i came across with strange issue where below mentioned code was throwing exception due to use of < (Less then) while > (greater then) works as expected.
<script>
SELECT * FROM STUDENT
WHERE DEPARTMENT_ID = #{depId}
<if test='joiningDate != null'> AND STUDENT_ID <= #{joiningDate} </if>
</script>

After googling for a while i find out this issue reported below.
https://code.google.com/p/mybatis/issues/detail?id=787
Above issue can be fixed by replacing < (less then) with < as shown below.
<script>
SELECT * FROM STUDENT
WHERE DEPARTMENT_ID = #{depId}
<if test='joiningDate != null'> AND STUDENT_ID <= #{joiningDate} </if>
</script>

I have also came across of suggestion for using  using CDATA or ^ in respected scenarios which i haven't given try yet.
Question:

*

*My question is shouldn't this issue be fixed by Mybatis team (at-least xml specific conversion for frequently used query tags) or this behaviour is as expected since we are using <script> tag ??

*Is there any alternate solution which i have missed out ?

A: To be fair, it's not the issue in MyBatis, but the behaviour of XML parsing.
If you don't want characters such as < and & to be parsed, you can use the term CDATA to prevent the XML parser to parse such text. Please refer to http://www.w3schools.com/xml/xml_cdata.asp for detail. Or you may escape it with &lt as comments.
I.E.
<script>
SELECT * FROM STUDENT
WHERE DEPARTMENT_ID = #{depId}
<if test='joiningDate != null'>
<![CDATA[
AND STUDENT_ID <= #{joiningDate}
]]>
</if>
</script>

A: you too can use that.
<= less or equal

    SELECT * FROM STUDENT
    WHERE DEPARTMENT_ID = #{depId}

= greater that

<script>
SELECT * FROM STUDENT
WHERE DEPARTMENT_ID = #{depId}
<if test='joiningDate != null'>
<![CDATA[
AND STUDENT_ID >= #{joiningDate}
]]>
</if>
</script>


text:
Q: RichTextBox строки Возник такой вопрос. Есть в RichTextBox у меня две строки, и надо при нажатии кнопки добавить в первую строку RichTextBox число. Я сделал по аналогии с TextBox.
richTextBox1.Lines[0] += "1";

Однако действие не выполняется. Для наглядности привожу пример с TextBox.
textBox1.Text += "1";

В чём проблема, что здесь за тонкость?
A: Чтобы добавить текст к richTextBox надо вызывать AppendText("текст"), а вот чтобы изменить конкретную строку - вот тут не знаю, самому интересно.
Полезно читать MSDN (ремарки): Lines по дефолту read-only, для изменения надо делать так:
richTextBox1.Lines = new string[] { "строка1", "строка2" };

A: Тонкость в том, что свойство Lines каждый раз возвращает новый массив строк. Ваш код меняет одну из строк в изменённом массиве, который с исходными данными уже не связан.
По идее, так должно работать:

*

*Сохранить массив в локальную переменную

*Изменить нужную строку в массиве через эту переменную

*Изменённый массив снова присвоить свойству Lines


text:
Q: How to get one value from several identical ones? As an example I have such records in my DB:
product_id
------------------------------------
887349c7-699e-4792-adde-3a44acd2d768
887349c7-699e-4792-adde-3a44acd2d768
887349c7-699e-4792-adde-3a44acd2d768
ecdcf200-6bc0-4b67-b47a-5946a1ab1dcf
ecdcf200-6bc0-4b67-b47a-5946a1ab1dcf
01a5419d-aaf8-4524-99ce-9bf5c1836823
01a5419d-aaf8-4524-99ce-9bf5c1836823

How can I get (using MySQL or Knex.js syntax) every product_id, but only 1, because I have copies (it's okay, this is how it has to be):
product_id
------------------------------------
887349c7-699e-4792-adde-3a44acd2d768
ecdcf200-6bc0-4b67-b47a-5946a1ab1dcf
01a5419d-aaf8-4524-99ce-9bf5c1836823

A: The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
SELECT DISTINCT product_id
FROM YourTable;

A: Another alternative is to group by the column
SELECT column
FROM table
GROUP BY column

If you're getting these duplicates because of a join to a table with multiple rows for this one row, it would be better to use any possibly ways of reducing the amount of data to be joined rather than generating lots of duplicates and then having to dedicate resources to squishing them afterwards
For example if you've got person joined to address, and address keeps a history of everywhere that person has lived, the current address being given by a leave_date that is null (a person has only one active address), it would be better to do:
SELECT person.*
FROM person JOIN address ON ...
WHERE address.leave_date IS NULL

Than do
SELECT DISTINCT person.*
FROM person JOIN address ON ...

In short, your response to "OMG, I'm getting duplicates" shouldn't always be "just ram a distinct in there to get rid of them", it should be "why did they appear and is there a way to eg cut down a 1:M join to 1:1 so they don't appear in the first place?"


text:
Q: Pushing Values Into nested ko.observableArray I want to nest a list of vendors into an existing JSON Payload that I get from the server, based on if the item within the JSON Payload requires a vendor.
What I want to end up with is something that looks like this:
    {
        "ProductName": "Product123",
        "RequiredComponents": "CAP 10% H/Vol",
        "StockCode": "142111411",
        "RequiredQtyByBom": 4,
        "QtyUnassignedInWarehouse": 0,
        "QtyAllocatedInWarehouse": 40,
        "PCBReference": "442C",
        "QtyOnOrder": 26,
        "Vendors": [],
        "RequireVendor": false
    },
    {
        "ProductName": "Product123",
        "RequiredComponents": "Screws",
        "StockCode": "Screws",
        "RequiredQtyByBom": 1,
        "QtyUnassignedInWarehouse": 0,
        "QtyAllocatedInWarehouse": 14,
        "PCBReference": "Screws",
        "QtyOnOrder": 26,
        "Vendors": [
                      {"VendorID": "3",
                      "VendorName": "ABC Supplier",
                      "VendorMOQ": 50000,
                      "VendorItemPrice": 322},
                      {"VendorID": "4",
                      "VendorName": "DEF Supplier",
                      "VendorMOQ": 4,
                      "VendorItemPrice": 120}
                   ],
        "RequireVendor": true
    },
    {
        "ProductName": "Product123",
        "RequiredComponents": "14141415",
        "StockCode": "151555231",
        "RequiredQtyByBom": 1,
        "QtyUnassignedInWarehouse": 0,
        "QtyAllocatedInWarehouse": 170,
        "PCBReference": "1414",
        "QtyOnOrder": 26,
        "Vendors": [],
        "RequireVendor": false
    }

I was thinking of doing this with 2 AJAX call an push the values into the Observable array.
AJAX Call 1: Create The Initial Payload fro Products
 MyDataViewModel.SelectedOrderID.subscribe = ko.computed(function () {
        $.ajax({
            url: "/URLToMethod/GetBomStockByProductID",
            data: { OrderID: ko.toJS(MyDataViewModel.SelectedOrderID) },
            type: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            timeout: 10000,
            success: function (Result) {
                for (var i = 0; i < Result.d.length; i++) {
                    element = Result.d[i];
                    MyDataViewModel.CheckStock.push({
                        ProductName: element.ProductName, RequiredComponents: element.RequiredComponents, StockCode: element.StockCode, RequiredQtyByBom: element.RequiredQtyByBom, QtyUnassignedInWarehouse: element.QtyUnassignedInWarehouse, QtyAllocatedInWarehouse: element.QtyAllocatedInWarehouse, PCBReference: element.PCBReference, QtyOnOrder: element.QtyOnOrder, Vendors: ko.observableArray(), RequireVendor: ko.computed(function () {
                            if ((element.RequiredQtyByBom * element.QtyOnOrder) > element.QtyAllocatedInWarehouse) {
                                return true
                            } else {
                                return false
                            }
                        })
                    }
                    );
                }
            },
            error: function (xhr, status) {
                alert(status + " - " + xhr.responseText);
            }
        });
    });

AJAX Call 2: Push Values into Vendors ko.observableArray() Created in First payload
 MyDataViewModel.PurchaseReqHasVendorDetails = ko.computed(function () {
        var self = MyDataViewModel;
        for (var i = 0; i < self.CheckStock().length; i++) {
            if (self.CheckStock()[i].RequirePO()) {
                $.ajax({
                    url: "/URLToMethod/GetVendorsByProductName",
                    data: { ProductName: self.CheckStock()[i].ProductName },
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    dataType: "JSON",
                    timeout: 10000,
                    success: function (Result) {
                        for (var i = 0; i < Result.d.length; i++) {
                            element = Result.d[i];
                            self.CheckStock()[i].Vendors.push({ VendorID: element.VendorID, VendorName: element.VendorName, VendorMOQ: element.VendorMOQ, VendorPrice: element.VendorPrice });
                        }
                    },
                    error: function (xhr, status) {
                        alert(status + " - " + xhr.responseText);
                    }
                });
                return true;
            } else {
                return false;
            }
        }
    });

But this doesn't work. It creates the initial payload but it does not obtain the second payload and push it into the observableArray that I created.
Any Advice would be greatly appreciated

A: You can use the mapping plugin to do this easily. Suppose you retrieve a slightly different JS from the server (or modify it a bit after you receive it), like this:
var data = {
    [ /* Your example data with products and nested vendors here */ ]
}

Creating the view models can be as simple as:
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);

If you don't want auto-generated view models but use your own ViewModel constructor functions you can use the mapping plugin to add additional "mapping options". The documentation has great examples on that.
Here's a fiddle with a demo that includes your data.


text:
Q: Fancybox prev/next area is too wide look i'm using the gallery function on iframes to show PDF files, but my problem here is the area to tap prev/next is big, how i can modify this space to make it thinner.
I'm using a touch screen and i need modify this area.

A: well i find it looking in css files,
int the file /fancybox/source/jquery.fancybox.css i find this block:
    fancybox-nav {
    position: absolute;
    top: 0;
    width: 5%;
    height: 100%;
    cursor: pointer;
    text-decoration: none;
    background: transparent url('blank.gif'); /* helps IE */
    -webkit-tap-highlight-color: rgba(0,0,0,0);
    z-index: 8040;
}

and modify width property reducing the %


text:
Q: Failed executing gradlew using PHP exec() through browser I want to run gradlew using PHP. What I have tried is using exec(), shell_exec, or passthru. I executed those commands inside a PHP script named "build.php". I tried calling the script from a browser or curl and got this error
Exception in thread "main" java.lang.RuntimeException: java.io.: /var/www/.gradle/wrapper/dists/gradle-2.2.1-all/6dibv5rcnnqlfbq9klf8imrndn/gradle-2.2.1-all.zip.lck (No such file or directory)

However when I called it from command line using php build.php, it worked very well.
So, I need the gradlew command to be executed through user action from browser. My question: what might cause this error and how to get rid of it?
UPDATED
This is what build.php looks like:
<?php

// some sorts of code ...

$alias = 'myalias';
$storepass = 'mypassword';
$keypass = 'mypassword';

$keystore = str_replace('.', '_', $packageName);
$exec = 'keytool -genkey -noprompt -keystore '.$keystore.'.keystore -alias '.$alias.' -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=kahfi, OU=ID, O=yanmii, L=jogja, ST=diy, C=ID" -storepass '.$storepass.' -keypass '.$keypass;
echo $exec;
$output = '';
exec($exec, $output);
print_r($output);

passthru("./gradlew assembleRelease 2>&1");

?>


text:
Q: AppleScript error/no result when clicking FaceTime Accept button in Notification Center Background:
I want to automatically answer incoming FaceTime calls on a dedicated Mac without user interaction. Since the hidden FaceTime defaults write com.Apple.FaceTime AutoAcceptInvites (a boolean) and AutoAcceptInvitesFrom (email or phone or contact card name) no longer work* (and indeed may not have worked in a great many OS versions), I tried a kludgy UI scripting way to accept an incoming FT call. This is on Ventura 13.1.
*I ran strings on the FaceTime binary and didn't see anything promising, but if anyone knows of an easier, defaults-based way of doing this, I'm all ears.
The button I want to click: "Accept"

What I tried:
I got the hierarchy of the Notification Center via Accessibility Inspector:

I then wrote an AppleScript to try to find that button and click it. It errors out with

System Events got an error: Can't get window 1 of application process "NotificationCenter". Invalid index.

if the Notification Center isn't visible. When I place a FT call to the computer and the Notification Center IS visible, it runs, but doesn't do anything, which tells me that the syntax is valid but the logic is wrong.
tell application "System Events"
    tell its application process "NotificationCenter"
        tell its window 1
            --          tell its group 1
            --              tell its scroll area 1
            set btns to its buttons
            repeat with btn in btns
                if name of btn = "accept" then
                    click btn
                end if
            end repeat
            --              end tell
            --          end tell
        end tell
    end tell
end tell

(I commented out the group and scroll area checks here, in the hopes that they weren't necessary. I tried it with them, too, but it also did nothing.
I also tried a much simpler approach:
if button "Accept" of scroll area 1 of group 1 of window 1 of application process "NotificationCenter" exists then click button "Accept" of scroll area 1 of group 1 of window 1 of application process "NotificationCenter"
but that didn't work so I figured it couldn't be that simple.


text:
Q: Set Automatic Proxy Configuration on a per-network basis? My company's Wi-Fi network requires that I use an Automatic Proxy Configuration (setting in the Advanced Network Settings) to access external websites.
However, I don't want to use the proxy when connecting to my home Wi-Fi network.
In the Network settings, I created a Work location which uses the proxy, and a Home location which does not, but this requires that I manually switch my location every time I go to work or go home.
Is there a way to use the automatic proxy whenever I connect to my work network, and not use the automatic proxy on all other networks? Or some other way that does not require manually setting my location twice a day?


text:
Q: Developing spring boot application with lower footprint In an attempt to keep our microservices, developed in spring-boot to run on Cloud Foundry, smaller in footprint, we are looking for best approach to achieve the same.
Any inputs or pointers in this direction will be most welcomed.
It's surely the best that one always builds the application upwards starting from bare minimum dependencies, and the add any more only when required. Is there more of good practices to follow to further keep the application smaller in size?

A: Below are some personal ideas on how to reach a smaller footprint with Spring Boot. Your question is too broad for these recommandations to be taken into account in any other context. I'm not entirely sure you want to follow these in most situation, it simply answers "how to achieve a smaller footprint".
(1) Only specify required dependencies
I wouldn't personally worry about it, but if the goal is to have a smaller footprint, you may avoid using starter-* dependencies. Only specify the dependencies you actually use.
Avoid this:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

In my sample project, the artifact produced with starter-* dependencies is ~25MB

Do this:
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
</dependency>

In my sample project, the artifact produced without starter-* dependencies is ~15MB

(2) Exclude AutoConfigurations
Exclude the AutoConfiguration you don't need:
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

(3) Spring Boot properties
Disable as much as you can in the application.properties (while making sure it does not have a negative impact too):
spring.main.web-environment=false
spring.main.banner-mode=off
spring.jmx.enabled=false
server.error.whitelabel.enabled=false
server.jsp-servlet.registered=false
spring.freemarker.enabled=false
spring.groovy.template.enabled=false
spring.http.multipart.enabled=false
spring.mobile.sitepreference.enabled=false
spring.session.jdbc.initializer.enabled=false
spring.thymeleaf.cache=false
...

(4) Choose your embedded web container wisely
If launching spring boot with an embedded web container, you may choose a different one:

*

*tomcat (by default)

*undertow (https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-undertow)

*jetty (https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jetty)

*...

(5) Spring's recommandations

*

*Memory: java -Xmx32m -Xss256k -jar target/demo-0.0.1-SNAPSHOT.jar

*Number of threads: server.tomcat.max-threads: 4

*source: spring-boot-memory-performance
(6) See also:

*

*How to reduce Spring memory footprint


text:
Q: Cannot get a reference to a dijit form when the form has a DateTextBox I am having trouble getting a reference to the dijit form widget when the form contains a DateTextBox.  The code snippet below demonstrates the problem.  When executed, the alert box says "undefined".  However, if I get rid of <input ... id="dateTextBox"... />, I am able to get a reference to the form widget.
<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dijit/themes/claro/claro.css" media="screen">

        <!-- load dojo and provide config via data attribute -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js"
            data-dojo-config="async: true, parseOnLoad: true">
        </script>
        <script type="text/javascript">
            require(["dijit/form/TextBox", "dijit/form/DateTextBox"]);
        </script>

        <script type="text/javascript">
            require(["dojo/parser", "dijit/registry", "dijit/form/Form", "dojo/domReady!"],
            function(parser, registry) {
                parser.parse();
                alert(registry.byId("frm_test"));
            });
        </script>
    </head>

    <body class="claro">
        <div data-dojo-type="dijit/form/Form" id="frm_test" encType="multipart/form-data" action="" method="">
            <input type="text" id="textBox" name="textBox" data-dojo-type="dijit/form/TextBox" />
            <input type="text" id="dateTextBox" name="dateTextBox" data-dojo-type="dijit/form/DateTextBox" />
        </div>
    </body>
</html>

A: I'd recommend wrapping the registry.byId into a ready call.
Keep parse onLoad: true, remove
require(["dijit/form/TextBox", "dijit/form/DateTextBox"]);

as the parser will auto require (when dojo>= 1.8) and use the following:
<script type="text/javascript">
    require(["dojo/ready", "dijit/registry", "dojo/domReady!"],
        function(ready, registry) {
            // by default the prioirty of this ready call will be after the
            // ready call used to parse when parseOnLoad is true
            ready(function() {
                alert(registry.byId("frm_test"));
            });
    });
</script>

Note that waiting for dojo/domReady! to fire is often not sufficient
  when working with widgets. Many widgets shouldn't be initialized or
  accessed until the following modules load and execute:

*

*dojo/uacss

*dijit/hccss

*dojo/parser

  Thus when working with widgets you should generally put your code
  inside of a dojo/ready() callback

http://dojotoolkit.org/reference-guide/1.9/dojo/domReady.html
http://dojotoolkit.org/reference-guide/1.9/dojo/ready.html#dojo-ready


text:
Q: Solving an equation with a few variables for a maximum value I'm playing a game called Screeps, where you program a colony in javascript. Central to the game are little scriptable units called creeps, which can be dynamically built from different parts to give them different properties.
I've written a system of equations for determining how effective a creep will be at completing a given job by looking at its part composition.
For example, the simplified equation for a job which upgrades the colony center is:
e = 10yx / ((x + y) * (15x + 2y))
x is the number of CARRY parts on the creep.
y is the number of WORK parts on the creep.
e is the total effectiveness of the job allocation
These equations work great for determining which creeps should be given which jobs. However, I was wondering if it there is a way to solve each equation for the maximum value of e? This would give me the most effective ratio of parts to build a creep for a high demand job.
If this is possible, since I am thinking of extending the equations with another variable, say z for the number of MOVE parts, would this still be possible?
Edit: Using trial and error on the aforementioned equation
f(1, 1); // returns 0.294
f(1, 2); // returns 0.350
f(1, 3); // returns 0.357 --- Highest value, therefore best ratio
f(1, 4); // returns 0.347
f(1, 5); // returns 0.333

Can this be solved without using trial and error? If the equation had three inputs instead of 2, would a similar approach work?

A: To find the maximum, we can first calculate the differential, and then look where it is zero.
The maximum of your equation is at x = (sqrt(30) - 2)/13, or x=0.26748, y=0.73252.
Here is some Python code that calculates it:
from sympy import evalf, solve
from sympy.abc import x, y

f = 10*y*x / ((x + y) * (15*x + 2*y))
f = f.subs(y, 1-x)  # we know x + y == 1
df = f.diff(x)
sol = solve([df], x)
print(f'solutions found: {sol}')
for s in sol:
    x0 = s[0].evalf()
    if x0 >= 0 and x0 <= 1:
        print(f'extremum at f({x0, 1-x0}) = {f.subs(x, x0).evalf()}')

Output:
solutions found: [(-2/13 + sqrt(30)/13,), (-sqrt(30)/13 - 2/13,)]
extremum at f((0.267478890388589, 0.732521109611411)) = 0.357724784017555

A: Mathematically speaking the maximum of e occurs when DIF(e,x)=0 and DIF(e,y)=0, where DIF() is the derivative. This occurs only when
2*y^2 = 15*x^2

or
y = sqrt(30)/2*x

Using the above in the expression for e
e = (170 - 20*sqrt(30))/169 = 0.3577247


text:
Q: Sprite not moving with PathModifier using Andengine I am build a live wallpaper and all I would like is for, right now, a simple sprite to move right and that's all. I have no animation for the sprite. The wallpaper loads and I see the sprite but it's just not moving.
I've implemented the PathModifer and 0 errors, I've checked my code to numerous examples and posts and I just cannot figure out why it is not moving.
Here is my entire class:
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.PathModifier;
import org.andengine.entity.modifier.PathModifier.IPathModifierListener;
import org.andengine.entity.modifier.PathModifier.Path;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.ui.livewallpaper.BaseLiveWallpaperService;
import org.andengine.input.sensor.acceleration.AccelerationData;
import org.andengine.input.sensor.acceleration.IAccelerationListener;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.ease.EaseSineInOut;

public class LiveWallpaperService extends BaseLiveWallpaperService implements IAccelerationListener{

//================================================================================
//  Fields
//================================================================================

    private static int CAMERA_WIDTH = 480;
    private static int CAMERA_HEIGHT = 854;

    private Scene mScene;

    private BitmapTextureAtlas grass;
    private ITextureRegion yourTextureRegion;

    private BitmapTextureAtlas house;
    private ITextureRegion houseRegion;

    private BitmapTextureAtlas cloud1;
    private ITextureRegion cloud1Region;

    @Override
    public EngineOptions onCreateEngineOptions() {
      Camera mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
              EngineOptions options = new EngineOptions(true,
                      ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
                              CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
              return options;

     }

    @Override
    public void onCreateResources(
            OnCreateResourcesCallback pOnCreateResourcesCallback)
            throws Exception {
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

        this.grass = new BitmapTextureAtlas(this.getTextureManager(), 1024, 512, TextureOptions.DEFAULT);
        yourTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.grass, this, "bglwp.png", 0, 0);
        this.mEngine.getTextureManager().loadTexture(this.grass);

        this.cloud1 = new BitmapTextureAtlas(this.getTextureManager(), 256, 128, TextureOptions.DEFAULT);
        cloud1Region = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.cloud1, this, "clld1.png", 0, 0);
        this.mEngine.getTextureManager().loadTexture(this.cloud1);

        this.house = new BitmapTextureAtlas(this.getTextureManager(), 512, 512, TextureOptions.DEFAULT);
        houseRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.house, this, "front.png", 0, 0);
        this.mEngine.getTextureManager().loadTexture(this.house);

        pOnCreateResourcesCallback.onCreateResourcesFinished();

    }

    @Override
    public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws Exception {
        final float x = CAMERA_WIDTH / 2 - yourTextureRegion.getWidth() /2;
        final float y = CAMERA_HEIGHT / 2 - yourTextureRegion.getHeight() /2;
        final float xx = CAMERA_WIDTH / 2 - houseRegion.getWidth() /2;
        final float yy = CAMERA_HEIGHT / 2 - houseRegion.getHeight() /2;

         mScene= new Scene();
         mScene.setBackground(new Background(0.3294117f, 0.788235f, 0.909803f));
         Sprite backgroundSprite = new Sprite(x - 80, y + 171, this.yourTextureRegion, getVertexBufferObjectManager());
         mScene.attachChild(backgroundSprite);

         Sprite foregroundSprite = new Sprite(xx + 10, yy + 80, this.houseRegion, getVertexBufferObjectManager());
         mScene.attachChild(foregroundSprite);

         Sprite cloud1Sprite = new Sprite( 100, 100, this.cloud1Region, getVertexBufferObjectManager());

         final Path path = new Path(2).to(200, 200).to(20, 20);

         cloud1Sprite.registerEntityModifier(new LoopEntityModifier(
                 new PathModifier(5, path, null, new IPathModifierListener() {
                @Override
                public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) {
                    Debug.d("onPathStarted");
                }

                @Override
                public void onPathWaypointStarted(PathModifier pPathModifier,
                        IEntity pEntity, int pWaypointIndex) {

                }

                @Override
                public void onPathWaypointFinished(PathModifier pPathModifier,
                        IEntity pEntity, int pWaypointIndex) {

                }

                @Override
                public void onPathFinished(PathModifier pPathModifier,
                        IEntity pEntity) {
                }
                 }, EaseSineInOut.getInstance())));

         mScene.attachChild(cloud1Sprite);
         pOnCreateSceneCallback.onCreateSceneFinished(mScene);
         }

    @Override
    public void onPopulateScene(Scene pScene,
            OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAccelerationAccuracyChanged(AccelerationData pAccelerationData) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAccelerationChanged(AccelerationData pAccelerationData) {
        // TODO Auto-generated method stub

    }
}

Any help anyone has would be most appreciated, thank you.

A: Your code works. It runs on my device. The problem seems to be its moving to little and too slow to easily notice. Try changing your duration from 30 to 5.
new PathModifier(5, path, null, new IPathModifierListener();

I also spaced out the path coordinates more to make the move more noticeable.
 final Path path = new Path(2).to(200, 200).to(0, 0);

Now its clearly moving.
Here is my full class:
package com.example.andenginetestbed;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.color.Color;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.ease.EaseSineInOut;

import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.PathModifier;
import org.andengine.entity.modifier.PathModifier.IPathModifierListener;
import org.andengine.entity.modifier.PathModifier.Path;

import android.os.Bundle;
import android.view.Menu;

public class TestBed extends SimpleBaseGameActivity {

    // ===========================================================
    // Constants
    // ===========================================================

    private static final int CAMERA_WIDTH = 720;
    private static final int CAMERA_HEIGHT = 480;

    // ===========================================================
    // Fields
    // ===========================================================

    private ITexture mTexture;
    private ITextureRegion mFaceTextureRegion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_test_bed);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.test_bed, menu);
        return true;
    }

    @Override
    public EngineOptions onCreateEngineOptions() {
        final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

        return new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
    }

    @Override
    public void onCreateResources() {
        try {
            this.mTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
                @Override
                public InputStream open() throws IOException {
                    return getAssets().open("tank.png");
                }
            });

            this.mTexture.load();
            this.mFaceTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture);
        } catch (IOException e) {
            Debug.e(e);
        }
    }
    ArrayList<Sprite> placedSprites = new ArrayList<Sprite>();
    @Override
    protected Scene onCreateScene() {
        this.mEngine.registerUpdateHandler(new FPSLogger());

        final Scene scene = new Scene();
        scene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f));

        /* Calculate the coordinates for the face, so its centered on the camera. */
        final float centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
        final float centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;

        final Sprite bigTank = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager());
        scene.attachChild(bigTank);

        final Sprite smallTank = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager());
        smallTank.setScaleCenter(smallTank.getWidth()/2, smallTank.getHeight()/2 );
        smallTank.setScale(0.667f);
        smallTank.setRotationCenter(smallTank.getWidthScaled() / 2,
        smallTank.getHeightScaled() / 2);
        smallTank.setRotation(45);
        scene.attachChild(smallTank);

         final Sprite cloud1Sprite = smallTank;

         final Path path = new Path(2).to(200, 200).to(0, 0);

         cloud1Sprite.registerEntityModifier(new LoopEntityModifier(
                 new PathModifier(10, path, new IPathModifierListener() {
                @Override
                public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) {
                    Debug.d("onPathStarted");
                }

                @Override
                public void onPathWaypointStarted(PathModifier pPathModifier,
                        IEntity pEntity, int pWaypointIndex) {

                }

                @Override
                public void onPathWaypointFinished(PathModifier pPathModifier,
                        IEntity pEntity, int pWaypointIndex) {

                }

                @Override
                public void onPathFinished(PathModifier pPathModifier,
                        IEntity pEntity) {
                }
                 }, EaseSineInOut.getInstance())));
        return scene;
    }

}


text:
Q: Node.js - can it be used for Desktop app development - MySQL, DataTable & File Open Since last 3days, I am after this, not sure I understood its purpose properly - Node.js/Electron.
Few years back I had built a simple VB.net application - It connects to Mysql (contains a table of filename with path), shows the filenamesPath as rows in grid, upon double click, it opens the file.
Can I do such a thing in Node.js or Electron?.
1) I am able to make a js file with a button which can open a local file, in Node.js desktop app window (not browser). [https://www.codediesel.com/nodejs/how-to-open-various-desktop-applications-from-nodejs/ ].
2) Also I am able to view mySql table as  html table in browser with localhost:port as well as the rows in console-log window [https://www.sitepoint.com/using-node-mysql-javascript-client/]
Is it possible to club both of these 2, Or Should I try something else. [As the rows are more than 100K, would need also Ajax]
EDITED:
test.html

    <meta http-equiv="Content-Security-Policy" content="script-src 'unsafe-inline';">

Electron MySQL Example

    <input type="button" id="action-btn" value="Retrieve 10 first rows in the database" />

Index.js
const electron = require('electron');
const app = electron.app;

const path = require('path');
const url = require('url');

const BrowserWindow = electron.BrowserWindow;

var mainWindow;
app.on('ready',function(){
  mainWindow = new BrowserWindow({
      width: 1024,
      height: 768,
      webPreferences: {
            nodeIntegration: true
        },
      //backgroundColor: '#2e2c29'
  });
  //mainWindow.loadURL('https://github.com');
   mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'test.html'),
    protocol: 'file:',
    slashes: true
  }));

});

A: You can use Electron to create Desktop app and connect to Mysql database. Here are couple of useful links.
https://ourcodeworld.com/articles/read/259/how-to-connect-to-a-mysql-database-in-electron-framework
https://github.com/techiediaries/electron-mysql-demo
Node JS is primarily used to create REST API, serve web pages from the server. You may create API in Node JS using Express/Restify which interacts with DB and the Electron app can consume this service. It depends on your requirement whether or not you want to have API layer.

A: Sure, you can build desktop Apps nowadays in Node, in fact there is multible options that you can choose from:

*

*Electron

*Meteor

*NWJS

*App JS

*Proton Native
All of these frameworks/technology allow you to write you App in Javascript and run it on Desktop platforms.


text:
Q: Considerations when signing up for a Salesforce trial using Google Authentication? I am signing up for a Salesforce trial, and was surprised to see that one can use a Google login to start the trial:

Before I take this step, I want to understand the consequences. Here are some of my questions/concerns:

*

*Will I only be able to login with Google if I sign-up with a trial using Google authentication?

*Will I get to pick a username (i.e. me@myco.com) or will it be some strange "key" or long auto-generated string?

*If you go to https://login.salesforce.com there is no Login with Google button, so how does one login if you initially login with Google?

A: *

*Will I only be able to login with Google if I sign-up with a trial
using Google authentication?
No, They read only your First Name, Last Name and basic info which is required to fill right section of this signup page using google,facebook.

*Will I get to pick a username (i.e.
me@myco.com) or will it be some strange "key" or long auto-generated
string?
As you know Salesforce username is unique across the org so if your gmail id is not registered with Salesforce they will set that as your username otherwise it will ask you to put unique username.

*If you go to https://login.salesforce.com there is no Login
with Google button, so how does one login if you initially login
with Google?
No you can't, if you want SSO. you need to setup my domain and setup SSO yourself.


text:
Q: Getting raw value of a cell of a selected row in a grid With
console.log(grid.getSelectionModel().getSelection());

I cann see that I have selected a row and there it is all the values of the row under the raw however I was unable to read it.
I have tried
grid.getSelectionModel().getSelection().raw
grid.getSelectionModel().getSelection().raw.EMAIL

etc, didn't work.

A: According to http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-getSelection getSelection() returns array of Ext.data.Model.
So what you need to do is
var sel = grid.getSelectionModel().getSelection(),
    model = sel[0],
    val = model.get('EMAIL');

A: Instead of
grid.getSelectionModel().getSelection()

is
grid.getSelectionModel().getSelections()

So it could be
var sel = grid.getSelectionModel().getSelections();

or
grid.getSelectionModel().getSelections()[0].get('field');

A: {
    xtype: 'gridpanel',
    ....
    listeners: {
        select: function(selModel, record, index, options){
            alert(record.get('EMAIL'));
                }
        }


text:
Q: memory leak in appdelegate in swift language please can fix my problem about memory leak i have got the leak in app delegate and i don't know when and how can i fix it  ?
the following part of my code which  is have leak from instrument which is must i release it from app delegate ?
class AppDelegate: UIResponder, UIApplicationDelegate {
   var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        UIApplication.shared.statusBarStyle = .lightContent
        UITabBar.appearance().tintColor = UIColor.white

        return true
    }

}

thanks a lot


text:
Q: Image is not centered In my footer area I have set a background image. Problem is it is not centered. Only the some part of image is shown. Right end of the image is hidden. If I crop the image, I can handle this. But I want to handle it from css.
Here is the code
#footer{

}

#middle-footer{
    background-image:url('img/footer-bg.gif');
    background-repeat:no-repeat;
    width:100%;
    margin-left:auto;
    margin-right:auto;
    height:inherit;
    overflow:hidden;
}

How to do this?

A: Ok, try this. Instead of using background-image: use the short-hand and after the URL use top center. Code will be:
#footer {
    background: url('img url') top center;
}

A: Resizing the background in CSS is possible only with modern browsers. So, if you would like to do, add this:
background-size: 90%;

The full CSS is:
#middle-footer{
    background-image:url('img/footer-bg.gif');
    background-repeat:no-repeat;
    background-size: 90%;
    width:100%;
    margin-left:auto;
    margin-right:auto;
    height:inherit;
    overflow:hidden;
}

A: The problem is you are mixing a width: 100% with the centering trick of doing margin-left: auto; and margin-right: auto; which won't work since if the width is 100% then the margins will be automatically nothing since the box fills the space.  So I reworked the CSS so it has a fixed width.  I also added a color to the box since we don't have an image to look at for reference but need to see the box. I also moved the inline style for #footer into the CSS since it was weird to see that empty #footer { } in the CSS.  Here is a full HTML example of how it should work.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

    <title>CSS Centering Fixed</title>


text:
Q: Background image not scaling properly on iOS Problem is that background images are not scaling properly on iOS devices, it's a responsive site and at least on desktop browsers it does scale great even on very small resolutions.. But when I test on iPhone/iPad it doesn't seem to be working that way.
The page is http://litoplas.net16.net/como.html (it's an internal presentation for meetings and phorums, it won't be a public link, and my customer wants his representatives to use iPads, which is the reason solving this is very important).
Here's an example of the CSS of a section I'm using with a background image:
.corte {
background: url(../images/corte.jpg) no-repeat center center fixed;
background-size: cover;
padding-bottom: 30%;

}
And as I said, the background images are scaling nicely on desktop browsers...They won't do the same on iOs!
Thanks in advance guys, I spent a lot  of time searching and trying to figure this out, hopefully you'll have some answers for me! :)

A: You need to have the following rule applied for each <section> like so:
background-size: 100% auto;
This fixed the problem for me using an iOS 7 simulator.

A: It appears to be your shorthand rule: background: url(../images/bannercalidad.jpg) no-repeat fixed;
More specifically it is the background-attachment: fixed that is causing the issues.  If I add a new rule of background-attachment: scroll then the image is no longer zoomed way far in to the upper-left corner.  This may not solve all your problems but it will get you on the right path.

A: background-attachment: scroll; worked for me. You should accept @Fernker's answer.


text:
Q: QuickSort - Worst case input example when pivot is in the middle position always What could be a worst case input example for QuickSort if I pick the pivot in the middle position? I am thinking about equals elements like 3,3,3,3 etc. Or could it take it as worst case even if it would be already sorted ?

A: The worst case for quicksort is when the pivot is at either end.  So having them arrive in sorted order is a worst case.
The only case for length 1 is 1 so it is also the worst case.
Otherwise we just increment every value by 1, then insert a 1 into the first pivot.  Giving us 1 as a pivot, and the previous worst case as our next one.
So if we're picking the element at position floor(length/2) as our pivot, here are some worst case inputs generated this way.
1
2 1
3 1 2
4 2 1 3
5 3 1 2 4
6 4 2 1 3 5

And in general for length n it goes
n n-2 n-4 ... (1 2 or 2 1 as appropriate) ... n-5 n-3 n-1

Note that this is not the only worst case.  In fact for each pivot, it can be at either end and still be a worst case.  That means that for n-1 pivots we have a choice to make, making there be 2^(n-1) orderings of 1..n that are equally bad.


text:
Q: Different methods of checking status of one libpq function Is there somebody who can explain to me, why in postgresql libpq there are
different methods of checking, whether an sql command was executed successfully or not (function "PQexec").
If your sql command in "PQexec" was a command returning no data (for instance an insert statement) you have to write
 if (PQresultStatus(res) != PGRES_COMMAND_OK)

and if your sql command in "PQexec" was a command returning data (for instance a fetch statement) you have to write
if (PQresultStatus(res) != PGRES_TUPLES_OK)

Information
http://www.postgresql.org/docs/9.0/static/libpq-exec.html

PGRES_COMMAND_OK: Successful completion of a command returning no data.
PGRES_TUPLES_OK:  Successful completion of a command returning data (such as a SELECT or SHOW).

Why is this?
It would be clearer, if there would be only one method to check the executing status of "PQexec".
Thanks alot in advance


text:
Q: Is there a way to tell if a method is an event or property accessor? That is, how can I, given a MethodInfo check if a method is the getter or setter of a property or the adder or remover or firer (?) of an event, without enumerating all the Property/EventInfos in the containing type. Does the compiler mark these methods with some information that would allow me to know when my MethodInfo is one?

A: This is not a complete solution but on the condition that the property type is not EventHandler, you can tell property get/set methods from event add/remove methods by checking their parameters and return values.
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        foreach (var methodInfo in typeof(TestClass).GetMethods())
        {
            if (!methodInfo.IsSpecialName)
                continue;

            CheckMethod(methodInfo);
        }

        // Method get_Name -> Property Get
        // Method set_Name -> Property Set
        // Method add_NameChanged -> Event Add/Remove
        // Method remove_NameChanged -> Event Add/Remove
    }

    static void CheckMethod(MethodInfo info)
    {
        var parameter = info.GetParameters().FirstOrDefault();
        if (parameter != null)
        {
            if (parameter.ParameterType.BaseType == typeof(MulticastDelegate))
            {
                Trace.WriteLine($"Method {info.Name} -> Event Add/Remove");
            }
            else
            {
                Trace.WriteLine($"Method {info.Name} -> Property Set");
            }
        }
        else if (info.ReturnType != typeof(void))
        {
            Trace.WriteLine($"Method {info.Name} -> Property Get");
        }
    }
}

public class TestClass
{
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value)
                return;

            _name = value;
            NameChanged?.Invoke(this, value);
        }
    }
    private string _name;

    public event EventHandler<string> NameChanged;
}

A: At least one difference between a manually declared method and one that was generated by the compiler is the presence of a SpecialName attribute in its MethodInfo object:
To find out which property the method is linked to you would inspect PropertyInfo objects to find their corresponding GetMethod and SetMethod properties, which would link to those methods.
Example LINQPad program:
void Main()
{
    typeof(Test).GetProperties().Select(property => new { property.MetadataToken, property.Name, getter = property.GetMethod?.MetadataToken, setter = property.SetMethod?.MetadataToken }).Dump();
    typeof(Test).GetMethods().Select(method => new { method.MetadataToken, method.Name, IsSpecial = (method.Attributes & MethodAttributes.SpecialName) != 0 }).Dump();
}

public class Test
{
    public int Value
    {
        get;
        set;
    }
}

Output:

A: MethodInfo.IsSpecialName is set to true for properties and events accessors, also for some other special methods as operators overload and etc. So you can check this flag along with  checking the parameter type. The following test program will output the event add/remove accessors:
public class MyEventClass {
private event EventHandler test;
public event EventHandler TestEven {
  add { test += value; }
  remove { test -= value; }
}

}
class Program {
    static void Main(string[] args)
    {
  Type myTestClassType = typeof (MyEventClass);
  var methods = myTestClassType.GetMethods();
  foreach (var methodInfo in methods)
  {
    if (methodInfo.IsSpecialName)
    {
      var parameters = methodInfo.GetParameters();
      if (parameters.Count() == 1 && parameters.ElementAt(0).ParameterType == typeof (EventHandler) &&
          (methodInfo.Name.Contains("add") || methodInfo.Name.Contains("remove")))
      {
        Console.WriteLine(methodInfo.Name);
      }

    }
  }

}

}


text:
Q: How to feed Labels with Dynamic Lengths to Tensorflow Numpy Input Function I am having problems in adding validation monitors to Estimator.fit. With this code I have:
images = dataset_utils.resize(images, (1596, 48))
images = dataset_utils.transpose(images)
labels = dataset_utils.encode(labels)
x_train, x_test, y_train, y_test = dataset_utils.split(features=images, test_size=0.5, labels=labels)
x_train_seq_lens = dataset_utils.get_seq_lens(x_train)
x_test_seq_lens = dataset_utils.get_seq_lens(x_test)

train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": np.array(x_train),
       "seq_lens": np.array(x_train_seq_lens)},
    y=np.array(y_train),
    num_epochs=1,
    shuffle=True,
    batch_size=1
)

validation_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": np.array(x_test),
       "seq_lens": np.array(x_test_seq_lens)},
    y=np.array(y_test),
    shuffle=True
)

validation_monitor = learn.monitors.ValidationMonitor(
    input_fn=validation_input_fn,
    every_n_steps=1
)

model = GridRNNModelFn(num_time_steps=1596, num_features=48, num_hidden_units=128, num_classes=80,
                       learning_rate=0.001, optimizer=Optimizers.MOMENTUM)

classifier = learn.Estimator(model_fn=model.model_fn, params=model.params, model_dir="/tmp/grid_rnn_ocr_model")
classifier.fit(input_fn=train_input_fn, monitors=[validation_monitor])

It throws this error: ValueError: Labels are incompatible with given information. Given labels: Tensor("random_shuffle_queue_DequeueUpTo:3", shape=(?, 37), dtype=int32), required signatures: TensorSignature(dtype=tf.int32, shape=TensorShape([Dimension(None), Dimension(33)]), is_sparse=False).
I want to figure out a way to feed labels into the input function without having to pad them.
To reproduce this yourself, simply clone this repository, remove this line  and run the script.


text:
Q: How to make matplotlib cycle through qualitative cmap? I'm afraid is isn't a reproducible example but I'll try to clearly explain my problem.
I have some geographic data that has a 'community' label that is a number, although it's just a categorical thing. There are about 100 communities, and it seems the labelling sequence is spatial; ie. consecutive labels are near to each other. I want to visualize the data using one of the qualitative colormaps, eg. 'Paired' (cf. https://matplotlib.org/stable/tutorials/colors/colormaps.html), which only has 12 colors, but as there are never (or at least rarely) more than twelve communities in a small area, that would not be a problem if matplotlib cycled through the colors, so that '01' gets the first color, '02' the second, ...; and only repeating at '13'.
Except instead the default seems to be to squeeze nearby labels together with the same color rather than cycling, so that '01','02','03, ..., have the same color; as do '13', '14', '15'... and so on.
This seems like it should be a simple thing to change, but I seem to lack the proper knowledge of matplotlib's inner workings to work out exactly what to do.
There's similar question here that suggests I just need to do something with set_prop_cycle, but I'm still not getting what I want...

A:  I think just creating a custom colormap by adding the X sets of colors you need will do the trick.
X = math.ceil(N / M), M being the number of colors in your base colormap.
In your example, N = 100, M = 12, X = 9.
Simple application:
cmap = plt.cm.tab20                           # get a specific colormap
cmaplist = cmap.colors                        # extract all colors
cmaplistext = cmaplist + cmaplist             # repeat X times, here X = 2

customMap = matplotlib.colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplistext, N)
plt.imshow(data, customMap)


text:
Q: auto adjustable textview changing height android i have one Textview which text size is auto i am assigning text on API response but its height is changing.
how can i pervert to change its height i set min and max line fix to set fix height but it's not working in some case
<TextView
        android:id="@+id/tvFeedTitle"
        style="@style/komuTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:autoSizeMaxTextSize="@dimen/feed_header_font_max_size"
        android:autoSizeMinTextSize="@dimen/feed_header_font_size"
        android:autoSizeTextType="uniform"
        android:ellipsize="end"
        android:maxLines="3"
        android:minLines="3"
        android:text="Covid News Live Updates: After Pfizer, Serum Institute seeks indemnity over COVID-19 vaccine, says sources"
        android:textColor="@color/white"
        android:textSize="@dimen/feed_header_font_size"
        app:layout_constraintTop_toBottomOf="@+id/imgFeed"
        app:layout_constraintEnd_toEndOf="@id/guideline2"
        app:layout_constraintStart_toStartOf="@id/guideline" />

this is my Textview
1

2

I am showing everything in Recyclerview
Please help me, Any help would be highly appreciated.