text:
Q: SpriteKit Game Center Authentication I am doing a sprite kit Game. I have a problem with Game Center: how i authenticate player?
in AppDelegate.swift i have this code:
     func authenticateLocalPlayer()
     {

     var localPlayer = getLocalPlayer() // see GKLocalPlayerHack.h
    localPlayer.authenticateHandler =
        {(viewController : NSViewController?, error : NSError?) -> Void in
            if viewController != nil
            {
                self.presentViewController(viewController!, animated:true, completion: nil)

                        }

but i get this error:
Value of type 'AppDelegate' has no member 'presentViewController'

on this line:
 self.presentViewController(viewController!, animated:true, completion: nil)

How can i solve this problem?

A: I think you need to use something like this. I am not 100% sure what you set for the parentWindow bit, my OSX knowledge is limited.
let dialogController = GKDialogController.shared()
dialogController.parentWindow = yourWindow // not exactly sure what you need to set here
dialogController.presentViewController(viewController)

Implementing GameKit.framework on OSX, cannot authenticate localPlayer
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/GameKit_Guide/DisplayingGameCenterUserInterfaceElements/DisplayingGameCenterUserInterfaceElements.html
Hope this helps.

A: I suggest to use a viewcontroller ;-)
Take a look at my answer here I won't copy it one to one.
Adding Game Center Leaderboard


text:
Q: Nested Where In in Doctrine2 I want to create this statement in Doctrine 2 :
SELECT Id, ParentId , LastName
  FROM Customer
 WHERE ParentId IN
       (SELECT Id
          FROM Customer
          WHERE ParentId IN $id)
       )

Here is my code :
    public function findByCustomer($id) : array
    {
    $qb = $this->_em->createQueryBuilder();
    $qb1 = $this->_em->createQueryBuilder();

    $qb->select('Customer.Id , Customer.ParentId ,  Customer.LastName ');
    $qb->from('..\City\Model\Entities\Customer', 'Customer');
    $qb->add('where', $qb->expr()->in('Customer.ParentId',

            $qb1->select('Customer.Id');
            $qb1->from('..\City\Model\Entities\Customer', 'Customer');
            $qb1->add('where', $qb->expr()->in('Customer.ParentId', $id)
            $qb1 = $qb1->getQuery();
            return $qb1->getResult();

        )
    );
    $qb = $qb->getQuery();
    return $qb->getResult();
}

But it doesn't work at all . Any suggestion?

A: You can bild a subquery via querybuilder like this:
$subQuery = $this->_em->createQueryBuilder();
$subQuery->select('c1.Id');
$subQuery->from('..\City\Model\Entities\Customer', 'c1');
$subQuery->add('where', $qb->expr()->in('c1.ParentId', $id)

$qb = $this->_em->createQueryBuilder();

$qb->select('Customer.Id , Customer.ParentId ,  Customer.LastName ');
$qb->from('..\City\Model\Entities\Customer', 'Customer');

$qb->andWhere($qb->expr()->in('Customer.ParentId',  $subQuery->getDQL()) );

$query = $qb->getQuery();
return $query->getResult();

Hope this help

A: I have antoher way to execute this query i hope this will help you.
You can use direct sql statement in doctrine2 like this
$sql = "SELECT Id, ParentId , LastName
  FROM Customer
 WHERE ParentId IN
       (SELECT Id
          FROM Customer
          WHERE ParentId IN $id)
       )";
 $data = $this->doctrine->sql_conn->fetchAll($sql , array());

I always use this one to write complicated sql statement in doctrine2. I hope this will help you

redpajama_set_name: RedPajamaStackExchange


text:
Q: Admob Interstitial Ad fails to load I am trying to load AdMob InterstitialAd add when

*

*App opens

*Button is clicked

*back is pressed
Problems

*

*When app opens its shows ad failed to load (in catlog)

*when back is pressed no ad is loaded

*when button is clicked for the 1st time the ad loads but after 1st click, it never loads
public class MainActivity extends AppCompatActivity {
 InterstitialAd mInterstitialAd;
 Button mNewGameButton;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     mNewGameButton = (Button) findViewById(R.id.newgame_button);

     mInterstitialAd = new InterstitialAd(this);
     mInterstitialAd.setAdUnitId("ca-app-pub-5059726881726792/4446999064");
     if (mInterstitialAd.isLoaded()) {
         mInterstitialAd.show();
     } else {
         //Begin Game, continue with app
     }

     mNewGameButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             if (mInterstitialAd.isLoaded()) {
                 mInterstitialAd.show();
             } else {
                 //Begin Game, continue with app
             }
         }
     });

     mInterstitialAd.setAdListener(new AdListener() {
         @Override
         public void onAdClosed() {
             //Begin Game, continue with app
         }
     });

     AdView mAdView = (AdView) findViewById(R.id.adView);
     AdRequest adRequest = new AdRequest.Builder()
         .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All emulators
         .addTestDevice("D016E92D0D3266640328381D0A8BB622")//bluestacks
         .addTestDevice("CE34804F0BB3F1F2F409E6DDFB272C60").build();//s3
     mAdView.loadAd(adRequest);
     mInterstitialAd.loadAd(adRequest);
 }

 @Override
 public void onBackPressed() {
     super.onBackPressed();
     mInterstitialAd = new InterstitialAd(MainActivity.this);
     mInterstitialAd.setAdUnitId("ca-app-pub-5059726881726792/4446999064");
     if (mInterstitialAd.isLoaded()) {
         mInterstitialAd.show();
     }
     AdView mAdView = (AdView) findViewById(R.id.adView);
     AdRequest adRequest = new AdRequest.Builder()
         .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All emulators
         .addTestDevice("D016E92D0D3266640328381D0A8BB622")//bluestacks
         .addTestDevice("CE34804F0BB3F1F2F409E6DDFB272C60").build();//s3
     mAdView.loadAd(adRequest);
     mInterstitialAd.loadAd(adRequest);
 }

}

A: I use this ads in my application and working correctly.
Have a look at below example.
InterstitialAd mInterstitialAd;
    Button mNewGameButton;

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

        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(<your ad unit id goes here>);
        final AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
        adRequestBuilder.addTestDevice("your test device id goes here");
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
            }
            @Override
            public void onAdClosed() {
                super.onAdClosed();
                mInterstitialAd.loadAd(adRequestBuilder.build());
            }
        });
        mInterstitialAd.loadAd(adRequestBuilder.build());

        mNewGameButton = (Button) findViewById(R.id.newgame_button);

        newgame_button.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {

            case R.id.newgame_button:
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }

A:
It always takes little time to load, hope you have imported SDK and manifest declaration(if not check it here). Here is the detail explanation

*

*Declare global variable
private lateinit var mInterstitialAd: InterstitialAd

*initialize the ad in onCreate of your activity
mInterstitialAd = InterstitialAd(this)
mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
mInterstitialAd.loadAd(AdRequest.Builder().build())

*show ad
       if (mInterstitialAd.isLoaded) {
            mInterstitialAd.show()
        } else {
            Log.d("isLoaded", "The interstitial wasn't loaded yet.")
        }

*adListener
mInterstitialAd.adListener = object : AdListener() {
    override fun onAdClosed() {

        //go to second activity or do something
    }

    override fun onAdLoaded() {
        Log.d("zma interstitial", "loaded");
    }

    override fun onAdFailedToLoad(i: Int) {
        Log.w("AgeActivity", "onAdFailedToLoad:" + i)
    }
}


text:
Q: Getting all the records in one single row in SQL Server I am writing a SQL Query to create calculated columns like this: (Simplified version of the code)
SELECT CUST_ID, NAME, ADDRESS,
       CASE WHEN STIP_ID = 20 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL1,
       CASE WHEN STIP_ID = 21 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL2,
       CASE WHEN STIP_ID = 22 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL3,
       CASE WHEN STIP_ID = 23 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL4,
       CASE WHEN STIP_ID = 24 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL5
FROM TABLE1

When I run this query this is how the report looks like. It creates multiple rows where the first condition statisfies for more that one column. How can I get unique records
CUSTID  NAME    ADDRESS Col1    Col2    Col3    Col4    Col5
 101    Nikh    US       X       X       X       X       X
 102    Chris   Canada   Yes     X       X       X       X
 102    Chris   Canada   X       X       Yes     X       X
 103    Todd    Japan    X       X       X       Yes     X
 103    Todd    Japan    X       X       X       X       Yes
 104    Levis   China    X       X       X       X       X
 105    Jack    Germany  X       Yes     X       X       X
 105    Jack    Germany  X       X       Yes     X       X

Desired result:
CUSTID  NAME    ADDRESS Col1    Col2    Col3    Col4    Col5
  101   Nikh    US       X      X       X       X        X
  102   Chris   Canada   Yes    X       Yes     X        X
  103   Todd    Japan    X      X       X       Yes      Yes
  104   Levis   China    X      X       X       X        X
  105   Jack    Germany  X      Yes     Yes     X        X

A: Use MAX:
SELECT  CUST_ID,
        NAME,
        ADDRESS,
        MAX(CASE WHEN STIP_ID = 20 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL1,
        MAX(CASE WHEN STIP_ID = 21 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL2,
        MAX(CASE WHEN STIP_ID = 22 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL3,
        MAX(CASE WHEN STIP_ID = 23 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL4,
        MAX(CASE WHEN STIP_ID = 24 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL5
FROM TABLE1
GROUP BY CUST_ID,
         NAME,
         ADDRESS

A: Solution to the question as posted:
SELECT [CUST_ID],[NAME],[ADDRESS],[20],[21],[22],[23],[24]
FROM TABLE1
CROSS APPLY (SELECT CASE [STATUS] WHEN 'OPEN' THEN 'YES' ELSE 'X' END [YES OR X])
PIVOT(MAX([YES OR X]) FOR [STIP_ID] IN ([20],[21],[22],[23],[24]) ) P

Solution that accommodates the new requirements:
SELECT
  [CUST_ID], [NAME], [ADDRESS],
  ISNULL([20],'X'), ISNULL([21],'X'), ISNULL([22],'X'), ISNULL([23],'X'), ISNULL([24],'X')
FROM TABLE1
CROSS APPLY (CASE WHEN Stips.StipulationID = 90 AND Stips.StatusID IN (39, 41) THEN '('TR10_Pers_FS_Curr_Signed' + '- ' + Prim.PrimaryCust) ELSE 'X' END) AS TR10_Pers_FS_Curr_Signed)
PIVOT(MAX(TR10_Pers_FS_Curr_Signed) FOR [STIP_ID] IN ([20],[21],[22],[23],[24]) ) P


text:
Q: How to deserialize foreignkey with django rest framework? For example
class People(models.Model):
    name = models.CharField(max_length=20)

class Blog(models.Model):
    author = models.ForeignKeyField(People)
    content = models.TextField()

and then,
class CreateBlogSerializer(serializers.Serializer):
    #author id
    author = serializers.IntegerField()
    content = serializers.TextField()

In views, I need to get author_id , check if the id exists and get the author instance, it's fussy to do that.
serializer = CreateBlogSerializer(data=request.DATA)
if serializer.is_valid():
    try:
        author = Author.objects.get(pk=serializer.data["author"])
    except Author.DoesNotExist:
        return Response(data={"author does not exist"})
    blog = Blog.objects.create(author=author, content=serializer.data["content"])

Is there a ForeignKeyField to deserialize and validate primarykey data and then return a instance.
class CreateBlogSerializer(serializers.Serializer):
    author = serializers.ForeignKeyField(Author)
    content = serializers.TextField()

serializer = CreateBlogSerializer(data=request.DATA)
if serializer.is_valid():
    #after deserialization , the author id becomes author model instance
    blog = Blog.objects.create(author=serializer.data["author"], content=serializer.data["content"])
else:
    #the author id does not exist will cause serializer.is_valid=Flase

PS
I knew PrimaryKeyRelatedField in ModelSerializer,but I can't use ModelSerializer here, the model structures are complex, the above are just examples。
My first thought is to write a customer field.

A: class ForeignKeyField(WritableField):

    def __init__(self, model_name, *args, **kwargs):
        super(ForeignKeyField, self).__init__(*args, **kwargs)
        self.model_name = model_name
        self.model_instance = None

    def from_native(self, pk):
        if not isinstance(pk, int):
            raise ValidationError("pk must be int")
        try:
            self.model_instance = self.model_name.objects.get(pk=pk)
            return self.model_instance
        except self.model_name.DoesNotExist:
            raise ValidationError('object does not exist')

    def to_native(self, obj):
        return self.model_instance

I hacked it, but I don't konw why it works.
Usage:
there is a little difference
class t_serializer(serializers.Serializer):
    author = ForeignKeyField(Author)

@api_view(["POST"])
def func(request):
    serializer = t_serializer(data=request.DATA)
    if serializer.is_valid():
        print isinstance(serializer.data["author"], Author)
        #print True
    else:
        print serializer.errors

A: It appears that what you want is custom validation code.
For this particular instance, you could write the following.
class CreateBlogSerializer(serializers.Serializer):
    author = serializers.ForeignKeyField(Author)
    content = serializers.TextField()

    def validate_author(self, attrs, source):
        """
        Verify that the author exists.
        """
        author = attrs[source]
        if Author.objects.filter(pk=author).exists():
            return attrs
        raise serializers.ValidationError("Specified Author does not exist!")

Now when you call serializer.is_valid() this check will occur.
So you can then do this elsewhere in your code,
if serializer.is_valid():
     blog = Blog.objects.create(author=serializer.data["author"], content=serializer.data["content"])

And be sure that if the given blog is created, there is a corresponding Author already in the DB.
Detailed Explanation
So Django Rest Framework provides a method of adding custom validation to serializers. This can be done with by providing methods of the following format in the serializer class validate_<field name>. These methods will set the source value to name of the given field, in our example author, which can then be used with the attrs variable to get the current value of the field (attrs contains all the values passed into the serializer).
These validation methods are each called with then serializer.is_valid() method is called. They are supposed to just return attrs if the given test passes, and raise a ValidationError otherwise.
They can get somewhat complex, so it is probably best if you read the full documentation here, http://www.django-rest-framework.org/api-guide/serializers#validation


text:
Q: Plotting in a for loop: Why can't I subtract from the counter? Why does the following code plot points at 1:10 and not at 0:9 on the x axis?
(I know I can code it differently to solve the problem, nevertheless, I wish to know.)
y <- rep(1,10)

for (i in 1:10) {

          if (i == 1) {
                    plot(y[i]~(i-1),pch = 14,
                         ylim = c(0,2),
                         xlim=c(0,11))
          }
          else {points(y[i]~(i-1), pch = 14)
          }
}

A: You have to use the I() (as-is) formula construct:
y <- rep(1,10)
for (i in 1:10) {
          if (i == 1) {
                    plot(y[i]~I(i-1),pch = 14,
                         ylim = c(0,2),
                         xlim=c(0,11))
          }
          else {points(y[i]~I(i-1), pch = 14)
          }
}

This is (according to ?I) because arithmetic operators ("+", "-", "*" and "^") inside formulae are interpreted as formula operators (for adding/dropping terms or creating interactions) rather than as arithmetic operators.
You could obtain the same by changing your plot calls to: plot(i-1,y[i],...) to get out of formula mode.

A: In formulas, the term -1 is interepreted as "without intercept". Of course, this has no direct effect on your plot and hence is ignored.
Note that the term -1 is a special case. You will receive an error message if you use, for example, -2 in your formula.


text:
Q: How to start versioning a composer package? I'm starting to develop a package that i'd like to open source and use in future projects. I don't understand the proper steps to get this started though.
I've just created the repository on github and here is my composer.json
{
    "name": "ProgrammingAreHard/Arbiter",
    "license": "MIT",
    "type": "library",
    "description": "Convenience library to manipulate Symfony ACL's",
    "authors": [
        {
            "name": "David Adams",
            "email": "adams.david.10@gmail.com"
        }
    ],
    "autoload": {
        "psr-0": {
            "ProgrammingAreHard\\Arbiter": "src/"
        }
    },
    "require": {
        "php": ">=5.3.3"
    },
    "require-dev": {
        "symfony/security": "2.4.*",
        "phpunit/phpunit": "~4.0"
    },
    "minimum-stability": "dev",
    "target-dir": "ProgrammingAreHard/Arbiter",
    "extra": {
        "branch-alias": {
            "dev-master": "1.0.x-dev"
        }
    }
}

I'm having a tough time wrapping my head around versioning though. I haven't made any git tags. I've put the branch-alias on just because i hear that it's a good practice. I'm not sure 1.0.x-dev is what should be there right now.
What should i do at this point? I'm not at a point where i'm comfortable with a 1.0 version. Should i create a lightweight or annotated git tag at something like "v0.1.0" immediately or wait until i'm at a point where it's fully functional?
What should i be doing so that it's not a headache later?
I'm assuming composer uses git tags for versioning(?)

A: In doubt (since you can chose any policy you want), you can refer to semantic versioning 2.0

Major version zero (0.y.z) is for initial development. Anything may change at any time.
The public API should not be considered stable.

As long as your public API can change, stay in 0.x.y.


text:
Q: Is there any way to indent wordwrapping acording to syntax in Vim?
Possible Duplicate:
Smart Wrap in Vim

I want the wordwrapping to fit the 4 space tab width in my html file.
alt text http://img191.imageshack.us/img191/1883/27258431.png
I want the Maecenas nisl quam to follow the identation of the li tag
Is that possible (other than do it manually)?

A: There is a patch for this, but it's been lingering for years and last time I checked did not apply cleanly.  See last entry in http://groups.google.com/group/vim_dev/web/vim-patches
-- I really wish this would get in the mainline.

A: https://superuser.com/questions/72714/vim-line-wrap-with-indent
Essentially you can get closer, but with the built-in functionality you can't make it automatically match the arbitrary < li > level.


text:
Q: How to generate XML with open and close tag for NULL/empty value columns in sql? I am working with SQL XML. I want to generate XML with open and close tag for NULL/empty value columns in sql. Please find below tables and query:
Tables:
emp:
+-------+---------+
| empid | empname |
+-------+---------+
|     1 | Arul    |
|     2 | Ram     |
|     3 | Nivi    |
+-------+---------+

empdetail:
+-------+------------+----------------+
| empid | empaddress |    empemail    |
+-------+------------+----------------+
|     1 | Chennai    | mail1@mail.com |
|     2 | Madurai    | mail2@mail.com |
|     3 | Mumbai     | NULL           |
+-------+------------+----------------+

Sql query:
select A.empid,A.empname,
(select B.empaddress,isnull(B.empemail,'') as empemail from empdetail B where A.empid=B.empid  for xml path('EmployeeDetails'),type)
from emp A
where A.empid=1 for xml path('root')

This query gives expected data like below:
<root>
  <empid>1</empid>
  <empname>Arul</empname>
  <EmployeeDetails>
    <empaddress>Chennai</empaddress>
    <empemail>mail1@mail.com</empemail>
  </EmployeeDetails>
</root>

but this query gives this tag <empemail />  When i move to empid 3:
<root>
  <empid>3</empid>
  <empname>Nivi</empname>
  <EmployeeDetails>
    <empaddress>Mumbai</empaddress>
    <empemail />
  </EmployeeDetails>
</root>

But I want open and close tag even column value is NULL. like below:
<root>
  <empid>3</empid>
  <empname>Nivi</empname>
  <EmployeeDetails>
    <empaddress>Mumbai</empaddress>
    <empemail></empemail>
  </EmployeeDetails>
</root>

A: <empemail /> is the standard way to represent an empty field.
You can replace the value with a space or some other value:
select e.empid, e.empname,
       (select ed.empaddress, coalesce(ed.empemail, ' ') as empemail
         from empdetail ed
         where e.empid = ed.empid
         for xml path('EmployeeDetails'), type
        )
from emp e
where e.empid = 3
for xml path('root')

Here is a db<>fiddle.


text:
Q: Which force:* events must I declare as  I'm confused when to use <aura:dependency resource="force.."> and when not?
If my component is using on of the following system events does it need to be explicitly declared as dependency?

*

*force:closeQuickAction

*force:createRecord

*force:navigateToSObject

*force:showToast

*...

I remember having read that system events are somewhat autodiscovered but in some open source repos (e.g. Strike Components) I found components declaring them explicitly.

A: The system automatically detects a component's dependencies through several mechanism and ensures they're available on the client when it needs them.
<aura:dependency> is for advanced use cases where you need explicit control over prefetching of definitions. Using this effectively requires careful consideration and performance analysis.
I highly recommend not using them until you have a clear data-based need to control definition prefetching.


text:
Q: Menu dropdown in position relative does not shift other items down I am trying to render items in a row, for each there is a custom dropdown menu. I have set the menu to position: relative because it has to be close to its respective item. However, with many items in a row when I open the menu, it shift everything else down. I tried setting position to absolute, but that simply makes the menu float to the bottom of the page. How do I open the menu for each of the items without shifting all the other content down?
Below is the codeSandbox: https://codesandbox.io/s/youthful-bohr-fmvh4?file=/src/App.js


text:
Q: Why does the Tango Point Cloud lose so much accuracy in the Y direction? I am using the Tango Point Cloud to place 3D objects in the world, however over time the accuracy of the point cloud worsens.
When I start the app the point cloud lines up with everything correctly but after maybe 10 seconds of moving the camera around the point cloud mesh is hovering about 1-2 inches above the real world objects. It gets worse until I restart the app. Otherwise, it seems ok in the X and Z directions but it always slowly increases in the Y direction.
I found a similar question but I'm not sure it's an offset issue because it looks correct in the beginning, it just slowly gets worse over time: How to I get more reliable Y position tracking for the Google Tango in Unity?
Also, I tried going back to the Point Cloud example from the Tango github and enabling video overlay so I could compare the point cloud mesh with the real world objects, and it happens there too - the mesh slowly begins to hover above the actual objects.  What is causing this and how do I fix it?

A: I found that this project (another example project from Google) didn't have the problem with the point cloud losing accuracy. After examining for any differences, I noticed that it doesn't have a character controller for the Tango AR camera. So, I removed the character controller from the camera in both my project and the Point Cloud example from the Tango github and this does fix the problem of bad Y accuracy. (You have to completely remove it from the camera, just un-checking it in the Unity editor doesn't fix it.)


text:
Q: Finding the primitive of function This problems are kind of simple but I don't know how to approach them.So I know the following things
$$ 1)F'(x)=1/x $$for every real x\0 $$ F(-1)=1$$ $$F(1)=0 $$ $$F(e)+F(-e)=?$$
F'(x) is f(x) so I know that my function is f(x)=1/x so I also know that F(x)=lnx.From $$F(1)=0$$ I find that $$c=0$$ but what about F(-1)? I can't have ln(-1),what am I doing wrong?
Another similar problem is $$f(x)=e^{x^2}$$ and $$F(-1)=0$$

A: As the domain of $\frac{1}{x}$ (i.e. $\mathbb{R}\setminus \{0\}$) has two parts (connected components, technically) this means that the integration constants can be different on both components:
$F(x) = \ln(x) + C_1$ for $x > 0$ and $F(x) = \ln(-x) + C_2$ for $x <0$.
$F(-1) = 1$ implies $\ln(1)+ C_2 = 1 \text{ so } C_2 = 1$.
$F(1) = 0$ implies $\ln(1) + C_1 = 0$ so $C_1 =0$.
Now $F(e) + F(-e) = (\ln(e) + C_1) + (\ln(e) + C_2) = 3$.
As to the second problem, all I could think of was: if $F$ is the primitive of $e^{x^2}$ and $F(-1) =0$ we know $$F(x) = F(x) - F(-1) =\int_{-1}^x e^{x^2}dx$$
So $$F(1) = \int_{-1}^{1} e^{x^2} dx = 2\int_0^1 e^{x^2} dx$$
which is at least strictly positive.. and Wolfram alpha tells us it's$> 2$ in fact (maybe using a lower bound function with computable primitive would tell us the same thing)


text:
Q: Compute gradient and hessian with the python package numdifftools when parameters are bounded I have minimized a log likelihood function using scipy.minimize and I want to compute the standard-errors associated to the parameters.
In cases in which parameters are not bounded, using numdifftools (nd.Gradient and nd.Hessian) works perfectly. I have issues when the parameters are bounded because nd.Gradient tries to compute the function with values of parameters out of bounds where the function is not defined.
My guess is that I should use the options relative to step (step_max, step_nom, etc.) but I do not understand how they work. Can anyone help me understand how to use them?
Thanks


text:
Q: Cannot add the value in the table Here I am trying to add the values of proId and userId in the table whose values I am getting through post method from my android app and I have also checked it by assigning a value 5 directly to the variable (which I have commented out in the table ) but it is still adding 0 in the table.
The problem here is that it is not adding the value of userId in the table instead its adding only 0 there.
I have checked in the android code , the value being passed there is fine.
I think something is wrong in the php code.
Kindly share the solution.
Here I have attached my php file and the MySQL table.
<?php
$pro= $_POST['proId'];
$user = $_POST['userId'];
//$user = 5;
include "config.php";

$check_sql = "SELECT * FROM `savedProducts` WHERE `proId` = '{$pro}' AND `userId` =
'{$user}'";
$result_check =mysqli_query($conn,$check_sql) or die("result failed");

if(mysqli_num_rows($result_check)>0){
echo "Added already";
}else{
$sql="INSERT INTO `$db`.`savedProducts` (`proId`,`userId`)
VALUES ('{$pro}','{$user}')";
$result=mysqli_query($conn,$sql) or die("result failed");
echo "Added successfully";
}
?>

A: As explained in my comments, you have to use more security checks in your code. Typically, you cannot take $_POST input values and concatenate them into your SQL query string. This will lead the user to be able to do nasty SQL injections and break your app or steal some user's data.

*

*Check the user's session to see if he is allowed to do the operation.

*Filter your user's input values and throw errors if they are missing or invalid.

*Use prepared statements with PDO instead of building your SQL strings yourself.
You may also have some problems in your Android app. To help debugging, you could install a proxy such as HTTP toolkit or mitmproxy and configure your smartphone to use it. This way you'll be able to see all the requests between your app and your PHP backend.
Put your config in your config.php file, create some utility functions in another include/tools.php file and add a session handling to check that the user is allowed to do the DB query or not. Typically, the user id should probably be taken directly from the current user, that you already have in the session. There's no need to send the user id via the POST request except if an admin can save products for another user.
But assuming you transfert the user id, here would be a solution where you don't just print a string to return but where you return a JSON object to your mobile app. This way you can handle more easily what has happened. I also decided that the HTTP response code would be set to something else than the 200 (for ok) in case of error. Typically a 400 error for a bad request if your Android app doesn't send valid POST parameters but a 500 error if we are having some MySQL connection errors to say that the problem is on the server side and not the client side.
This would be an example of code (without the session handling):
<?php

// Config comming from "config.php";
define('DB_NAME', 'test');
define('DB_USER', 'sdfsadf');
define('DB_PSWD', 'test');
define('DB_DSN', 'mysql:host=localhost;dbname=' . DB_NAME . ';charset=utf8mb4');
define('DB_PDO_OPTIONS', [
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// Error codes:
define('ERROR_MISSING_PARAM', 1);
define('ERROR_WRONG_PARAM', 2);
define('ERROR_DATABASE_CONNECTION', 3);
define('ERROR_DATABASE_QUERY', 4);

/******************************** FUNCTIONS **********************************/

/**
 * Return a response to the mobile app. You can pass an object or any type of
 * variable to the mobile app. It will be converted to JSON.
 * If you are returning an error then you have to set a non-zero code value and
 * a description for the error.
 *
 * @param mixed $response A PHP object/value to return in JSON to the mobile app.
 * @param integer $error_code The app error code to return. Defaults to 0 => no error.
 * @param string $error_description An optional error description.
 * @param int $http_error_code If $error_code is not 0 then what HTTP error code to return.
 * @return void
 */
function return_json_response($response, $error_code = 0, $error_description = '', $http_error_code = 400)
{
    if ($error_code > 0) {
        http_response_code($http_error_code);
    }
    header('Content-Type: application/json; charset=utf-8');
    $data = (object)[
        'response' => $response,
        'error_code' => $error_code,
        'error_description' => $error_description,
    ];
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;
}

/*************************** PROGRAM STARTS HERE *****************************/

// Check the product id parameter and stop if it's missing or invalid.
if (!isset($_POST['proId'])) {
    return_json_response(false, ERROR_MISSING_PARAM, 'Missing "proId" POST parameter');
} elseif (!is_numeric($_POST['proId'])) {
    return_json_response(false, ERROR_WRONG_PARAM, 'Invalid "proId" value! It should be numeric.');
}
$product_id = intval($_POST['proId']);

// Check the user id parameter and stop if it's missing or invalid.
// If the user id can be taken from the session then I would not use
// this parameter since it could be changed by the client to make a big
// mess in the products of other users. If needed, keep it for admins
// by adding more security controls.
if (!isset($_POST['userId'])) {
    return_json_response(false, ERROR_MISSING_PARAM, 'Missing "userId" POST parameter');
} elseif (!is_numeric($_POST['userId'])) {
    return_json_response(false, ERROR_WRONG_PARAM, 'Invalid "userId" value! It should be numeric.');
}
$user_id = intval($_POST['userId']);

try {
    $pdo = new PDO(DB_DSN, DB_USER, DB_PSWD, DB_PDO_OPTIONS);
} catch (PDOException $e) {
    error_log($e->getMessage());
    return_json_response(false, ERROR_DATABASE_CONNECTION, 'Could not connect to the database.', 500);
}

try {
    // See if the product is already saved for this user.
    $search_query = "SELECT * FROM `savedProducts` WHERE " .
                    "`proId` = :proId AND `userId` = :userId";
    $statement = $pdo->prepare($search_query);
    $statement->execute([
        ':proId' => $product_id,
        ':userId' => $user_id,
    ]);
    if ($statement->rowCount()) {
        return_json_response([
            'ok' => true,
            'affected_rows' => 0,
            'already_saved' => true
        ]);
    }

    // Insert the saved product for the given user.
    $insert_query = "INSERT INTO `savedProducts` (`proId`, `userId`) VALUES (:proId, :userId)";
    $statement = $pdo->prepare($insert_query);
    $statement->execute([
        ':proId' => $product_id,
        ':userId' => $user_id,
    ]);
    if ($statement->rowCount() === 1) {
        return_json_response([
            'ok' => true,
            'affected_rows' => $statement->rowCount(),
            'already_saved' => false
        ]);
    } else {
        return_json_response(false, ERROR_DATABASE_QUERY, 'Did NOT manage to save the product.', 500);
    }
    echo $statement->rowCount();
} catch (PDOException $e) {
    error_log($e->getMessage());
    return_json_response(false, ERROR_DATABASE_QUERY, 'SQL query error.', 500);
}

HTTP 200 response if the product was already saved:
{
    "response": {
        "ok": true,
        "affected_rows": 0,
        "already_saved": true
    },
    "error_code": 0,
    "error_description": ""
}

HTTP 200 response if the product wasn't saved before and was added correctly:
{
    "response": {
        "ok": true,
        "affected_rows": 1,
        "already_saved": false
    },
    "error_code": 0,
    "error_description": ""
}

HTTP 400 response if the "proId" POST param is missing:
{
    "response": false,
    "error_code": 1,
    "error_description": "Missing \"proId\" POST parameter"
}

HTTP 500 response if we didn't manage to connect to the DB:
{
    "response": false,
    "error_code": 3,
    "error_description": "Could not connect to the database."
}

A: Maybe work this:
$sql="INSERT INTO `savedProducts` (`proId`, `userId`) VALUES ('" . $pro . "', '" . $user . "')";


text:
Q: How to call AppRegistry.registerComponent with some delay I need to read some user settings before App initialize. This settings will update the style of the app.
I called AppRegistry.registerComponent with some delayed but app crashed. Have found this issue on https://github.com/facebook/react-native/issues/17724 but nothing helps.

A: I found answer
AppRegistry.registerComponent("App", () => App);
AppRegistry.registerRunnable(appName, initParams => {
    setTimeout(
        () => AppRegistry.runApplication("App", initParams),
        5000
    );
});


text:
Q: Packed BCD 4 digit addition (8086 assembler) Im having trouble writing this code. Could someone give me the solution (I understand BCD numbers, etc, I just can't write code that works)?
It's supposed to add two packed BCD numbers (4 digits each; they are at addresses OP1 and OP2) and place the result in address RES.
Thanks in advance :)

A: Using daa (decimal adjust after addition), you can simply add them directly, without a round trip through binary integers.
Something like this (completely untested)
mov al, [OP1]
add al, [OP2]
daa
mov [RES], al
mov al, [OP1 + 1]
adc al, [OP2 + 1]
daa
mov [RES + 1], al

A: I will not give you a solution, but instead some guidance. You need to split your work into 5 simple stages:

*

*Read the BCD encoded numbers

*Decode them to integers in the memory

*Perform addition

*Encode the addition result back to BCD representation

*Store the result in RES

I think that each stage is relatively easy to implement and hope this will help you to solve it by yourself.


text:
Q: OpenGL ES2.0 offscreen context for FBO rendering I would like to do offscreen rendering (in console environment without any WS) with FBOs.
I know that it is necessary to create an OpenGL context, and at least a dummy window for any operation, therefore I did the following initialization:
// Step 1 - Get the default display.
eglDisplay = eglGetDisplay((EGLNativeDisplayType)0);

// Step 2 - Initialize EGL.
EGLint iMajorVersion, iMinorVersion;
if (!eglInitialize(eglDisplay, &iMajorVersion, &iMinorVersion))
{
    printf("Error: eglInitialize() failed.\n");
    goto cleanup;
}

// Step 3 - Make OpenGL ES the current API.
eglBindAPI(EGL_OPENGL_ES_API);
if (!TestEGLError("eglBindAPI"))
{
    goto cleanup;
}

// Step 4 - Specify the required configuration attributes.
EGLint pi32ConfigAttribs[5];
pi32ConfigAttribs[0] = EGL_SURFACE_TYPE;
pi32ConfigAttribs[1] = EGL_WINDOW_BIT;
pi32ConfigAttribs[2] = EGL_RENDERABLE_TYPE;
pi32ConfigAttribs[3] = EGL_OPENGL_ES2_BIT;
pi32ConfigAttribs[4] = EGL_NONE;

// Step 5 - Find a config that matches all requirements.
int iConfigs;
if (!eglChooseConfig(eglDisplay, pi32ConfigAttribs, &eglConfig, 1, &iConfigs) || (iConfigs != 1))
{
    printf("Error: eglChooseConfig() failed.\n");
    goto cleanup;
}

// Step 6 - Create a surface to draw to.
EGLSurface eglSurface;
eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, (EGLNativeWindowType)NULL, NULL);
if (!TestEGLError("eglCreateWindowSurface")) goto cleanup;

// Step 7 - Create a context.
eglContext = eglCreateContext(eglDisplay, eglConfig, NULL, ai32ContextAttribs);
if (!TestEGLError("eglCreateContext")) goto cleanup;

// Step 8 - Bind the context to the current thread
eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
if (!TestEGLError("eglMakeCurrent")) goto cleanup;

This type of initialization works on the target system, but if I draw something into the FBO, and after read it back (getReadPixels) always only get a black image.
I have tried the same code above X11, where it (already) fails on eglCreateWindowSurface call with error: EGL_BAD_NATIVE_WINDOW WORKS, BUT it WORKS if I pass to this call a real X11window native window handler (This case I can read back the valid rendered image also)
Please clarify me about what type of surface should I need to use for FBO rendering??
or what do I do wrong??
The rest of the drawing code:
    //init and start opengl es shanders
    Shaders_Init();
{
    // create a framebuffer object
    glGenFramebuffers(1, &fboId);
    glBindFramebuffer(GL_FRAMEBUFFER, fboId);

    // create a texture object
    GLuint textureId;
    glGenTextures(1, &textureId);
    glBindTexture(GL_TEXTURE_2D, textureId);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //GL_LINEAR_MIPMAP_LINEAR
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_HINT, GL_TRUE); // automatic mipmap
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, renderBufferWidth, renderBufferHeight, 0,
                    GL_RGB, GL_UNSIGNED_BYTE, 0);
    //glBindTexture(GL_TEXTURE_2D, 0);

    // attach the texture to FBO color attachment point
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D, textureId, 0);

    // check FBO status
    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(status != GL_FRAMEBUFFER_COMPLETE) {
        printf("Problem with OpenGL framebuffer after specifying color render buffer: \n%x\n", status);
    } else {
        printf("FBO creation succedded\n");
    }
}

// Sets the clear color.
// The colours are passed per channel (red,green,blue,alpha) as float values from 0.0 to 1.0
glClearColor(0.6f, 0.8f, 1.0f, 1.0f); // clear blue

// We're going to draw a triangle to the screen so create a vertex buffer object for our triangle
{
    // Interleaved vertex data
    GLfloat afVertices[] = {    -0.4f,-0.4f,0.0f, // Position
                            0.4f ,-0.4f,0.0f,
                            0.0f ,0.4f ,0.0f};
    // Generate the vertex buffer object (VBO)
    glGenBuffers(1, &ui32Vbo);

    // Bind the VBO so we can fill it with data
    glBindBuffer(GL_ARRAY_BUFFER, ui32Vbo);

    // Set the buffer's data
    unsigned int uiSize = 3 * (sizeof(GLfloat) * 3); // Calc afVertices size (3 vertices * stride (3 GLfloats per vertex))
    glBufferData(GL_ARRAY_BUFFER, uiSize, afVertices, GL_STATIC_DRAW);
}

// Draw a triangle
{
    glClear(GL_COLOR_BUFFER_BIT);
    if (!TestEGLError("glClear")) goto cleanup;

    // First gets the location of that variable in the shader using its name
    int i32Location = glGetUniformLocation(uiProgramObject, "myPMVMatrix");

    // Then passes the matrix to that variable
    glUniformMatrix4fv( i32Location, 1, GL_FALSE, pfIdentity);

    /*
        Enable the custom vertex attribute at index VERTEX_ARRAY.
        We previously binded that index to the variable in our shader "vec4 MyVertex;"
    */
    glEnableVertexAttribArray(VERTEX_ARRAY);

    // Sets the vertex data to this attribute index
    glVertexAttribPointer(VERTEX_ARRAY, 3, GL_FLOAT, GL_FALSE, 0, 0);

    /*
        Draws a non-indexed triangle array from the pointers previously given.
        This function allows the use of other primitive types : triangle strips, lines, ...
        For indexed geometry, use the function glDrawElements() with an index list.
    */
    glDrawArrays(GL_TRIANGLES, 0, 3);
    if (!TestEGLError("glDrawArrays")) goto cleanup;

        // get the image data
        long imageSize = x * y * 3;
        unsigned char *data = new unsigned char[imageSize];
        glReadPixels(0,0,x,y,GL_RGB,GL_UNSIGNED_BYTE,data);

THANKS in advance!!!!!
Regards,
Geza

A: The solution was the following (without error handling):
    #ifdef CONTEXT_ES20
    EGLint ai32ContextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2,
                                                           EGL_NONE };
    #endif

// Step 1 - Get the default display.
    eglDisplay = eglGetDisplay((EGLNativeDisplayType)0);

// Step 2 - Initialize EGL.
    eglInitialize(eglDisplay, 0, 0);

    #ifdef CONTEXT_ES20
// Step 3 - Make OpenGL ES the current API.
    eglBindAPI(EGL_OPENGL_ES_API);

// Step 4 - Specify the required configuration attributes.
    EGLint pi32ConfigAttribs[5];
    pi32ConfigAttribs[0] = EGL_SURFACE_TYPE;
    pi32ConfigAttribs[1] = EGL_WINDOW_BIT;
    pi32ConfigAttribs[2] = EGL_RENDERABLE_TYPE;
    pi32ConfigAttribs[3] = EGL_OPENGL_ES2_BIT;
    pi32ConfigAttribs[4] = EGL_NONE;
    #else
    EGLint pi32ConfigAttribs[3];
    pi32ConfigAttribs[0] = EGL_SURFACE_TYPE;
    pi32ConfigAttribs[1] = EGL_WINDOW_BIT;
    pi32ConfigAttribs[2] = EGL_NONE;
    #endif

// Step 5 - Find a config that matches all requirements.
    int iConfigs;
    eglChooseConfig(eglDisplay, pi32ConfigAttribs, &eglConfig, 1,
                                                          &iConfigs);

    if (iConfigs != 1) {
        printf("Error: eglChooseConfig(): config not found.\n");
        exit(-1);
    }

// Step 6 - Create a surface to draw to.
    EGLSurface eglSurface;
    eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig,
                                        (EGLNativeWindowType)NULL, NULL);

// Step 7 - Create a context.
    #ifdef CONTEXT_ES20
    eglContext = eglCreateContext(eglDisplay, eglConfig, NULL,
                                                     ai32ContextAttribs);
    #else
    eglContext = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
    #endif

// Step 8 - Bind the context to the current thread
    eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);


text:
Q: Create "Init" and "End" SIGNAL for module in VHDL library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
entity struture_test is
        Port ( clk : in STD_LOGIC;
               rst : in STD_LOGIC;
               Init  : in STD_LOGIC;
               i_ia : in STD_LOGIC_VECTOR (11 downto 0);
               i_ib : in STD_LOGIC_VECTOR (11 downto 0);
               end_s : out  std_logic;
               result : out STD_LOGIC_VECTOR (11 downto 0));
end struture_test;

architecture Behavioral of struture_test is
    signal en_sn : std_logic := '0';
begin
PROCESS (clk,rst)
    variable acc : signed (23 downto 0) ;
    variable x   : signed (35 downto 0) ;
begin
    if (rst = '0') then
        result <= (others => '0');
        end_s  <= '0';
    elsif (rising_edge (clk)) then

        if ((Init) = '1') then
            acc := signed (i_ia)*signed (i_ib);
            x   := acc * signed (i_ia);

            result <= std_logic_vector (x(23 downto 12));
            end_s  <= '1';
         else
            end_s  <= '0';
         end if;
    end if;
end process;

end Behavioral;

Hi everyone
I have a project which includes some blocks. The blocks link each other through Init or End Signal. It means that The End signal of one Block is connected to Init signal of the following block.
I'm confused about that Does the above code make a good Init and a End signal ?
If I change my code and convert it into Pipelined structure to operate with the higher frequency clock. The variables convert into the signals
PROCESS (clk,rst)
    signal acc : signed (23 downto 0) ;
    signal x   : signed (35 downto 0) ;
begin
    if (rst = '0') then
        result <= (others => '0');
        end_s  <= '0';
    elsif (rising_edge (clk)) then

        if ((Init) = '1') then
            acc <= signed (i_ia)*signed (i_ib);
            x   <= acc * signed (i_ia);

            result <= std_logic_vector (x(23 downto 12));
            end_s  <= '1';
         else
            end_s  <= '0';
         end if;
    end if;
end process;

How to create Init and End signal in this case? The block illustrates in the picture

A: The idea is good, but the code is wrong. In addition it has some bad coding smells.
Basic rules:

*

*Do not use asynchronous resets.

*You can not declare signals in processes. Process allow variable declarations; architectures allow signal declarations.

*Each signal assignment in a clock process creates a flip-flop / delay of one clock cycle. So it's 3 clock cycles delay in total, but you end signal is only delayed by one cycle.

*Do not enable pipelined operations. Use a delayed chain of valid bits.

*Do not reset pipeline results, because underlying hardware resources like DSP (multiplication) units do not support resets.

Changed code:
library IEEE;
use     IEEE.std_logic_1164.all;
use     IEEE.numeric_std.all;

entity struture_test is
  port (
    clk    : in  std_logic;
    rst    : in  std_logic;
    Init   : in  std_logic;
    i_ia   : in  std_logic_vector(11 downto 0);
    i_ib   : in  std_logic_vector(11 downto 0);
    end_s  : out std_logic;
    result : out std_logic_vector(11 downto 0)    := (others => '0');
  );
end entity;

architecture rtl of struture_test is
  signal ValidChain : std_logic_value(2 downto 0) := (others => '0');
  signal ia_delayed : signed(i_ia'range)          := (others => '0');
  signal acc        : signed(23 downto 0)         := (others => '0');
  signal x          : signed(35 downto 0)         := (others => '0');
begin
  process(clk)
  begin
    if rising_edge(clk) then
      ValidChain <= ValidChain(ValidChain'high - 1 downto ValidChain'low) & Init;

      acc        <= signed(i_ia) * signed(i_ib);
      ia_delayed <= signed(i_ia);
      x          <= acc * ia_delayed;
      result     <= std_logic_vector(x(23 downto 12));
    end if;
  end process;

  end_s <= ValidChain(ValidChain'high);
end architecture;

Please note: Signal i_ia used in the 2nd multiplication needs to be delayed by one cycle, otherwise you would mix ia values from different pipeline cycles.


text:
Q: What steps should I take to determine the value category of an expression? I'm rather confused about determiming the value category of an expression. Could you please provide the basic steps that should be taken (what should be analysed) to determing the value category of an expression?

A: If you just want a quick and usually correct answer, consider these rules of thumb:

*

*If it's a function or an already existing object, then it's a glvalue.

*

*Most glvalues are lvalues.

*xvalues are the things that can specifically be moved from: casts to an rvalue reference type, or a function call where the function return type is an rvalue reference type (especially std::move and sometimes std::forward).

*If it's just a value or a way of creating a new object, then it's a prvalue.

But there are some cases where the category could still be unclear.  And the above involves some simplifications (in particular, the rules for A.B and A ? B : C are more complicated).
The only really reliable way is to look for your answer in the Standard.

*

*Determine what sort of expression you have in terms of the grammar. A literal? An operator expression? A lambda? Etc.

*If the expression is an operator expression, figure out if overload resolution will select some overloaded operator function or a built-in candidate operator, as described in [over.match.oper], [over.oper], and [over.built].

*If the expression is actually a call to an overloaded operator function, the value category is determined from the return type of the operator function selected by overload resolution, as described in [expr.call].  In this case, ignore the description of built-in operator behavior for this purpose.

*Otherwise, find the section of [expr.prim] or [expr.compound] (see the table of contents) for the grammatical form of the expression.  That section will state how the value category of the expression is determined.  It will often be necessary to know the types and value categories of any subexpressions, so you may need to follow these rules recursively.


text:
Q: Google Play Games Services 2017: How to invite somebody to a multiplayer match? Google announced in December 2016 that Google+ is no longer integrated in Google Play Games Services: https://android-developers.googleblog.com/2016/12/games-authentication-adopting-google.html And as a result, a call of Unities Social.localUser.LoadFriends() method returns zero friends.
Now with no friends available, how do you invite other players to a multiplayer match using Googles Play Games Services?

A: In the Google Play Game Services documentation, there is a code example on how to invite G+ friends and anonymous players at this link: https://developers.google.com/games/services/android/realtimeMultiplayer#invite_players_option, btw this is a deprecated example and is not reflecting the actual changes to the APIs.
Update August 2017
Currently RealTimeMultiplayer.getSelectOpponentsIntent(...) and a lot other methods are marked as deprecated in the docs too. (They weren't when this answer was posted). Read here for more info about this


text:
Q: React Native: Key Value array or hasmap? I would like to create an array/collection/hasmap in my react native app where a key is linked to a value. Cause I am coming from PHP I will give you a short example of what I mean. In PHP you simply create an array with key/value pair like this:
$array = array(
    41 => "bar",
    65 => "foo",
);

This is what I want to have too in my react native map. A key linking to a value. Right now I am doing it like this:
var votes = [];

responseJson.map((product, key) => {
  var productID = product.id;
  votes.push({
    productID: product.votes
  });
});

console.log("Votes:", votes);

However, what I get at the end is this:
0: {productID: "0"}
1: {productID: "1"}
2: {productID: "2"}
3: {productID: "0"}
4: {productID: "8"}
5: {productID: "4"}

First of all, the productID variable gets printed as name and not as the value.. First error... And second of all I want to have something like this:
312: "0"
521: "1"
741: "2"
633: "0"
653: "8"
873: "4"

You guys have any idea of how I can do this?
Kind regards and thank you!

A: In javascript you can use object as a method to store key-value pairs.
If you want to define keys using variables you should do something like this
votes.push({
  [productID]: product.votes
});

You can achieve what you want by doing something similar to this -
var votes = {};

responseJson.forEach((product, key) => {
   var productID = product.id;
   votes[productID] = product.votes
});

console.log("Votes:", votes);

Hope it help.

A: You can use the bracket notation for it.
Example:
var votes = [];

responseJson.map((product, key) => {
   var productID = product.id;
   votes.push({
    [productID]: product.votes
 });
});

console.log("Votes:", votes);


text:
Q: How much Volt battery is Required for powering 2 12V + 5V Rpi? I am very noob to Electronics, I am planning to make a Robot, I have 2 12 V motors, 1 RPi and 1 Ultrasonic sensor
I am very confused on how to calculate the power for Motors as it is 12 V and Pi can't power them up?
Also can you please help suggest which battery should i use, Lipo or Alakyne Battery Cells?
For Pi - I will power it with my Mobile Power bank.
Motor Module which i am planning to use https://www.electronicscomp.com/l298n-dual-h-bridge-dc-stepper-motor-driver-controller-module

A: The motor will operate over a fairly wide voltage range, but speed is proportional to voltage. The linked motor specification chart is based on 12 volts, so that would be the best choice to try. The chart lists no-load current at 60 ma and maximum load current at 300 mA. There is no indication if the maximum is a momentary current or a continuous current. 300 mA at 12 volts is 3.6 W. The mechanical power of 2 kg-cm at 200 RPM is 4.1 W. I suspect that is more than the motor can do continuously.
Alkaline AA cells have a lifetime of 1 to 2 amp-hours when discharged at 0.5 amps. That would mean 2 to 4 hours lifetime.
You should probably measure the motor current while it is driving the actual load that you intend to drive with whatever batteries or other power source is most convenient. Then make a final decision based on expected ongoing use details.


text:
Q: Probability notation  Hey guys, I was just wondering why in my textbook(A First Course in Probability, 8th edition) and basically everywhere I've looked at when we have some random variable(assume for the sake of the following example that it is discrete) denoted by $X$ and we want to write down the expression for the probability of $X$ assuming the value of $k$ we do it as follows:
$$P\{X=k\} = ...$$
 and not as
$$P(X=K)=...$$
Why the curly brackets? Does it have anything to do with sets or is it just convention? The same question applies to expected values - why $E[X]$ and not $E(X)$  although variance is usually denoted as $Var(X)$ ?

A: It is just a matter of preference. For the expected value some authors even use $\mathbb E X$ without any brackets at all. Note that $P(X=k)$ is actually short-hand for $P(\{X=k\})$, i.e. it is the probability of the event $\{X=k\}$ happening. So the notation $P\{X=k\}$ is probably emphasizing this without any additional brackets.

A: For the expectation $\mathbb{E}[\cdot]$, as I understand it this gets square braces because it is an operator (... so totally arbitrary, but...). Expectation is more basic than the variance, since the variance is actually a function involving the expectation of random variables $Var(X)=\mathbb{E}[g(X)] = \mathbb{E}[(X - \mathbb{E}X)^2]$. Seeing variance as a function, and thus having round braces made me happier at least.

A: Note that an event (e.g., $\{X = k\}$) is, by definition, a (measurable) set, hence the use of the curly brackets. The notation for the measure (probability) of a measurable set (event) may come with or without the parentheses by convention when there is no confusion (i.e., $\mu E$ is the same as $\mu(E)$). So people write both $P\{X=k\}$ and $P(\{X=k\})$.
The use of square brackets with the expectation operator $\mathbb{E}$ is a more specific convention I think. Most operators are not often seen used with square brackets.


text:
Q: Prettify a one-line JSON file I downloaded a 203775480 bytes (~200 MiB, exact size is important for a later error) JSON file which has all entries all on one line. Needless to say, my text editor (ViM) cannot efficiently navigate in it and I'm not able to understand anything from it. I'd like to prettify it. I tried to use cat file.json | jq '.', jq '.' file.json, cat file.json | python -m json.tool but none worked. The former two commands print nothing on stdout while the latter says Expecting object: line 1 column 203775480 (char 203775479).
I guess it's broken somewhere near the end, but of course I cannot understand where as I cannot even navigate it.
Have you got some other idea for prettifying it? (I've also tried gg=G in ViM: it did not work).

A: I found that the file was indeed broken: I accidentally noticed a ']' at the beginning of the file so I struggled to go to the end of the file and added a ']' at the end (it took me maybe 5 minutes).
Then I've rerun cat file.json | python -m json.tool and it worked like a charm.


text:
Q: Stripe API redirectToCheckout not redirecting to the correct url in Next.js In Next.js the Stripe redirectToCheckout function is sending the checkout page to a url that fails, but the json response data is full and the url is correct (works if I try it manually). Stripe is not sending the checkout to the session.url for some reason.
How can we have the redirectToCheckout redirect to the session.url?
I'm currently using this...
await stripe.redirectToCheckout({ sessionId: id });

I've tried what the Stripe docs suggest...
res.redirect(303, session.url);

But that gives a CORS error - CORS request external redirect not allowed.
Any ideas?

A: I solved my problem by explicitly telling Next.js the names of the stripe API keys in the next.config.js file.
next.config.js
   env: {
     stripe_public_key_test: process.env.stripe_public_key_test,
     stripe_secret_key_test: process.env.stripe_secret_key_test,
     stripe_webhook_endpoint_secret: process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET,
      },

Restart the app after editing the next.config.js file
I ended up using await stripe.redirectToCheckout({ sessionId: id });


text:
Q: Calculating minutes difference I'm trying to find users that opened their email that they got during 10 minutes from where a user got the email, however, for me it shows every user, not just users   that opened their email that they got 10 minutes from where a user got an email.
Code that I tried to use
SELECT s.id_user as "users opened emails during 10 minutes" FROM emails_clicks as c
JOIN  emails_sent as s
WHERE TIMESTAMPDIFF(MINUTE, s.date_sent, c.date_click) < 10
GROUP BY s.id_user

Data:
`emails_sent` - table of sent emails:
a. `id` - a unique id of the sent letter
b. `id_user` - the user to whom the letter was sent. (FK) -> `users`.`id`
c. `id_type` - email type
d. `date_sent` - date and time of sending the letter

`emails_clicks` - table of clicks on emails:
a. `id` - a unique id click on the letter
b. `id_email` is not a unique click email id . (Foreign Key) -> `emails_sent`.`id`
c. `date_click` - date and time of the click on the letter

A: Your join is not actually joining your tables. There is no relationship there. If it was me, I would use
SELECT c.id, s.is_user "users opened emails during 10 minutes"
FROM email_clicks c
JOIN emails_sent s on c.id_email = s.id
WHERE TIMESTAMPDIFF(MINUTE, s.date_sent, c.date_click) < 10
GROUP BY c.id

(if I understand your naming convention correctly...


text:
Q: Generating variations of a json object, internal values, based on another value "state" I need to generate a json, similar to:
'alpha' : {
  "impro": 10,
  "axdo": 20,
  "sendo": 14
}
'beta' : {
  "tero": 90,
  "dote": 10,
  "sendo": 14
}

The values, for secondary keys ("impro") are having, 3 states: normal, warning, danger.
states = ['normal', 'warning', 'danger']

I'm thinking on using classes:
 class Alpha:
   def __init__(self):
     keys = ['impro', 'axdo', 'sendo']
     state = random.choice(states)
     for k,v in keys.iteritems():
        setattr(self, k, generate_value(state=state))

generate_value is a function that generate a value, based on the state that was passed.
I need to create enough random, Alpha objects, to be sure, that each secondary key, was in all 3 states.

A: I hope I understood the question correctly. Every value of object Alpha is chosen from values that belong to three intervals (normal, warning, danger). I use product to generate all combinations:
import random
from itertools import product, cycle
import json

class Alpha:
    keys = ['impro', 'axdo', 'sendto']
    values = {'normal':(0, 100), 'warning':(200, 300), 'danger': (400, 500)}

    def __init__(self):
        pass

    def __repr__(self):
        return 'Alpha(impro={},axdo={},sendto={})'.format(self.impro, self.axdo, self.sendto)

class MyEncoder(json.JSONEncoder):
        def default(self, o):
            return o.__dict__

def generate_objects(cls):
    for p in zip(cycle([cls.keys]), product(cls.values.keys(), repeat=len(cls.keys))):
        c = cls()
        for k, v in zip(*p):
            rand_val = random.randint(*cls.values[v])
            setattr(c, k, rand_val)
        yield c

for alpha in generate_objects(Alpha):
    print(json.dumps({'alpha': alpha}, cls=MyEncoder, indent=4))

Prints:
{
    "alpha": {
        "impro": 42,
        "axdo": 24,
        "sendto": 96
    }
}
{
    "alpha": {
        "impro": 75,
        "axdo": 57,
        "sendto": 210
    }
}
{
    "alpha": {
        "impro": 11,
        "axdo": 62,
        "sendto": 478
    }
}

... and so on.


text:
Q: Connect to Google Talk using smack I want to develop a Java application which connects to Google Talk  and allows a user to chat with it's friends. I am using smack API and the fallowing code:
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com",5222,"gmail.com");
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
XMPPConnection connection  = new XMPPConnection(config);
try {
    connection.connect();
} catch (XMPPException e) {
    e.printStackTrace();
}
try {
    connection.login("username", "password");
} catch (XMPPException e) {
    e.printStackTrace();
}

but I obtain the fallowing exception:
SASL authentication PLAIN failed: invalid-authzid:
    at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:337)
    at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
    at org.jivesoftware.smack.Connection.login(Connection.java:348)
    at Main.main(Main.java:21)

Can someone help me to solve this problem?

A: This should do the trick, quite simple
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

 public class SenderTest
{
public static void main(String args[])
{
    //ConnectionConfiguration connConfig = new ConnectionConfiguration("localhost", 5222);
        //connConfig.setSASLAuthenticationEnabled(false);
     //ConnectionConfiguration connConfig = new ConnectionConfiguration("localhost", 5222);
     ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
       XMPPConnection connection = new XMPPConnection(connConfig);

        try {
            connection.connect();
            System.out.println("Connected to " + connection.getHost());
        } catch (XMPPException ex) {
            //ex.printStackTrace();
            System.out.println("Failed to connect to " + connection.getHost());
            System.exit(1);
        }
        try {
            connection.login("sender@example.com", "a");
            System.out.println("Logged in as " + connection.getUser());

            Presence presence = new Presence(Presence.Type.available);
            connection.sendPacket(presence);

        } catch (XMPPException ex) {
            //ex.printStackTrace();
            System.out.println("Failed to log in as " + connection.getUser());
            System.exit(1);
        }

    ChatManager chatmanager = connection.getChatManager();
    Chat newChat = chatmanager.createChat("receiver@gmail.com", new MessageListener() {
        public void processMessage(Chat chat, Message message) {
            System.out.println("Received message: " + message);
        }
    });

    try {
        newChat.sendMessage("Howdy!");
        System.out.println("Message Sent...");
    }
    catch (XMPPException e) {
        System.out.println("Error Delivering block");
    }
}

}

A: This is the method I used to connect to google talk using smack.
 private ConnectionStatus status;
 private XMPPConnection xmppConnection;

public void connect(String server, int port, String s) throws Exception
{
xmppConnection = new XMPPConnection(new ConnectionConfiguration(server, port,s));
xmppConnection.connect();
xmppConnection.addConnectionListener(this);
xmppConnection.getChatManager().addChatListener(this);
}

and the authentication.
public void authenticate(String username, String password) throws Exception
{
  xmppConnection.login(username, password);
buddyList.setSession(xmppConnection);
setStatus(ConnectionStatus.AUTHENITCATED);
}

A: This saved my day
connectionConfig = new ConnectionConfiguration(host, port, service);
connectionConfig.setSASLAuthenticationEnabled(false);
connectionConfig.setTruststoreType("BKS");
connection = new XMPPConnection(connectionConfig);


text:
Q: Python numpy array filter I got the following  numpy array named 'data'. It consists of 15118 rows and 2 columns. The first column mostly consist of 0.01 steps, but sometimes there is a step in between (shown in red) which I would like to remove/filter out.
I achieved this with the following code:
# Create array [0, 0.01 .... 140], rounded 2 decimals to prevent floating point error
b = np.round(np.arange(0,140.01,0.01),2)

# New empty data array
new_data = np.empty(shape=[0, 2])

# Loop over values to remove/filter out data
for x in b:
    Index = np.where(x == data[:,0])[0][0]
    new_data = np.vstack([new_data,data[Index]])

I feel like this code is far from optimal and I was wondering if anyone knows a faster/better way of achieving this?

A: Here's a solution using pandas for resampling, you can probably achieve the same result in pure numpy but there are a number of floating point and rounding error pitfalls you are going to face, maybe it's better to let a trusted library do the work for you.
Let's say arr is your data array and assume your index to be in fractions of seconds. You can convert your array to a dataframe with a timedelta index:
df = pd.DataFrame(arr[:,1], index=arr[:,0])
df.index = pd.to_timedelta(df.index, unit="s")

Than resampling it's pretty easy, 10ms is the frequency you want, first() should give you the expected result dropping everything but the records at 10ms ticks, but feel free to experiment with other functions
df = df.resample("10ms").first()

Eventually you could get back to your array with something like:
np.vstack([pd.to_numeric(df.index, downcast="float").values / 1e9,
           df.values.squeeze()]).T


text:
Q: "TypeError: only length-1 arrays can be converted to Python scalars" error when printing array values in a loop I don't understand why I get the error "only length-1 arrays can be converted to Python scalars" when I try to run this code. I though this error only occurred when you don't have a numpy array, but I do.
Please help!

A: You're trying to print out lists, when you actually want to print floats. I believe you're looking for:
print("x: %5.2f y: %5.4f" %(x_list[i], y_list[i]))

A: Your print line is trying to cast the entire list of values of x_list and y_list to floats. Instead, you should print each element individually.
Your last line should be:
print("x: %5.2f y: %5.4f" %(x_list[i], y_list[i]))


text:
Q: Reading CSV file based to the condition My csv file is like this
Despription,Car, Deminsion,,
length,5677,
height,3797,
width,6883,
Engine,,
cc,2000,
power,65,
Break,,
rear,disc,
front,disc,

I want extract rows between Deminsion and engine and put them in to a variable,and rows between Engine and Break to another variable.
I have been trying it with python csv.
Can anyone figure a way out?

A: You need to implement that logic, program won't be able to do it via configurational attributes. Implement the circle with bag-functions
# Pattern identification list
store = {'Deminsion': [], 'Engine': []}
# Default / initial pattern
target = 'Deminsion'

with open('data1.txt') as csvFile:
# Create a list of parameters
dataList = [line.split() for line in csvFile]
# Process the list
for i,x in enumerate(dataList):
    if i == 0:
        continue
    x=x.split()
    if x[0] in store:
        target = x[0]
    else:
        store[target].append(x)


text:
Q: How to fix the counting of strings to include the duplicate entries I'm having problems figuring out how to get the total count of email addresses there are. The code I have written only comes up with the non-duplicate addresses, where the assignment is asking for the total number including the duplicates.
I've tried the for loop, and just setting count to the len() function and got the same result. I reread the materials and I am completely stumped as to how to include the duplicate entries.
fname = input("Enter file name: ")
if len(fname) == 0:
    fname = "mbox-short.txt"
fh = open(fname)
for line in fh:
    line = line.rstrip()
    if not line.startswith('From '):
        continue
    words = line.split()
    print(words[1])
count = len(words[1])
print("There were", count, "lines in the file with From as the first word")

Expected result: There were 27 lines in the file with From as the first word
Actual Result: There were 14 lines in the file with From as the first word

A: Increment a counter variable in the loop that's reading from the file.
count = 0
for line in fh:
    line = line.rstrip()
    if line.startswith('From '):
        words = line.split()
        print(words[1])
        count += 1
print("There were", count, "lines in the file with From as the first word")


text:
Q: Performing an atomic swap in solidity with a disposable smart-contract I want to perform an atomic token swap without a pre-deployed smart-contract and I am wondering how to do that in Solidity.
The most common approach to do atomic swaps between tokenA and tokenB is the P2-SC-2P (Peer-to-Smart-contract-to-Peer) approach:

*

*deploy a token swap smart-contract

*alice deposits tokenA in the smart-contract

*bob deposits tokenB in the smart-contract and receives tokenA in exchange

I want to get rid of step 1 to have a truly P2P mechanism. The main idea would be that Alice signs a transactions that transfers X tokenA to the person propagating the transaction, only if that person transfers Y tokenB to Alice in return.
Is it even possible to implement something like this?
Technically speaking, my first thought was to have Alice sign a transaction that deploys a smart-contract would take care of making the atomic swap between the signer and the caller before self-destructing.
I am not a good Solidity dev (to say the least) so here is the pseudo Solidity code I had in mind that could perform the atomic swap without requiring a pre-deployed smart-contract:
contract AtomicSwap {
   sellerSignedApprovalTx = "<RawSignedTxData>"

   constructor() public {
      buyer = caller
      seller = verifySignature(sellerSignedApprovalTx)
      TokenB.approve(buyer,sellerSignedApprovalTx.askPrice)
      delegateCall(sellerSignedApprovalTx.data)
      safeTransferFrom(TokenB,buyer,seller,sellerSignerApprovalTx.askPrice)
      safeTransferFrom(TokenA,seller,buyer,sellerSignerApprovalTx.tokenAmount)
      selfdestruct()
   }
}

As you can see, the idea is that the smart-contract has only 1 use: it performs the swap and then self-destructs (hence the notion of "disposable" smart-contract).
What do you think? Is this even technically possible?
If yes, would it work a bit like my pseudo code or am I completely off?

A: I got the answer to my question via another channel: it's not recommendable to use this technique because the seller needs to sign the transaction for execution without knowing the contract address which will be executing the trade. So it would be like writing a blank check and comes with many security issues.


text:
Q: p:SelectOneMenu default value in edit mode I'm using primefaces and have a datatable that has 2 columns. One column is outputtext another one is selectOneMenu. I made editable selectOneMenu. Actually it's work but not properly. Default value of selectItem is shown null but ı want it to show first value as default value. How can I make it?
    <p:dataTable id="cellEditingTable" var="message"
    value="#{messageTableController.menuList}" paginator="true"
    paginatorPosition="bottom" editable="true" editMode="cell">
        <p:column>
            <p:selectOneMenu id="menu" value="#{messageTableController.selected}"
                style="width:96%" effect="fold" editable="true">
                <f:selectItem itemLabel="#{message.assign}"
                    itemValue="#{message.assign}" />
                <f:selectItem itemLabel="#{message.combo}"
                    itemValue="#{message.combo}" />
            </p:selectOneMenu>
        </p:column>
    </p:dataTable>

I change selectOneMenu's value to first ItemValue. So when run the program,  first ItemValue picked selected item as a default.
    <p:selectOneMenu id="menu" value="#{message.assign}"
        style="width:97%" editable="true">
        <f:selectItem itemLabel="#{message.assign}"
            itemValue="#{message.assign}" />
        <f:selectItem itemLabel="#{message.combo}"
            itemValue="#{message.combo}" />
    </p:selectOneMenu>

A: Add noSelectionOption to the first selectItem
<f:selectItem itemLabel="#{message.assign}"
                    itemValue="#{message.assign}" noSelectionOption="true" />

A: May be late to answer this.
If you use editable="true" then while rendering in the browse, it will render as textbox.
Remove the editable="true" then the default value will be selected.
If you want to provide the filter option in the selectOneMenu, use filter="true"
<p:selectOneMenu id="menu" value="#{message.assign}"
    style="width:97%" filter="true">
    <f:selectItem itemLabel="#{message.assign}"
        itemValue="#{message.assign}" />
    <f:selectItem itemLabel="#{message.combo}"
        itemValue="#{message.combo}" />
</p:selectOneMenu>

Based on the editable property, it will render in browser as below.


text:
Q: Android searchView with voice icon In an android app, I want to implement a searchView like this

There are some requirements:

*

*the SearchIcon and the text("搜索")are in the middle of the searchView

*a voiceIcon is inside the right side of the searchview.
3.the searchView is expanded by default.
I try to use the android searchView component, but i can't move the searchIcon to the middle of the searchView and I dont konw how to add an voiceIcon.
How can I do this,Thanks.

A: If you chose to follow the use of a SearchView, you will come accross the creation of a searchable item in XML.
To get the microphone logo, you can add this line to your searchable
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"

This will enable the voice module, and also add the microphone icon to your searchView if you follow the Android tutorial you can find here
http://developer.android.com/guide/topics/search/search-dialog.html

A: I know that I shuold use custom layout to do this, so I write like this:
 <LinearLayout
                    android:orientation="horizontal"
                    android:background="@color/orange_yellow"
                    android:gravity="center"
                    android:layout_width="match_parent"
                    android:layout_height="50dp">
                    <RelativeLayout
                        android:id="@+id/homeSearchView"
                        android:background="@color/white"
                        android:layout_marginLeft="10dp"
                        android:layout_width="match_parent"
                        android:layout_weight="5"
                        android:gravity="center_horizontal"
                        android:layout_height="wrap_content">
                        <LinearLayout
                            android:orientation="horizontal"
                            android:gravity="center"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_toLeftOf="@+id/voiceSearchIconImageView"
                            android:layout_toStartOf="@+id/voiceSearchIconImageView">

                            <ImageView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:background="@drawable/ic_action_search"
                                android:id="@+id/searchIconImageView" />

                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:gravity="center"
                                android:text="@string/search"
                                android:id="@+id/textView" />
                        </LinearLayout>

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:background="@drawable/ic_action_voice"
                            android:id="@+id/voiceSearchIconImageView"
                            android:layout_alignParentTop="true"
                            android:layout_alignParentRight="true"
                            android:layout_alignParentEnd="true" />

                    </RelativeLayout>

                    <ImageButton
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="10dp"
                        android:background="@drawable/ic_action_scan"
                        android:id="@+id/scanImageButton" />
</LinearLayout>

and it seems work

the next step is to implement the search logic like SearchView component.

A: you can also replace the mic icon with your custom icon
 by adding this to ur search_view in xml
app:voiceIcon="@drawable/ic_mic


text:
Q: MSI install powershell program but no modules available I installed AutomatedLab.msi from here - https://github.com/AutomatedLab/AutomatedLab/releases
it installed without any errors but there doesn't appear to be any powershell modules available... or it doesn't seem to know where the modules are?  Is there anything else that I can do...
PS C:\Users\Administrator\Downloads> Get-LabAvailableOperatingSystem -Path C:\LabSources

Get-LabAvailableOperatingSystem : The term 'Get-LabAvailableOperatingSystem' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-LabAvailableOperatingSystem -Path C:\LabSources
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-LabAvailableOperatingSystem:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Is there some special way I'm supposed to install msi executables?  Ive tried  'start-process' I've tried "Install-Module MSI" I can't seem to get anything to work.
Any suggestions?


text:
Q: $n$-th root of a complex number I am confused about the following problem. With $w=se^{i{\phi}}$, where $s\ge 0$ and $\phi \in \mathbb{R}$, solve the equation $z^n=w$ in $\mathbb{C}$ where $n$ is a natural number. How many solutions are there?
Now my approach is simply taking the $n$-th root which gives
$$z=\sqrt[n]{s}e^{\frac{i\varphi}{n}}$$
However, it seems that this problem is asking us to show the existance of the $n$-th root. Can I assume that the $n$-th root of a complex number already exists? Moreoover, would I be correct to say that there is only one solution which is given above?


text:
Q: Get latest transaction details from loanhist I have a loan history table which contain all the loans a customer borrowed and repayed. There are two status(on the same row) that indicate loan borrow and loan repay: LD = loan disburse while LP = Loan Paid.
My problem is this, I am trying to find:

*

*outstanding balance(sum(principal+interest) in LD - sum(principal+interest) in LP)

*Installment amount(sum(principal+interest)) in LD

*SUM of all LD i.e principal + interest as loan amount

*Last repayment date i.e in LP

*Amount paid(principal+interest) in LP

Table structure

This is my solution so far:
for LP
$amtdues = "select h.ac_no, loan_amt, MAX(trx_date) AS Last_Pay, MAX(principal+interest) as Last_Paid,  disb_date, exp_date,  principal+interest as loan_interest, MAX(principal-interest) as outstanding_balance, trx_date as payment_date from loanhist h, loans l where h.ac_no = '$id' and l.ac_no = '$id' and trx_type = 'LP' group by trx_date, loan_amt, disb_date, exp_date, h.ac_no, interest, principal, trx_date ";

$amts = sqlsrv_query($conn, $amtdues);

$lp = sqlsrv_fetch_array($amts, SQLSRV_FETCH_ASSOC);

For LD
$amtdues2 = "select h.ac_no, loan_amt, MAX(trx_date) AS Last_Pay, disb_date, exp_date,  principal+interest as loan_interest, MAX(interest+principal) as outstanding_balance, MAX(interest+principal) as installment, trx_date as payment_date from loanhist h, loans l where h.ac_no = '$id' and l.ac_no = '$id' and trx_type = 'LD' group by trx_date, loan_amt, disb_date, exp_date, h.ac_no, interest, principal, trx_date ";

$amts2 = sqlsrv_query($conn, $amtdues2);
$ld = sqlsrv_fetch_array($amts2, SQLSRV_FETCH_ASSOC);

My output in html
<?php echo parseCurrency(abs($lmts['loan_limit']));?>
 <?php echo parseCurrency(abs($ld['loan_interest']));?>
 <?php echo parseCurrency(abs($ld['outstanding_balance'] - $lp['outstanding_balance']));?>
 <?php echo parseCurrency(abs($ld['installment']));?>

After I tried these queries, I got incorrect values. Could someone pls help a sister out?

A: Based on the table information for loanhist and making some assumption about what's in loans (and that there is a 1:many relationship from loans to loanhist), I think this query will start you off in the right direction.
SELECT l.ac_no,
       l.loan_amt,
       l.disb_date,
       l.exp_date,
       SUM(CASE WHEN trx_type='LD' THEN h.principal+h.interest ELSE 0 END) -
         SUM(CASE WHEN trx_type='LP' THEN h.principal+h.interest ELSE 0 END) AS outstanding_balance,
       MAX(CASE WHEN trx_type='LD' THEN h.principal+h.interest ELSE 0 END) AS instalment_amount,
       SUM(CASE WHEN trx_type='LD' THEN h.principal+h.interest ELSE 0 END) AS loan_amount,
       MAX(CASE WHEN trx_type='LP' THEN trx_date ELSE NULL END) AS last_payment_date,
       SUM(CASE WHEN trx_type='LP' THEN h.principal+h.interest ELSE 0 END) AS amount_paid
FROM loans l
JOIN loanhist h
ON h.ac_no = l.ac_no
WHERE l.ac_no = '$id'
GROUP BY l.ac_no, l.loan_amt, l.disb_date, l.exp_date


text:
Q: Refactoring: How to replace function call with function code What I'm trying to achieve is like Code -> Refactor -> Extract -> Method functionality of PhpStorm but vice versa.
I want to take some particular function calls and replace it with the code of that functions.
For example I have:
function main()
{
    $test = "test";
    module1($test);
    module2($test);
}

function module1($text)
{
    echo "Some text:" . $text;
}

function module2($text)
{
    echo "Another text:" . $text;
}

Then I want to receive next result:
function main()
{
    $test = "test";
    echo "Some text:" . $test;
    echo "Another text:" . $test;
}

I don't need full recursion, like if module1() function contain another function call - I don't need to go deep inside of it. Just let it be on level 1.
It also doesn't matter for me how to do it, with PhpStorm, another IDE or with another script.

A: Use Refactor | Inline... in PhpStorm (invoke it on a function/method definition).
<?php
function aa($hello)
{
    return "Hello $hello";
}

echo aa('Yo!');

Final result for that simple code:
<?php

echo "Hello 'Yo!'";

As you may see it's a bit incorrect (the single quotes around the variable content), so make sure to check your code afterwards.

Final result for your code sample (after using it on each function):


text:
Q: How to check if a file exists in javascript? I'm using the jquery library to load the content of an html file. Something like this:
$("#Main").load("login.html")
If the file (in this case 'login.html') does not exist, I would like to detect it so that I can redirect the user to an error page for example. Any ideas how I can detect if the file to load exists or not?

A: You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.
More Info in the docs http://docs.jquery.com/Ajax/ajaxComplete#callback
Test here http://pastebin.me/48f32a74927bb
e.g
$("#someDivId").ajaxComplete(function(request, settings){
    if (settings.status===404){
        //redirect here
    }
});

A: @PConroy's solution works, but it does the same thing for all failed ajax requests.
If you need this on a per request basis - i.e. if the first request fails it goes to X page and if the second fails go to Y, then you need to do this using the error handle in the $.ajax function:
http://jsbin.com/iwume
(to edit: http://jsbin.com/iwume/edit)


text:
Q: Resource ids in R.java increase according to alphabetical order of resources - can I rely on it? I have 26 wav files corresponding to letters of the alphabet in my raw folder. These are "a.wav", "b.wav" ... to "z.wav". When I build the project the SDK assigns ids in R.java like so:
public static final class raw {
        public static final int a=0x7f040000;
        public static final int b=0x7f040001;
        public static final int c=0x7f040002;
        public static final int d=0x7f040003;
    .... etc
        public static final int z=0x7f040019;

In practice, can I rely on Eclipse and Ant builds to assign the values in alphabetical order, increasing by one each time?

A:
In practice, can I rely on Eclipse and Ant builds to assign the values in alphabetical order, increasing by one each time?

No. There are no documented rules for how they are generated, and so it can change at any point.

but it would save me about 140 switch/case or if statements by the time I'm finished.

The suggestion by harism is the correct one: maintain your own static array of the IDs.


text:
Q: return the first word from square bracket using regex I have a file which contain
[[ abstraction, verb.cognition:abstract,+ ]]

I want to remove the square bracket and want to keep the word abstraction from this bracket. So the output should be -
abstraction

I have tried -
import re

with open('test.txt','r') as f:
    for line in f:
        rx = re.compile(r'\[[^][]*]')  string
        while rx.search(line):
            line = rx.sub('',line)
            s = line.strip()
            print(s)

which shows [] only square bracket.Is there ay way to do this? please help .

A: using re.search
Ex:
s = "[[ abstraction, verb.cognition:abstract,+ ]]"
m = re.search("\[\[(.*?)\,.*", s)
if m:
    print(m.group(1))

Output:
 abstraction

A: You don't even need to worry about the brackets, if your file only contains that, you only need to match the first word.
import re
t = "[[ abstraction, verb.cognition:abstract,+ ]] "

match = re.search(r"\b([^,]+)\b", t)
# prints False when no match is found
print(match is not None and match.group(0))
# abstraction

A: You can try this too,
line="""[[ abstraction, verb.cognition:abstract,+ ]] rewq [[ abs, verb.cognition:abstract,+ ]] fdsaf [[ abstraction, verb.cfdsa,+ ]] """
rx = re.compile(r'\[\[[^][]*]]')
line = rx.sub(lambda m: '' if m.group(0).find("abstraction")== -1 else "abstraction", line)
s = line.strip()
print(s)

Output is
abstraction rewq  fdsaf abstraction


text:
Q: combine two 2-dimensional arrays to produce a 3-dimensional array Consider the arrays x and y
x <- structure(1:4, .Dim = c(2L, 2L), .Dimnames = structure(list(A = c("a",
"b"), B = c("c", "d")), .Names = c("A", "B")))
y <- structure(5:8, .Dim = c(2L, 2L), .Dimnames = structure(list(A = c("a",
"b"), B = c("c", "d")), .Names = c("A", "B")))
> x
   B
A   c d
  a 1 3
  b 2 4
> y
   B
A   c d
  a 5 7
  b 6 8

How do you combine them to produce z:
> z
, , C = e

   B
A   c d
  a 1 3
  b 2 4

, , C = f

   B
A   c d
  a 5 7
  b 6 8

It looks like a fairly common operation but I haven't found a function that
does this.


text:
Q: Max $Z=4x_1+5x_2$ Using two phase simplex
max $$z=4x_1+5x_2$$
  s.t $$3x_1+x_2\leq27$$
$$x_1+x_2=12$$
$$3x_1+2x_2\geq 30$$
$$x_1,x_2\geq 0$$

To start the process we find an initial solution, so we add a slack variables:
$$3x_1+x_2+x_3 = 27$$
$$x_1+x_2+x_4=12$$
$$3x_1+2x_2-x_5= 30$$
$$x_1,x_2, x_3,x_4,x_5\geq 0$$
or should it be
$$3x_1+x_2+x_3 = 27$$
$$x_1+x_2+x_4=12$$
$$3x_1+2x_2-x_5+x_6= 30$$
$$x_1,x_2, x_3,x_4,x_5,x_6\geq 0$$

A: To set up an LP in augmented form, to prepare it for either the two-phase method or the big-$M$, method:

*

*Each $\le$ constraint gets a slack variable

*Each $=$ constraint gets an artificial variable

*Each $\ge$ constraint gets both a surplus variable and an artificial variable

So, your second set of constraints is correct.

*

*$x_3$ is a slack variable

*$x_4$ is an artificial variable

*$x_5$ is a surplus variable and $x_6$ is an artificial variable.


text:
Q: Convert string from codepage 1252 to 1250 and back I work with Delphi 7 (ANSI based). I need to convert strings between code pages. I found a solution on the net with multiByteToWideChar and wideCharToMultiByte functions. But as I see it does not work back and force. I can convert from 1250 to 1252 but the other way is not so nice.
Here is my test code:
procedure TForm1.Button1Click(Sender: TObject);

function ANSIToUTF8( text_ : string; codePage_ : cardinal ): string;
var
  w : WideString;
  sizeMB, sizeWC : integer;
begin
  if ( codePage_ <> CONST_codepage_UTF8 ) then
  begin
    // ANSI_XXXX to UTF16
    sizeMB := length( text_ );
    sizeWC := multiByteToWideChar( codePage_, 0, PAnsiChar( text_ ), sizeMB, nil, 0 );
    setLength( w, sizeWC );
    multiByteToWideChar( codePage_, 0, PAnsiChar( text_ ), sizeMB, PWideChar( w ), sizeWC );

    // UTF16 to UTF8
    sizeMB := wideCharToMultiByte( CONST_codepage_UTF8, 0, PWideChar( w ), sizeWC, nil, 0, nil, nil );
    setLength( result, sizeMB );
    wideCharToMultiByte( CONST_codepage_UTF8, 0, PWideChar( w ), sizeWC, PAnsiChar( Result ), sizeMB, nil, nil );
  end else
    result := text_;
end;

function UTF8ToANSI( text_ : string; codePage_ : cardinal ): string;
var
  w : WideString;
  sizeMB, sizeWC : integer;
begin
  if ( codePage_ <> CONST_codepage_UTF8 ) then
  begin
    // UTF8 to UTF16
    sizeMB := length( text_ );
    sizeWC := multiByteToWideChar( CONST_codepage_UTF8, 0, PAnsiChar( text_ ), sizeMB, nil, 0 );
    setLength( w, sizeWC );
    multiByteToWideChar( CONST_codepage_UTF8, 0, PAnsiChar( text_ ), sizeMB, PWideChar( w ), sizeWC );

    // UTF16 to ANSI_XXXX
    sizeMB := wideCharToMultiByte( codePage_, 0, PWideChar( w ), sizeWC, nil, 0, nil, nil );
    setLength( result, sizeMB );
    wideCharToMultiByte( codePage_, 0, PWideChar( w ), sizeWC, PAnsiChar( Result ), sizeMB, nil, nil );
  end else
    result := text_;
end;

  procedure testString( s_ : string; icp_ : cardinal );
  var
    sutf : string;
    s1250, s1252 : string;
    pc : pchar;

    function strToHex( s_ : string; ocp_ : cardinal ) : string;
    var
      i : integer;
    begin
      result := '';
      for i := 1 to length( s_ ) do
      begin
        if ( i > 1 ) then
          result := result + ', ';
        result := result + TStringUtility.byteToHexaDecimalStr( ord( s_[i] ) );
      end;
    end;

    procedure logInput;
    var
      s : string;
    begin
      s := 'Input (' + intToStr( icp_ ) + '): ' + strToHex( s_, icp_ );
      listbox1.items.add( s );
    end;

    procedure logOutput( ocp_ : cardinal );
    var
      s : string;
    begin
      s_ := utf8toansi( sutf, ocp_ );
      s := 'Output (' + intToStr( ocp_ ) + '): ' + strToHex( s_, ocp_ );
      listbox1.items.add( s );
    end;

  begin
    logInput;
    sutf := ansitoutf8( s_, icp_ );
    logOutput( 1250 );
    logOutput( 1252 );
    listbox1.items.add( '' );
  end;

begin
  testString( #$f5 + #$fa + #$fb, 1250 ); // õúû in 1250
  testString( #$6f + #$fa + #$75, 1252 ); // õúû in 1252
end;

The logged results are not the expeted ones. It shows that the api calls converts the strings from 1250 into 1252 but no 1252 to 1250. I changed my default code page to 1252 and the result was the same.
Input (1250): $f5, $fa, $fb
Output (1250): $f5, $fa, $fb
Output (1252): $6f, $fa, $75

Input (1252): $6f, $fa, $75
Output (1250): $6f, $fa, $75
Output (1252): $6f, $fa, $75

A: What you are attempting is not possible. There are characters in 1250 that are not present in 1252, and vice versa.
Consider the example characters from your question. Let's start with $f5 in 1250. That is ő. Now, that character does not exist in 1252, and so the system has no way to do what you ask it to do. Instead it does the best it can, and returns $6f in 1252 which is o.
Then when you convert back from 1252 to 1250, there's no problem, because o is in the ASCII range and can be converted correctly. But of course there's no way for the system to be able to get back to ő, that information was lost when you went to 1252.
If you need to handle text in either 1250 or 1252, then the obvious solution is to use Unicode.


text:
Q: Is it is possible to make radio group readonly in Angular? I would like to if it is possible to make radio group readonly in Angular.

A: The Radio button not allowed to used "Readonly" attributed. Instead you can used
"Disabled" attributed for Disabled or Readonly.
HTML :
<input type="radio" name="example_6" value="4" disabled="true">

or you can used Angular Way with Form Group to disable
this.myForm.get('Example').disable();

A: disable will lose the value of the radio, so that's not what we want.
There is no elegant method to make it readonly.
Just recover the change with the old value programmatically, like this.
oldValue = getInitialOldValueFromServerOrWhatEver();

onChange(event: MatRadioChange, oldValue: someType) {
  if (someCondition) {
    this.yourForm.get('yourRadioGroupFormControlName').patchValue(event.value);
  } else {
    this.yourForm.get('yourRadioGroupFormControlName').patchValue(oldValue);
    // provide some info
    alert('This can not be changed');
  }
}

<mat-radio-group formControlName="yourRadioGroupFormControlName" (change)="onChange($event, oldValue)">


text:
Q: accessing tags from different classes - cocos2d This might sound quite straightforward. How can tags from one class accessed in another in cocos2d. I plan to use these tags to create a contact listener between a rope (rope class made of revolute joints) and a sprite (sprite class). Thanks in advance.

A: well, you can always retrieve an object that derives from CCNode as follows:
MyClass *anObject=(MyClass*) [theContainerObject getChildByTag:theObjectTagToRetrieve];

note that MyClass must also derive from CCNode (you could not have added it in the first place as a child of another CCNode derivative. Luck with that, it seems like a lot of properties to expose in HelloWorldLayer. Maybe another approach would be to add object getter methods in HelloWorldLayer that you could use elsewhere, ie hide your implementation details but provide the functionality.