text:
Q: Fall down or fall out Is it correct to say "He fell down from the tree" or we have to use fell out ?. Maybe these two forms are possible? Please explain me :)) thank You.

A: He fell **out of the tree, wagon, cart, car (the door is open)**.
Fall out implies you are "in something" and you fall out of it. For trees, we typically say to climb a tree, and to be "up in the tree". It is viewed as a "container". Therefore, you fall out of it. It is NOT a two-word verb.
Please note: You can also "fall out" with a group of friends. No longer be friends with them. It is a two-word verb here.
There is also fall off of something: He fell off the roof, he fell off the branch [of a tree where he was sitting], he fell off the pedestal, he fell off the boat. Here, it's OFF, because you are considered to be "on a surface". This is not a two-word verb.
/Fall down/ (a two-word verb) means to fall to the ground or to a surface without the idea of being inside something. He was walking down the street and fell down. The old lady tripped and fell down on the walkway*
However, we would say: He fell down the stairs. In that sense, it's fall and down the stairs and is not a two-word verb.


text:
Q: Doctrine Entity "Class not found" I'm proceeding to Doctrine's Getting Started guide and stuck in the beginning because of "Class 'Product' not found in /var/www/test/product-create.php on line 6":
<?php
require_once 'bootstrap.php';

$newProductName = $argv[1];

>>>>> $product = new Product();
$product->setName($newProductName);

$entityManager->persist($product);
$entityManager->flush();

echo sprintf('Created Product with ID %d' . PHP_EOL, $product->getId());

As written in guide, I have the Product class under "./src" directory in my project.
Please, help me, because I want to start using Doctrine without Symfony and I can't move any further.
Here is my bootstrap.php:
<?php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

use Symfony\Component\Yaml\Parser;

require 'vendor/autoload.php';

$yaml = new Parser();

$parameters = $yaml->parse(file_get_contents(__DIR__ . '/parameters.yml'));
$parameters = $parameters['parameters'];

$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . '/src'), $parameters['debug']);

$conn = array
    (
        'host'      => $parameters['database_host'],
        'port'      => $parameters['database_port'],
        'driver'    => $parameters['database_driver'],
        'user'      => $parameters['database_user'],
        'password'  => $parameters['database_password'],
        'dbname'    => $parameters['database_name']
    );

$entityManager = EntityManager::create($conn, $config);

And this is my Product.php:
<?php
/**
 * @Entity
 * @Table (name="products")
 **/
class Product
{
    /**
     * @Id
     * @Column(type="integer") @GeneratedValue
     **/
    protected $id;

    /**
     * @Column(type="string")
     **/
    protected $name;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

Thank you all in advance!

A: I dont see where you include Product class. You need to write in the top of your file
require_once 'patch_to_your_class/Product.php';
or to use an autoloader for classes.

A: I just came across your question now, and hope that you found an answer, but to help others you need to make sure that you included in your composer.json the following
"autoload": {
    "psr-0": {"": "src/"}
}

Or include it manually like @Сергей Студеникин suggested

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using $scope value to compare dates using momentjs I am currently using a select option to generate months and years using the angular attribute ng-repeat to gather data for credit card expiration dates.  I would like to return the value of the month and year after they are concatenated into one string and compare the string to today's date using momentjs.  When doing this, month and year are returning as an invalid date.  Please see my example below:
HTML
<select id="expMonth" class="form-control" ng-model="expMonth" ng-change="checkDate()">
   <option value="" disabled>Month</option>
   <option value="{{ month }}" ng-repeat="month in months">{{ month }}</option>
</select>

 <select id="expYear" class="form-control" ng-model="expYear" ng-change="checkDate()">
    <option value="" disabled>Year</option>
    <option value="{{ year }}" ng-repeat="year in years">{{ year }}</option>
 </select>

Javascript/Angular
$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
$scope.years = [];
var currentYear = new Date().getFullYear ();
for ( var i = currentYear; i <= new Date ().getFullYear () + 10; i++ ) $scope.years.push ( i );

$scope.checkDate = function() {
    var expDate = $scope.expMonth.toString() + $scope.expYear.toString();
    if (expDate < moment().format('MMYYYY')) {
      console.log('please enter an invalid date');
    } else {
      console.log('this date is valid')
    }
}

I believe the dates are returning as a string and I am not sure how to convert it so I can compare it with today's date using the moment.format('MMYYYY'). Any help would be awesome.

A: You are trying to compare if one string is less than another string which will not work. You have two options:

*

*Compare the months and the years separately

*Use moment's isBefore method to compare the dates

Separate Comparison:
$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
$scope.years = [];
var currentMonth = new Date().getMonth();
var currentYear = new Date().getFullYear();
for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i);

$scope.checkDate = function() {
  if (!($scope.expMonth && $scope.expYear)) return;
  if ($scope.expMonth <= currentMonth && $scope.expYear <= currentYear) {
    console.log('please enter an valid date');
  } else {
    console.log('this date is valid');
  }
}

Moment isBefore
$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
$scope.years = [];
var currentMonth = new Date().getMonth();
var currentYear = new Date().getFullYear();
for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i);

$scope.checkDate = function() {
  if (!($scope.expMonth && $scope.expYear)) return;
  var expDate = $scope.expMonth.toString() + $scope.expYear.toString();
  if (moment(expDate, 'MMYYYY').isBefore()) {
    console.log('please enter an valid date');
  } else {
    console.log('this date is valid');
  }
}


text:
Q: If $[G:N]$ and $|H|$ are relatively primes, then $H\lt N$. I'm trying to show that if $N$ is a normal subgroup of $G$ and $H$ is a subgroup of $G$ such that $[G:N]$ and $|H|$ are relatively primes, then $H\lt N$. I've already found $|H|||N|$ but I couldn't go further, I need help
Thanks in advance.

A: The image of $H$ under the canonical projection $G\to G/N$ is a subgroup of order dividing both $|H|$ and $|G/N|=[G:N]$, hence is trivial, hence is contained in the kernel $N$.

A: Hint: Consider the subgroup $HN$ of $G$ and note that $(HN)/N \cong H/(H\cap N)$.


text:
Q: Is there difference between how we treat 'free variable' in basic logic and the kind we come across in elementary mathematics? This question may come across as quite contrived so let me give you an example we might find in a typical (simple) example, let $x$ and $y$ be elements of the reals (they can be considered for all values in the reals) for example for a well defined $f$ we might have $y=f(x)$ which means for every admissible value of $x$ there exists a value of $y$ and they can form a set of pairs (in this case, the graph of $f$) forming the set: $[(x,y)|y=f(x)]$.
In this case we have limited our values such that $y=f(x)$ is always true, for every $x$ we must consider a certain $y$ and we have no freedom to change this.
In the case of the basic quantification logic I've done it seems different for proper 'free variables' for free variables we denote a domain of discourse $D$ and each variable is free to vary inside it, for example $x$ and $y$ are now free to vary however we can still have $y=f(x)$ but this becomes a subset of the possibilities of values for $x$ and $y$, now we can define something like $y=f(x)$ and consider the values of $x$ and $y$ that make it true, such as proving the existence of at least one pair in the graph by writing:
$∃(y)∃(x)(y=f(x))$
we can also say:
$∀(x)∃!(y)(y=f(x))$
And with the graph of the function, $G_f$
$∀((x,y)∈G_f(y=f(x))$
Is there a difference here between the first and second case? Can we make a distinction between a 'free variable' and an elementary variable?

A: Assuming $f$ is defined elsewhere, and we know it is a function, the 3 examples you give have the following meanings:

*

*$\exists y, \exists x, y=f(x)$ means "domain of $f$ includes at least one element, which I call $x$, and the image of $x$ by $f$ is $y$.

*$\forall x, \exists! y, y=f(x)$ means that for all $x$, there is one and only one image by $f$, which we call $y$. It is somewhat clumsy because $x$ is not restricted at all, so if we don't assume that $x$ is restricted to domain of $f$, it is false. And if we assume $x$ is restricted to domain of $f$, it is a tautology, $f$ being a function. One last interpretation would be: for all $x$ in the implicit set I am currently working in (e.g. $\mathbb{R}$) , there is a unique image by $f$; which means: $f$ is defined everywhere in our implicit working set.

*$\forall (x,y) \in G_f, y=f(x)$, assuming $G_f$ is defined elsewhere, is a tautology if $G_f$ is defined as all pairs of $(x, f(x))$.

A "free variable" has a precise technical meaning: a variable is free in an expression if its quantification does not appear in the expression. But it still needs to appear elsewhere in the mathematical discourse. See free and bound variables in Wikipedia.
More generally, if you want to dig this subject, you should define a context, i.e. what logic rules you are using, etc. The answer should then come from the context. Usually we do maths with a vague/sloppy notion of what a variable is, but this does not mean variable usage has never been studied. You could look at various formal logical systems, proof assistants (e.g. Coq), at programming languages especially the concept of referential transparency, etc.
Moreover, a large part of lambda calcules is just about dealing with variables, and the Wikipedia's article is very instructive; it shows there are many subtle details for variable management to be done right. A positive aspect is that all this is used in programming languages, and programming languages work, so there is a very strong basis, as well as a very strong community specialized in these topics. There are many points of contact between the math logic community and the computer science community, notably proof assistants.


text:
Q: What is the second parameter in savedInstanceState.getInt? I'd like to understand something from the following Android fragment docs:
Android fragment docs
In the example at the end of the page, the mCurCheckPosition int is saved in a bundle as "curChoice":
@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

However, at the start of the example, when checking for and possibly retrieving "curChoice", there is a second parameter '0' that is provided:
 if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }

What is this zero doing there? Surely the point of referencing "curChoice" is to retrieve the value that was saved under it in the first place?

A:
What is this zero doing there?

Quoting the documentation, it is the "value to return if [the] key does not exist".

Surely the point of referencing "curChoice" is to retrieve the value that was saved under it in the first place?

Yes, and in this case, the default value would seem to be superfluous. In general, the default value is for cases where the key is conditionally added to the Bundle, so the consumer of the Bundle can cleanly handle the case where the key was not added.

A:
Surely the point of referencing "curChoice" is to retrieve the value that was saved under it in the first place?

I replied to it:
Yeah, developer intention is clear to get the value saved in savedInstance , but
There may be situation :

key ,given to retrieve the value !=  Key, to insert the data in
  savedInstance

So developer also provide a default value (O in your case) that is used to prevent from null pointer exception

A: It's the default value to assign to "mCurCheckPosition" in case there is no "curChoice" key in the savedInstanceState. Think of it as a case where the fragment is getting restored(so savedInstanceState won't be null) but there is no "curChoice".


text:
Q: flatness and reduction Let $\mathcal J$ be an ideal sheaf on a (Noetherian) $Y$-scheme $X$, and let $\mathcal I$ be the unique primary ideal in a primary decomposition $\mathcal J$ corresponding to a minimal associated prime $x \in X$ with the closure $Z$. In this case $\mathcal O_X/\mathcal I$ puts a canonical scheme structure on  $Z$. If $Z_{red}$ is flat over $Y$, is it true that $Z$ itself is flat over $Y$? Would it help to assume that $X, Y$ are smooth?
(this is a reposting of this question here which didn't get answers)

A: Your current question as stated is a little weaker than the linked original question. So I will answer both negatively by giving an example of $I$ a prime ideal and $J$ is $I$-primary inside a polynomial ring $R$ over the complex number $k$.
The point is the so-called miracle flatness, (in the graded form for this example to ease notations). Let $S=k[l_1,...,l_d]$ where the $l$s form a system of parameters for $R/I$ (and also $R/J$). Then $R/I$ is flat over $S$ iff it is Cohen-Macaulay. So a counter-example exist whenever one can find an example such as $R/I$ is Cohen-Macaulay but $R/J$ is not.
Such examples are easy to find when you simply require $I$ to be the radical of $J$. But if you also want $J$ to be a primary ideal, the most pleasing-looking one is probably:
Let $R=k[a,b,c,x,y,z]$, let $I$ be the $2\times 2$ minors of the matrix $\begin{bmatrix} a & b & c \\  x & y & z\end{bmatrix}$. Let $J=I^2$. Then one can check that $I$ is a prime ideal, $J$ is primary (indeed it agrees with the second symbolic power of $I$), and $R/I$ is Cohen-Macaulay while $R/J$ is not. Note also that $X,Y$, being Spec of polynomial rings $R,S$, are smooth.


text:
Q: Azure active directory throwing "Not implemented" for api management disaster recovery I'm following this api management disaster recovery guide on the microsoft docs, I've setup my active directory user and got the values from the config (as suggested) and then have  copied and pasted the code out of the example
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/xxxx");
var result = await authenticationContext.AcquireTokenAsync("https://management.azure.com/", "xxx", new Uri("https://resource.com"), new PlatformParameters());

It seems that the suggested new PlatformParameters(PromptBehavior.Auto) doesn't work as that object no longer required you to pass a parameter into the constructor, I get a NotImplemented exception:
System.NotImplementedException : The method or operation is not implemented.
   at Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters.GetCoreUIParent()
   at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenInteractiveHandler.CreateWebUIOrNull(IPlatformParameters parameters)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenInteractiveHandler..ctor(RequestData requestData, Uri redirectUri, IPlatformParameters platformParameters, UserIdentifier userId, String extraQueryParameters, String claims)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenCommonAsync(String resource, String clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, String extraQueryParameters, String claims)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenAsync(String resource, String clientId, Uri redirectUri, IPlatformParameters parameters)

I feel like the values for tenant, application id may be wrong so I'll decribe to the best of my ability where I got these values from:
Tenant Id:

*

*On the azure active directory option click the "app registrations" option

*Find and click "Endpoints"

*copy out the oauth endpoint

*take the guid that is in the url and paste it into the var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/{here}");
Application Id

*

*On the azure active directory option click the "app registrations" option

*Find and click user who has the permissions required

*Click settings

*Click "properties" option in the list

*Copy out the "application id"

*paste it var result = await authenticationContext.AcquireTokenAsync("https://management.azure.com/", "{here}", new Uri("https://resource.com"), new PlatformParameters());
Edit: Looking through the decompiled source I've actually found the cause of my problems it seems that it calls through to the platform parameters class to GetCoreUiParent which is simply not implemented:
public class PlatformParameters : IPlatformParameters
{
    internal CoreUIParent GetCoreUIParent()
    {
      throw new NotImplementedException();
    }
}

Edit 2 - I feel a bit of an idiot here but it seems that a new version of this nuget has been published as a preview it has a new version of the PlatformParameters class which has an implementation but requires more parameters than the example given, I feel I am on the right track
Thanks all

A: Firstly, the steps in Microsoft Docs Guide you are referring register a Native application with Azure AD and then make use of Delegated Permissions. So there is code to prompt user for signing in and entering their credentials.
Now this code will work perfectly with a .NET Framework (Full) Console Application but not with .NET Core.
static void Main(string[] args)
{
        var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/{tenant id}");
        var result = authenticationContext.AcquireTokenAsync("https://management.azure.com/", "{application id}", new Uri("{redirect uri}"), new PlatformParameters(PromptBehavior.Auto)).Result;

Underlying issue for .NET Core is that it does not provide UI capabilities, so interactive flows aren't really supported with .NET Core.
This is also the reason you had to remove PromptBehavior.Auto from new PlatformParameters(PromptBehavior.Auto) as this would break for .NET Core.
You can find more information in the references mentioned below:

*

*Here is a thread on GitHub with code very similar to yours Interactive authentication in .net core 2.0 console application on windows

*Documentation for ADAL on GitHub. See it clearly says Except for .NET Core, which does not provide any user interaction

On a side note, I know .NET Core 3.0 is coming up with support for Windows Desktop Applications, but it's all still in preview.
In future interactive flow should work with .NET Core 3.0 and MSAL.NET (different than ADAL.NET).
More details here: ADAL does not properly support .NET Core 3


text:
Q: PHP or Laravel caching Server Side Code? I have this strange issue. My server side code is being cached by something i dont know what.
This is my route : Route::get('GlCountry/{country}', 'CashHoldingController@GetGlByCountry');
CashHoldingController had some functions but i deleted the entire file so now is empty and my application is still using the functions that i deleted... is like they are there but dont.
My server is running under IIS7 and im using laravel 5.5
No matter what i do is like the controller code is being cached somewhere.
I've tried disabling php opcache extension  but still the same. I dont know what is going on.

A: Clear the routes cache with this command:
php artisan route:clear


text:
Q: How to adding MS Access database in C# App and ASP.Net App This may be a stupid question....
But I remember I should able to select MS Access database from Visual Studio=>Project=>Add New Item=>Installed Template=>Data=>Local Database then I can select MS Access database....
But I couldn't find it anywhere....
I wonder if my Visual Studio version is different? I am using Visual Studio 2010 Professional.
Thanks in advance....
King


text:
Q: How to align active tab center in android Sliding Tab Layout I have 12 items in android sliding tab layout + view pager. While sliding from left to right, selected tab should be center same as play store. Please help me how to do that. In my application active tab is always left of the screen.

A: Google Has provided sample for sliding tab layout. But in the implementation of SlidingTabLayout class, it was not designed for center align the selected tab. I have modify the scroll method to make the selected/active tab center of the screen. Here is the code change:
Class Name: SlidingTabLayout
Line Number: 241, scrollToTab{}
Updated Method:
private void scrollToTab(int tabIndex, int positionOffset) {
    final int tabStripChildCount = mTabStrip.getChildCount();
    if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
        return;
    }

    View selectedChild = mTabStrip.getChildAt(tabIndex);
    if (selectedChild != null) {
        int targetScrollX = selectedChild.getLeft() + positionOffset;

        if (tabIndex > 0 || positionOffset > 0) {
            // If we're not at the first child and are mid-scroll, make sure we obey the offset
            targetScrollX -= (getWidth()-selectedChild.getWidth())/2;
        }

        scrollTo(targetScrollX, 0);
    }
}

A: Had this problem as well. tabLayout provides only tabContentStart option, needed both sides:
public class CenteringTabLayout extends TabLayout {
public CenteringTabLayout(Context context) {
    super(context);
}

public CenteringTabLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CenteringTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    View firstTab = ((ViewGroup)getChildAt(0)).getChildAt(0);
    View lastTab = ((ViewGroup)getChildAt(0)).getChildAt(((ViewGroup)getChildAt(0)).getChildCount()-1);
    ViewCompat.setPaddingRelative(getChildAt(0), (getWidth()/2) - (firstTab.getWidth()/2),0,(getWidth()/2) - (lastTab.getWidth()/2),0);
}
}

A: My approach differs a bit of the Shripad Bhat solution, which bounce the tab at the end of the slide.
Here's my workaround...
Changes to onPageScrolled method:
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    int tabStripChildCount = mTabStrip.getChildCount();
    if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
        return;
    }

    mTabStrip.onViewPagerPageChanged(position, positionOffset);

    View selectedTitle = mTabStrip.getChildAt(position);
    int selectedOffset = (selectedTitle == null) ? 0 : selectedTitle.getWidth();
    int nextTitlePosition = position + 1;
    View nextTitle = mTabStrip.getChildAt(nextTitlePosition);
    int nextOffset = (nextTitle == null) ? 0 : nextTitle.getWidth();
    int extraOffset = (int)(0.5F * (positionOffset * (float)(selectedOffset + nextOffset)));
    scrollToTab(position, extraOffset);

    if (mViewPagerPageChangeListener != null) {
        mViewPagerPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
    }
}

Changes to scrollToTab method:
private int mLastScrollTo;

private void scrollToTab(int tabIndex, int positionOffset) {
    final int tabStripChildCount = mTabStrip.getChildCount();
    if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
        return;
    }

    View selectedChild = mTabStrip.getChildAt(tabIndex);
    if (selectedChild != null && selectedChild.getMeasuredWidth() != 0) {

        int targetScrollX = ((positionOffset + selectedChild.getLeft()) - getWidth() / 2) + selectedChild.getWidth() / 2;

        if (targetScrollX != mLastScrollTo) {
            scrollTo(targetScrollX, 0);
            mLastScrollTo = targetScrollX;
        }
    }
}


text:
Q: Do Progress in the Ark retained between characters? I started a new game as a Nova Kid leaving behind a Human character i created when i had completed the Floran artifact quest and was looking for clue to the Hylotl one
When i got to The Ask with my new character i found not only is the Floran girl from the Floran artifact quest was there but the Floran Artifact was in the Arc's door
the answer here says that the universe is retained between characters like structures and the like. so does this mean that if i complete parts of the Artifact obtaining with one character, when i start a new character i skip these? (in this case since my human has gotten my Floran artifact would my Nova Kid skip this?)

A: All changes made in the Ark by completing quests (new characters moving into the Ark, and new shops opening in the Outpost) are retained since that's stored into the universe folder. Despite this your new character still has to do all the previous main-story quests of your old character since quest progression is not saved in the universe folder but character folder.


text:
Q: Header in RichTextBox file gets removed I use the following code:
RichTextBox rtf = new RichTextBox();
rtf.Rtf = AnswerRTF;
rtf.SaveFile(sourceFile + "/" + fileName);

for creating a RichTextBox file
but this code removes Header and Footer after creating that file.
What is the problem?

A: You can Use the following code for create rtf file when you saved rtf file in a database  :
            string attachFile = Path.Combine(dataDirectory, fileName);
            StreamWriter myStreamWriter = new StreamWriter(attachFile, true);
            myStreamWriter.WriteLine(AnswerRTF);
            myStreamWriter.WriteLine("}");
            myStreamWriter.Close();


text:
Q: RewriteRule on a long, ugly URL i am trying to redirect http://domain.com/partners/index.php?00N600000028zDp=0016000000qp33G&00N60000002UzF5=0016000000qp33G&00N600000029PAh=0016000000qp33G&00N6000000292kr=GO%20GREEN%20AMERICA%20TV&00N60000002X3cq=1$
to another page. typically i would do this as such:
RewriteRule ^partners/index.php?00N600000028zDp...(shortening this)$ http://domain.com/page/ [L,NE,NC,R=302]

however this time it's not working. i suspect it has something to do with the ?,=,&, or % characters in the URL, but i am not sure. any advice? thank you.

A: You can't match against the query string (everything after the ?) in the regex pattern in a RewriteRule. You need to match against the %{QUERY_STRING} variable:
RewriteCond %{QUERY_STRING} ^00N600000028zDp=0016000000qp33G&00N60000002UzF5=0016000000qp33G&00N600000029PAh=0016000000qp33G&00N6000000292kr=GO%20GREEN%20AMERICA%20TV&00N60000002X3cq=1$
RewriteRule ^partners/index.php$ http://domain.com/page/? [L,NE,NC,R=302]

Keep in mind that when you redirect the browser, the browser will load http://domain.com/page/ and this redrect that you've setup doesn't touch that at all. So you'll see the contents of http://domain.com/page/ once you get redirected.


text:
Q: Hibernate 5 on GAE: NoClassDefFoundError: javax.naming.StringRefAddr is a restricted class After migration from Hibernate 4.3.11.Final to 5.0.6.Final I receive the following exception:
[INFO] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in xxx.xxx.configuration.AppConfiguration: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax.naming.StringRefAddr is a restricted class. Please see the Google  App Engine developer's guide for more details.
[INFO]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
[INFO]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
[INFO]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
[INFO]  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
[INFO]  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
[INFO]  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
[INFO]  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
[INFO]  at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1051)
[INFO]  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:828)
[INFO]  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
[INFO]  at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
[INFO]  at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
[INFO]  at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
[INFO]  at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548)
[INFO]  at org.mortbay.jetty.servlet.Context.startContext(Context.java:136)
[INFO]  at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
[INFO]  at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
[INFO]  at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
[INFO]  at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
[INFO]  at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
[INFO]  at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
[INFO]  at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
[INFO]  at org.mortbay.jetty.Server.doStart(Server.java:224)
[INFO]  at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
[INFO]  at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:272)
[INFO]  at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:283)
[INFO]  at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
[INFO]  at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
[INFO]  at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
[INFO]  at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:258)
[INFO]  at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:47)
[INFO]  at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:213)
[INFO]  at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:211)
[INFO]  at java.security.AccessController.doPrivileged(Native Method)
[INFO]  at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:211)
[INFO]  at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:277)
[INFO]  at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
[INFO]  at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:225)
[INFO]  at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:216)

[INFO] Caused by: java.lang.NoClassDefFoundError: javax.naming.StringRefAddr is a restricted class. Please see the Google  App Engine developer's guide for more details.
[INFO]  at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:52)
[INFO]  at org.hibernate.internal.SessionFactoryImpl.getReference(SessionFactoryImpl.java:877)
[INFO]  at org.hibernate.type.TypeFactory$TypeScopeImpl.injectSessionFactory(TypeFactory.java:62)
[INFO]  at org.hibernate.type.TypeFactory.injectSessionFactory(TypeFactory.java:100)
[INFO]  at org.hibernate.type.TypeResolver.scope(TypeResolver.java:37)
[INFO]  at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:249)
[INFO]  at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
[INFO]  at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
[INFO]  at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:135)
[INFO]  at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
[INFO]  at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
[INFO]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$6.run(AbstractAutowireCapableBeanFactory.java:1627)
[INFO]  at java.security.AccessController.doPrivileged(Native Method)
[INFO]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1624)
[INFO]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
[INFO]  ... 38 more

StringRefAddr is a restricted class I know, but is there any trick to run Hibernate 5 somehow? I am using GAE 1.9.30.

A: I just shared details on the GAE implementation around black & white lists along with the hack that one need to do get around this issue here.


text:
Q: Having  in
* take up entire height in justified
* I've created this Plunker (make preview frame wider enough so each list item doesn't take up a whole line).
I have the following markup:

Here is the first link

Here is the second link

Yet another, this time with a lot more text that wraps

Here is the second link

I would like all anchors to take up the same height, 100% of the li they're contained in.  So if the anchor have enough text that it wraps within the list item, all the anchors should have that same height.
The issue appears to be how .nav-justified is implemented in that the list items have display: table-cell; which is required to allow them to be justified, but prevents the anchors from taking up the entire height.  Any way around this other than making the list items have a static height?

A: Giving a height in pixel to li do the trick.
jsfiddle
li {
  border: 1px solid red;
  height:80px;
}


text:
Q: Unable to decrypt email address using openssl_decrypt & AES in PHP I'm trying to create an unsubscribe link for my email marketing system. In the email I created an unsubscribe button and after it's clicked I'm trying to pass the email address and table id via the URL, with encryption like below:
<?php

$email_id = '123456';
$addto = 'test@gmail.com';

$email_id= openssl_encrypt($email_id, "AES-256-CBC", "25c6c7ff35b9979b151f2136cd13b0ff");
$encto= openssl_encrypt("$addto", "AES-256-CBC", "25c6c7ff35b9979b151f2136cd13b0ff");

 ?>

after click button url is like
https://sub.example.com/unsbscribe.php?id=bK2XGnJms0rzPuQOpvauGw==&eadd=WoN/K2t4xjKb057c++EIhg==

unsbscribe.php:
<?php

$eid    = $_GET['id'];
$eaddr  = $_GET['eadd'];

$eid    = openssl_decrypt($eid, "AES-256-CBC", "25c6c7ff35b9979b151f2136cd13b0ff");
$eaddr  = openssl_decrypt($eaddr, "AES-256-CBC", "25c6c7ff35b9979b151f2136cd13b0ff");

?>

Your Email Address is <address><?php echo $eaddr; ?></address>

Your Id is: <?php echo $eid; ?>

Please check this link of my real project which will output $_get Data and unencrypted data also
https://ems.vozcodex.com/unsbscribe.php?id=bK2XGnJms0rzPuQOpvauGw==&eadd=WoN/K2t4xjKb057c++EIhg==
Using
var_dump($_GET);
Result: array(2) { ["id"]=> string(24) "bK2XGnJms0rzPuQOpvauGw==" ["eadd"]=> string(24) "WoN/K2t4xjKb057c EIhg==" }

I'm only able to decrypt the table id - which is '123456', but not the email address. I tried various openssl_decrypt methods but am unable to decrypt the email address. email address always comes empty.
Can you please help to point out the issue. I am using PHP 7.4 (ea-php74).

A: It seems encoding of the + signs went wrong. Try url-encoding the encrypted values properly when generating the URL for the email, as suggested by Topaco in the comments. + (and several other characters) has a special meaning in URLs.
e.g. something like:
$email_id = openssl_encrypt($email_id, "AES-256-CBC", "25c6c7ff35b9979b151f2136cd13b0ff");
$encto = openssl_encrypt($addto, "AES-256-CBC", "25c6c7ff35b9979b151f2136cd13b0ff");

$url = "https://sub.example.com/unsbscribe.php?id=".urlencode($email_id)."&eadd=".urlencode($encto);


text:
Q: Why my string containing query does not work in stored procedure My situation is that I send a query to the stored procedure to run it though c# code.
This query is generated through c# code and it runs successfully when I directly copy and paste it on storedprocedure and run it.
My query is  this :
select acString from account_string where bstatus=1 and  (dbo.getElementFromString(1,acstring) between 1000 and 4587)

(I copied it after running my code by debugging as it is genrated dynaimcally).
The same query I send to stored procedure through parameters  like this :
ALTER PROCEDURE [dbo].[sp_shekharSheetDisplay]
@action varchar(50)='',
@query varchar(max)=''   //here  i send my query through parameter
AS
BEGIN
 SET NOCOUNT ON;
BEGIN TRY
  if(@action='sheet')
 begin
     select accountstring,
     isnull(sum(case when amttype='dr' then (amount) end),'0.00') DR,
     isnull(sum(case when amttype='cr' then (amount)  end),'0.00') CR,
     isnull(sum(case when amttype='dr' then (amount) end),'0.00')-isnull(sum(case when amttype='cr' then (amount)  end),'0.00') amt
     from tbltransaction_detail where accountstring in (@query)
     group by accountstring

 end
END TRY
BEGIN CATCH
    EXECUTE sp_ErrorDB_AddNew
 SELECT 3,'SQL Exception'
END CATCH
END

It does not work while running. It does not send any data to my dataset (in ds below):
    Cls_budget objBudget = new Cls_budget();
    DataSet ds = new DataSet();
    objBudget.Action = "sheet";
    objBudget.Query = query;
    ds = objBudget.ManageSheet();// I found no data in ds here in my table

But when I try that query statically by copying and replacing the @query in line below :
     from tbltransaction_detail where accountstring in (@query)
Then I get all table displayed with data (please see this http://prntscr.com/ashf14)
Why it does not work when I use @query?

A: You are trying to use your passed in query directly within an IN-clause. This will not work...
You might try something with dynamic SQL: This will create your statement as a string, fill in the passed in query as if it was written there directly, and then execute the command dynamically.
But I must admit, that I think it was better to pass in the parameters you use in your "internal" query and solve this without dynamic SQL...
 DECLARE @cmd NVARCHAR(MAX)=
 N'select accountstring,
 isnull(sum(case when amttype=''dr'' then (amount) end),''0.00'') DR,
 isnull(sum(case when amttype=''cr'' then (amount)  end),''0.00'') CR,
 isnull(sum(case when amttype=''dr'' then (amount) end),''0.00'')-isnull(sum(case when amttype=''cr'' then (amount)  end),''0.00'') amt
 from tbltransaction_detail where accountstring in (' +  @query + ')
 group by accountstring';
 EXEC (@cmd)


text:
Q: Error in metadata: org.apache.thrift.transport.TTransportException What is this Error means?
"  Error in metadata: org.apache.thrift.transport.TTransportException? "
In what are all the cases this error come?
I am getting this error while creating tables and while loading the data into the table.

A: org.apache.thrift.transport.TTransportException, Its a very generic error that message describing that the hiveserver is having a problem and suggesting you to take a look at the Hive logs. If you can able to access the full log stack and share the exact details might get the real cause of this problem. Most of the times I faced this error was like Issues with hive metadata, unable to access hive metadata,dir permissions issues,concurrency related issues, hiveserver port related problems.
You can give a try restarting and recreating your tables. or setting up hive port before starting the server might help you.
    $export HIVE_PORT=10000
    $hive --service hiveserver

There might be other reasons too but we can look out there once we get full log stack.


text:
Q: Possibly Incorrect Current Reading I'm not entirely sure if I have done the following equation correct or not, but based on the calculations, my multimeter result seems to be incorrect. I have a very simple circuit, containing a 9V battery, an LED (with 3.2 V forward voltage at 24 mA), and a 270 ohm resistor (as shown below).

simulate this circuit – Schematic created using CircuitLab
My question is, when I do the calculations to determine what the current should be in the circuit, I do (voltage / resistance = I), so I get (I = 5.8V / 270 = 0.0214 Amps).  This is 21 mA, approximately. When I insert my meter into the circuit, (inserting the meter between + and the LED, breaking the circuit and properly measuring amperage) I obtain a reading of about 2.1 mA. Did I do the calculation wrong?
I am using a Craftsman 82344 autoranging multimeter. Also, when I insert the multimeter into the circuit, the LED no longer illuminates as it should (at least according to the articles I have studied). Any help would be appreciated, if any more details are needed let me know.

A: Since your circuit has a known resistance in it, you can avoid the meter burden voltage issue by calculating the current from a measurement of the voltage drop across the resistor measured with your meter in voltmeter mode, rather than by inserting the meter into the circuit in ammeter mode.
Of course, if your resistor doesn't have the value you think it does (manufacturing tolerance or human error in reading the markings) that determination will be invalid, but you can remove the battery and use your meter in ohm mode on the unpowered circuit to measure the resistor.

A: The manual doesn't say what the internal shunt resistor is but it may be high enough to affect the circuit you're measuring. Try hooking up again and manually changing the range to the highest that will still give you two significant digits of current reading - probably using the 'select' switch on your meter. This will switch in progressively lower shunt resistors. Record the current reading for each setting.
Let us know how that works.

A: I suspect you had the meter connected incorrectly.
When measuring current, the meter must be inserted in the circuit - break the circuit at some point, and connect the meter leads to the two points that you disconnected, so all the current flowing in the circuit passes through the meter.


text:
Q: Collective nouns for "stewardess"? What are the collective nouns for stewardess? Like the group of stewardess, the team ... what else could it be?
I've been trying to google it, but haven't found it yet =(

A: After having a quick search in here (https://en.wiktionary.org/wiki/Appendix:Glossary_of_collective_nouns_by_subject) for stewardess, attendant, flight attendant, cabin crew and air stewardess and having a quick Google for "collective noun for flight attendants" and found nothing, I am confident in saying that there is not an accepted group noun for describing a number of stewardesses. You will therefore need to do one of two things:

*

*Use a group noun used for something else that is related in some way. There are lots of possibilities here, so I will just list a few. Group would be the most generic, if there were a lot of them you could use crowd; I quite like bevy, but my personal choice would perhaps be flock.

*Make up your own group noun that either makes sense, or is humorous. E.g. (using BillJ's suggestion in the comments) "a cabin of stewardesses".

A side note - assuming you are referring to an air stewardess, they don't tend to be called that nowadays; instead they are referred to as flight attendants or cabin crew in order to be gender neutral.

A: Well a group of stewardesses have just me and they sounded like a bunch of geese, so how about a "gaggle" of stewardesses


text:
Q: Continuous but partial derivative does not exist Let $f:\mathbb{R}^2\to \mathbb{R}$ be any function. Then we know the following:

*

*Differentiability  implies existence of partial derivatives and continuity

*Existence of partial derivatives does not imply continuity and hence not differnetiability.

*Continuity does not imply differentiability.

But now my question is "Does continuity of $f$ implies existence of partial derivatives?"

A: No. Take $f(x,y)=|x|$. It is continuous, but $\frac{\partial f}{\partial x}(0,0)$ doesn't exist.

A: Not even nicely true for single-variable functions.  See Weierstrass function:
  https://en.wikipedia.org/wiki/Weierstrass_function
Continuous everywhere, differentiable nowhere.

A: Consider the function
\begin{align}
f(x,y)&=|x|+|y|, &\text{if}\quad(x,y)\ne(0,0)\\
&=0,&\text{if}\quad(x,y)=(0,0)
\end{align}
This function is continuous at $(0,0)$ but none of the first order partial derivatives exist.


text:
Q: where data has been stored between the trans and rollback...? On the interview I faced a question. So I try to recreating it:
salary
id  Emp_id  Salary
1   1       50000
2   2       40000
3   3       30000

See following example:
begin tran
update salary set Salary = 25000 where id = 2
select * from salary -- salary = 25000
rollback
select * from salary -- salary = 40000

Here my question is,

where did the old value of salary has been stored.?

Note : My guess is Magic Table may be used as like as trigger.
when I googled like 'where did the data has been stored between the trans and rollback', then I get the results as different types of Transaction-Rollback Tutorials. So I need helping hand from Stack overflow.
Edit 1
begin tran
update salary set Salary = 25000 where id = 2
select * from salary -- salary = 25000
-- I want to see salary = 40000 at here. Where as OUTPUT clause is invalid.
rollback
select * from salary -- salary = 40000

Thanks,
TamilPugal.

A: It is NOT a "magic table". The transaction details are stored in the transaction log until the transaction is released (commit or rollback). A table would be insufficient here because a transaction could affect any number of tables.
To be more clear, the data still resides in the table but is marked for deletion. Then either the rows become unmarked or the rows are removed. I am not good at explaining this but that is the basic concept of how it works.

A: Have a look at this...
USE tempdb;
go

CREATE TABLE dbo.TranTest (id INT NOT NULL, some_value INT NOT NULL);
INSERT dbo.TranTest (id, some_value) VALUES (1, 11111);

BEGIN TRANSACTION
    -- check initial values...
    SELECT * FROM dbo.TranTest tt;

    -- update values and include the OUTPUT clause to view the contents of the "Inserted" & "Deleted" tables.
    UPDATE tt SET
        tt.some_value = tt.some_value * 22
            OUTPUT
                Deleted.id,
                Deleted.some_value,
                Inserted.id,
                Inserted.some_value,
                GETDATE() AS tran_date
    FROM
        dbo.TranTest tt;

    -- check the values after the UPDATE and before the ROLLBACK
    SELECT * FROM dbo.TranTest tt;

ROLLBACK TRANSACTION

    -- check the values after the ROLLBACK
    SELECT * FROM dbo.TranTest tt;

Results...
id          some_value
----------- -----------
1           11111

id          some_value  id          some_value  tran_date
----------- ----------- ----------- ----------- -----------------------
1           11111       1           244442      2018-11-16 16:18:17.330

id          some_value
----------- -----------
1           244442

id          some_value
----------- -----------
1           11111


text:
Q: Memory Management with C++ plugin plugged into C software Suppose I have a C-Programm that calls some code written in C++. To make it a bit more concrete, this could look similar to the following:
// C++:
extern "C" void * pluginFunction(void * input) {
    result = (SomeObject *) input;
    if (! result)
        SomeObject * result = new SomeObject();

    // Do something really intelligent here.
    return (void*) result;
}

For the calling C-programm:
int main() {
    void * result;
    while (something) {
        result = pluginFunction(result);
        // some more things
    }

    // Cleanup memory
}

Furthermore suppose that the C-Programm provides a custom memory management. Thus, the C-Programm alway knows which memory has been allocated using the provided function custom_alloc, custom_free and custom_realloc.
On the C++-side, the operators new, new[], delete and delete[] have been overloaded globally both in the standard and in the throw () version.
Now my questions:

*

*If the C-part would free all memory allocated over the custom functions during the call of pluginFunction, would it free all memory actually allocated, or is there something more than the memory provided by the variants of new?

*What further harm would be done by bypassing the call to a proper destructor? Could that harm be avoided purly on the C++-side, e.g. within pluginFunction?

*Do you see any potential pitfalls or side-effects?

Please note that I have no access to the calling C-Program, but have to use the interface provided. Thus, I have no other option as to arrange my memory in a way that it gets freed properly and hope for the best.

A: The rule is very simple: you have to destroy memory where you allocate one. So your plugin interface must provide both allocate and deallocate functions.

A: *

*C++ functions can also call malloc() or any other standard C library that might call malloc(), so overriding new and delete might not be enough. You would also need to override malloc, calloc, etc.

*The C++ code might do some other initialization that needs deinitialization in the destructor, like opening hardware, sockets, files, etc. So yes, there can be side effects.

*See 2.


text:
Q: How to cope with multi AZ RDS MySQL on SQL Server? We run SQL Server (production), and RDS MySQL off AWS. Both have their respective static IP address. SQL Server pulls data from MySQL database regularly. If we enable multi AZ for the RDS MySQL instance, how then should we configure SQL Server?
Current configuration utilises MySQL Connector/ODBC Data Source Configuration and we believe that the TCP/IP Server field accepts only a valid IP address. It is not able to establish connection, although able to resolve the endpoint's IP address correctly, to the MySQL server. By endpoint, I mean the long connection string -- myInstanceName.abbd12345.us-east1.rds.amazonaws.com

In an event of a MySQL failover, the endpoint string remains the same but its IP address would have changed/switched over to another. This, effectively, will render the current SQL Server configured connection by IP address to break. It will be a pain in the neck to update the connection by hand every time.
TL;DL
MySQL will be multi AZ. How to configure SQL Server to use the correct IP address if and when MySQL has a failover?

A: As it turns out, just found out that it does not work for MySQL ODBC driver v3.x. It works for MySQL ODBC driver version 5.x.

Download the latest MySQL ODBC driver or version 5.x.
https://dev.mysql.com/downloads/connector/odbc/5.3.html


text:
Q: MongoDB aggregation: Counting results of the lookup without joining I'm working with this query:
    customers.aggregate: [
  {$lookup: {
    from: "users",
    localField: "_id",
    foreignField: "customerId",
    as: "users"
  }},
  {$lookup: {
    from: "templates",
        let: {localField: "$_id"},
    pipeline: [{
    $match: { $and: [{
      $expr: { $eq: ["$customerId", "$$localField"]}},
        {module: false}]
    }}],
    as: "templates"
  }},
  {$lookup: {
    from: "publications",
    localField: "_id",
    foreignField: "customerId",
    as: "publications"
  }},
 {$lookup: {
    from: "documents",
    let: {localField: "$_id"},
    pipeline: [{
    $match: { $and: [{
      $expr: { $eq: ["$customerId", "$$localField"]}},
        {createdAt: {$gte: {$date: "<someDate>"}}}]
    }}],
    as: "recentDocuments"
  }}
]

In the last lookup stage I'm filtering documents with the customerId field according to the _id field and newer than <someDate> and then joining those documents to respective "customer" object.
And after this step or if possible even in this same step I would also like to add a new field to each resulting "customer" document with the counted number of all the documents (not only those that pass the time filter) from the "documents" collection with the customerId field value corresponding to the customer document's _id. And I also wish not to join those documents to the customer object as I only need a total number of documents with respective customerId. I can only use extended JSON v1 strict mode syntax.
The result would look like:
customers: [
 0: {
  users: [...],
  templates: [...],
  publications: [...],
  recentDocuments: [...],
  totalDocuments: <theCountedNumber>
 },
 1: {...},
 2: {...},
 ...
]

A: Use $set and $size
db.customers.aggregate([
  {
    $lookup: {
      from: "documents",
      let: { localField: "$_id" },
      pipeline: [
        {
          $match: {
            $and: [
              { $expr: { $eq: [ "$customerId", "$$localField" ] } }
            ]
          }
        }
      ],
      as: "recentDocuments"
    }
  },
  {
    $set: {
      totalDocuments: { $size: "$recentDocuments" }
    }
  }
])

mongoplayground

A: So on Thursday I've found a proper syntax to solve my problem. It goes like:
db.customers.aggregate([
    {
    $lookup: {
    from: "users",
    localField: "_id",
    foreignField: "customerId",
    as: "users"
  }},
  {$lookup: {
    from: "templates",
        let: {localField: "$_id"},
    pipeline: [{
    $match: { $and: [{
      $expr: { $eq: ["$customerId", "$$localField"]}},
        {module: false}]
    }}],
    as: "templates"
  }},
  {$lookup: {
    from: "publications",
    localField: "_id",
    foreignField: "customerId",
    as: "publications"
  }},
  {$lookup: {
    from: "documents",
    let: {localField: "$_id"},
    pipeline: [{
    $match: { $and: [{
      $expr: { $eq: ["$customerId", "$$localField"]}},
        {createdAt: {$gte: {$date: "<someDate>"}}}]
    }}],
    as: "recentDocuments"
  },
  {$lookup: {
    from: "documents",
    let: {localField: "$_id"},
    pipeline: [{
    $match: {$and: [{
      $expr: {$eq: ["$customerId", "$$localField"]}},
      { $count: "count" }],
    as: "documentsNumber"
  }}
])

This command would, in the last stage of the aggregate pipeline, go over the documents collection again, but this time would return all the documents instead of filtering by the time period, and then would swap the resulting object for every "customer" object with the array with one item being the number of all the documents. The array could be later "unwinded" with the $unwind action, but it proved to decrease the performance drastically, thus - omitted. I really hope this will help someone to solve a similar problem.


text:
Q: PowerShellGet "unable to find package source" upon Install-Module, despite Find-Module working correctly I recently created an Azure Artifacts feed for one of the projects in my organization. I followed the instructions at this link.
Most things work. In particular, I'm able to:

*

*Create the feed

*Use nuget to push a package to said feed

*Register the feed with PowerShell via Register-PSRepository

*Run Find-Module -Repository <Repository Name>
The last bit -- running Find-Module -- generates the expected output, viz., a single module with the expected version, name, and description. However, I get the following message when I attempt Install-Module:
PS C:\Windows\System32> install-module -name ADHelpers -Repository 'ADHelpersTest2'
Install-Package: C:\Users\my_name\OneDrive\Documents\PowerShell\Modules\PowerShellGet\2.2.5\PSModule.psm1:9711
Line |
9711 |  … talledPackages = PackageManagement\Install-Package @PSBoundParameters
     |                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to resolve package source
     | 'https://pkgs.dev.azure.com/my_organization/my_project/_packaging/my_feed/nuget/v2'.

I've scrubbed my organization, project, and feed name, as I don't think that's important for solving this problem.
My question is simple: What could cause this? I'm confused that I'm able to Find-Module just fine, but unable to run Install-Module for the result that Find-Module successfully fetches.
I've been unsuccessful in finding guidance elsewhere, and am unsure what I'm doing wrong.
Thanks in advance -- I appreciate your time.

A: If you want to install the custom package in the Azure DevOps pipeline, you could add task power shell and run the script Install-Package ADHelpers -Scope CurrentUser -Force
to install the package.
In my sample, the package name is Get-Hello and the result is:

You could refer to this blog and my previous answers for more details


text:
Q: PROC TABULATE with ALL and row percentage I am not able to get a row with ALL using row percentages.  I would like the first row to give sum and percentage for column totals. So the percent under borderline for ALL should display 1861 * 100/5049=36.8% and under Desirable to display 1399 * 100/5049=27.7%. Currently it is displaying 100% and I need to change that.
proc tabulate data=sashelp.heart;* format=8.2;
 class chol_status smoking_status sex;
 table (all   smoking_status sex),
    (all chol_status)*(n*f=8. colpctn) ;
run;

The output is
           All      Cholesterol Status
                   Borderline Desirable  High
         N ColPctN N ColPctN N ColPctN N ColPctN
All     5049 100.00 1861 100.00 1399 100.00 1789 100.00  <- change the cholesterol % to denominator 5049

Smoking Status
Heavy (16-25)   1029 20.38 383 20.58 285 20.37 361 20.18
Light (1-5)      563 11.15 192 10.32 174 12.44 197 11.01
Moderate (6-15)  563 11.15 217 11.66 170 12.15 176 9.84
Non-smoker      2436 48.25 886 47.61 655 46.82 895 50.03
Very Heavy (> 25) 458 9.07 183 9.83 115 8.22 160 8.94

Sex
Female 2770 54.86 959 51.53 803 57.40 1008 56.34
Male   2279 45.14 902 48.47 596 42.60 781 43.66

A: I think the closest you can get is this:
proc tabulate data=sashelp.heart;* format=8.2;
 class chol_status smoking_status sex;
 table all*rowpctn=' '   (smoking_status sex)*(n=' '*f=8. colpctn=' '),
    (all) (chol_status) ;
run;

That's not what you want, though, and doesn't really look very good.  It's the only option that comes out of proc tabulate, though, as Tabulate won't let you assign statistics to both the rows and the columns - you have to pick one.
PROC REPORT will do what you want, with some effort.  However, you could also run this in a two step process - output the tabulate to a dataset, fix the row percentages, then re-print it, either in Report or Tabulate, not asking it to percentage things that time.


text:
Q: Unable to work with unixtimestamp column type in string data type I have a hive table to load JSON data. There are two values in my JSON. Both have data type as string. If I keep them as bigint, then select on this table gives below error:
Failed with exception java.io.IOException:org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.JsonParseException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
 at [Source: java.io.ByteArrayInputStream@3b6c740b; line: 1, column: 21]

If I change it two string, then it works OK.
Now, because these columns are in string, I am not able to use from_unixtime method for these columns.
If I try to alter these columns data types from string to bigint, I get below error:
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter table. The following columns have types incompatible with the existing columns in their respective positions : uploadtimestamp

Below is my create table statement:
create table ABC
(
    uploadTimeStamp bigint
   ,PDID            string

   ,data            array
                    <
                        struct
                        <
                            Data:struct
                            <
                                unit:string
                               ,value:string
                               ,heading:string
                               ,loc:string
                               ,loc1:string
                               ,loc2:string
                               ,loc3:string
                               ,speed:string
                               ,xvalue:string
                               ,yvalue:string
                               ,zvalue:string
                            >
                           ,Event:string
                           ,PDID:string
                           ,`Timestamp`:string
                           ,Timezone:string
                           ,Version:string
                           ,pii:struct<dummy:string>
                        >
                    >
)
row format serde 'org.apache.hive.hcatalog.data.JsonSerDe'
stored as textfile;

My JSON:
{"uploadTimeStamp":"1488793268598","PDID":"123","data":[{"Data":{"unit":"rpm","value":"100"},"EventID":"E1","PDID":"123","Timestamp":1488793268598,"Timezone":330,"Version":"1.0","pii":{}},{"Data":{"heading":"N","loc":"false","loc1":"16.032425","loc2":"80.770587","loc3":"false","speed":"10"},"EventID":"Location","PDID":"skga06031430gedvcl1pdid2367","Timestamp":1488793268598,"Timezone":330,"Version":"1.1","pii":{}},{"Data":{"xvalue":"1.1","yvalue":"1.2","zvalue":"2.2"},"EventID":"AccelerometerInfo","PDID":"skga06031430gedvcl1pdid2367","Timestamp":1488793268598,"Timezone":330,"Version":"1.0","pii":{}},{"EventID":"FuelLevel","Data":{"value":"50","unit":"percentage"},"Version":"1.0","Timestamp":1488793268598,"PDID":"skga06031430gedvcl1pdid2367","Timezone":330},{"Data":{"unit":"kmph","value":"70"},"EventID":"VehicleSpeed","PDID":"skga06031430gedvcl1pdid2367","Timestamp":1488793268598,"Timezone":330,"Version":"1.0","pii":{}}]}

Any ways I can convert this string unixtimestamp to standard time or I can work with bigint for these columns?

A: *

*If you are talking about Timestamp and Timezone then you can define them as int/big int types.
If you'll look on their definition you'll see that there are no qualifiers (") around the values, therefore they are of numeric types within in the JSON doc:
"Timestamp":1488793268598,"Timezone":330

create external table myjson
(
    uploadTimeStamp string
   ,PDID            string

   ,data            array
                    <
                        struct
                        <
                            Data:struct
                            <
                                unit:string
                               ,value:string
                               ,heading:string
                               ,loc3:string
                               ,loc:string
                               ,loc1:string
                               ,loc4:string
                               ,speed:string
                               ,x:string
                               ,y:string
                               ,z:string
                            >
                           ,EventID:string
                           ,PDID:string
                           ,`Timestamp`:bigint
                           ,Timezone:smallint
                           ,Version:string
                           ,pii:struct<dummy:string>
                        >
                    >
)
row format serde 'org.apache.hive.hcatalog.data.JsonSerDe'
stored as textfile
location '/tmp/myjson'
;

+------------------------+-------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| myjson.uploadtimestamp | myjson.pdid |                                                                                myjson.data                                                                                |
+------------------------+-------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|          1486631318873 |         123 | [{"data":{"unit":"rpm","value":"0","heading":null,"loc3":null,"loc":null,"loc1":null,"loc4":null,"speed":null,"x":null,"y":null,"z":null},"eventid":"E1","pdid":"123","timestamp":1486631318873,"timezone":330,"version":"1.0","pii":{"dummy":null}},{"data":{"unit":null,"value":null,"heading":"N","loc3":"false","loc":"14.022425","loc1":"78.760587","loc4":"false","speed":"10","x":null,"y":null,"z":null},"eventid":"E2","pdid":"123","timestamp":1486631318873,"timezone":330,"version":"1.1","pii":{"dummy":null}},{"data":{"unit":null,"value":null,"heading":null,"loc3":null,"loc":null,"loc1":null,"loc4":null,"speed":null,"x":"1.1","y":"1.2","z":"2.2"},"eventid":"E3","pdid":"123","timestamp":1486631318873,"timezone":330,"version":"1.0","pii":{"dummy":null}},{"data":{"unit":"percentage","value":"50","heading":null,"loc3":null,"loc":null,"loc1":null,"loc4":null,"speed":null,"x":null,"y":null,"z":null},"eventid":"E4","pdid":"123","timestamp":1486631318873,"timezone":330,"version":"1.0","pii":null},{"data":{"unit":"kmph","value":"70","heading":null,"loc3":null,"loc":null,"loc1":null,"loc4":null,"speed":null,"x":null,"y":null,"z":null},"eventid":"E5","pdid":"123","timestamp":1486631318873,"timezone":330,"version":"1.0","pii":{"dummy":null}}] |
+------------------------+-------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

*Even if you have defined Timestamp as a string you can still cast it to a bigint before using it in a function that requires a bigint.
cast (`Timestamp` as bigint)

hive> with t as (select '0' as `timestamp`) select from_unixtime(`timestamp`) from t;

FAILED: SemanticException [Error 10014]: Line 1:45 Wrong arguments
  'timestamp': No matching method for class
  org.apache.hadoop.hive.ql.udf.UDFFromUnixTime with (string). Possible
  choices: FUNC(bigint)  FUNC(bigint, string)  FUNC(int)
  FUNC(int, string)

hive> with t as (select '0' as `timestamp`) select from_unixtime(cast(`timestamp` as bigint)) from t;
OK
1970-01-01 00:00:00


text:
Q: A depth-first search of an undirected graph produces the same number of tree edges I'm trying to show that a depth-first search of an undirected graph always produces the same number of tree edges. I know that this statement does not hold for direct graphs.
What I did: Lets assume that there are two different DFS runs on the same undirected graph G (with n vertices) so the number of tree edges in first run is x and the number of tree edges in second run is y.
Now I want to say that if each DFS run gives us one DFS tree then we know that x=n-1=y which means that our assumption is incorrect. The problem is that each DFS run can return some a few trees and not exactly one so I need to "count" the number of tree edges in each tree.
I also tried to prove the theorem with induction but didn't get any results. Any ideas on how to show it? I also tried to find a full proof online but it looks like it's not an interesting theorem to prove. The only thing I came across with is the counterexample for the direct case.
Disclaimer: I posted this question at SO at first but moved it here because it feel more right to ask it here. Let me know if it's not the right place to ask it.
Tree Edge is an edge which is present in the tree obtained after applying DFS on the graph.

A: if You're original graph is not connected, then your statement is wrong and DFS may produce different "Tree edge counts" on each connected group in your graph unless you want to combine all the spanning Trees together.
but if your original graph is connected it's simple , because of your graph has n nodes. then your Tree also has n nodes and each tree with n nodes has n-1 edges. so
x=y=n-1


text:
Q: Unable to print a doc from specifice printer in Swing I am writing a code that should find list of printers on client machine and set a particulate printer for print a Doc. But I was goggling on net and I found code some think like that:
package org.ui;
import java.io.FileInputStream;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
public class Printing {
    public static void main (String [] args) {
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet ();
        PrintService [] pservices = PrintServiceLookup.lookupPrintServices (flavor, aset);
        try {
            int printer = getPrinter(pservices);
            if(printer == -1) {
                throw new Exception("No network printer found");
            }
            DocPrintJob pj = pservices[0].createPrintJob();
            FileInputStream fis = new FileInputStream ("c:///file.txt");
            Doc doc = new SimpleDoc (fis, flavor, null);
            pj.print (doc, aset);
        }
        catch (Exception ex) {
            ex.printStackTrace ();
        }
    }
    private static int getPrinter(PrintService[] pservices) {
        int printer = -1;
        for(int i = 0; i<pservices.length; i++) {
            if(pservices[i].getName().contains("\\\\")) {
                System.out.println("network printer: " + pservices[i].toString());
                printer = i;
                break;
            }
        }
        return printer;
    }
}

But I am unable to get print on paper, can anyone tell me whats the problem in this code? Its a desktop application.

A: According to the documentation of print()

[...] When the print method returns, printing may not yet have completed as printing may happen asynchronously, perhaps in a different thread. Application clients which want to monitor the success or failure should register a PrintJobListener.

This means that you need to register a PrintJobListener to be able to tell what the problem is:
Try:
pj.addPrintJobListener(new PrintJobListener() {
  @Override
  void printDataTransferCompleted(PrintJobEvent pje) {
    System.out.println("Transfer completed");
  }
  @Override
  void printJobCanceled(PrintJobEvent pje) {
    System.out.println("Cancelled");
  }
  @Override
  void printJobCompleted(PrintJobEvent pje) {
    System.out.println("Completed");
  }
  @Override
  void printJobFailed(PrintJobEvent pje) {
    System.out.println("Failed");
  }
  @Override
  void printJobNoMoreEvents(PrintJobEvent pje) {
    System.out.println("No more events");
  }
  @Override
  void printJobRequiresAttention(PrintJobEvent pje) {
    System.out.println("Check printer");
  }
});

before calling print() and see what gets outputed to the console


text:
Q: How to add method description in Swagger UI in PyCharm with Flask-RESTX I am using Swagger as my API tooling framework and I just found this page: https://petstore.swagger.io/ and saw how each method has a description.
For example: POST: pet/ is described by add a new Pet to the store.
I thought adding this kind of description in PyCharm, using Flask-RESTX. How can I do this? I read the specification page of RESTX, but I didn't find any useful help.

A: You should have a swagger.yml.
summary: <your description here>

Basic Structure


text:
Q: Build Android with no display? Is it possible to build Android for a device without a touchscreen? I have in mind a device with no display at all. This would be similar to Android Things SDK, which is not at all ready yet.

A: Yes, it's possible with Android Things. Displays are optional.

Android Things supports graphical user interfaces using the same UI
  toolkit available to traditional Android applications. In graphical
  mode, the application window occupies the full real estate of the
  display. Android Things does not include the system status bar or
  navigation buttons, giving applications full control over the visual
  user experience.
However, Android Things does not require a display. On devices where a
  graphical display is not present, activities are still a primary
  component of your Android Things app. This is because the framework
  delivers all input events to the foreground activity, which has focus.
  Your app cannot receive key events or motion events through any other
  application component, such as a service.


text:
Q: Dynamics CRM Email entity isReply, isForward replacement in 2013/2015? In Dynamics CRM 2015 Email forms I need to know if email is forwarded, replied etc.
In Dynamics CRM 2011 there used to be JavaScript variables for this e.g. isReply, isForward, isReplyall
These variables doesn't exists in Dynamics CRM 2013/2015.
Is there any alternative to get this information on email form?
Regards
Imran

A: We have to read the subject line of email to see RE: FW:
In addition to that CRM tracking token will be appended at the end of email subject.
If you want to configure for multilingual, use some config to have all the equivalent of RE: FW: of your user base languages in a delimited string to check.


text:
Q: I am a new developer,when I changed the theme to Theme. Material3 during Android development, there was a problem with folding the title bar When I changed the theme to Theme. Material3 during Android development, there was a problem with folding the ActionBar.ToolBar is blocked.
[enter image description here](https://i.stack.imgur.com/VAqlb.png)
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/lin"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/mainbackground">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:fitsSystemWindows="true">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/appbarcolor"
            app:collapsedTitleGravity="center_horizontal"
            app:expandedTitleTextColor="?android:attr/textColor"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:statusBarScrim="@android:color/transparent"
            app:title="注册并开始">

            <ImageView
                android:id="@+id/iv_image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="?attr/mainbackground"
                app:layout_collapseMode="parallax" />

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:contentInsetLeft="0dp"
                app:contentInsetStart="0dp"
                app:layout_collapseMode="pin"/>
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView
        android:id="@+id/nested_scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        ......
    </androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Originally, I used NestScollView for areas other than AppBarLayout. I tried to change it to a separate xml, and found it invalid. I also tried to add android: fitsSystemWindows="true" to her, which is also invalid


text:
Q: Python Libraries not working in Terminal on Mac I was using virtualenv in terminal when my terminal crashed and all my libraries were working fine. All my packages/libraries are in  /Library/Python/2.7/site-packages directory. I am using Python 3.8 I have tried export PYTHONPATH=/Library/Python/2.7/site-packages but this also does not work when I run my programs. I also get this error on certain programs: ImportError: Missing required dependencies ['numpy']-although Numpy is there in path I mentioned earlier. After the terminal crashed I can no longer create virtualenv's either, something is very wrong.

A: use python -m pip install [package] to install all packages.


text:
Q: Fail2ban regex doesn't match my log I'm trying to create a failregex in Fail2ban to find these lines ( and IP addresses ), but I can't write it.
My log lines looks like these:

[Thu Sep 22 10:28:32.215159 2016] [:error] [pid 1616] [client
  83.143.240.13:54895] FastCGI: server "/var/www/cgi-bin/php5-fcgi-104.236.209.45-80-blogginger.com" stderr:
  PHP message: WP login failed for username: admin, referer:
  http://blogginger.com/wp-login.php
[Thu Sep 22 04:38:01.588441 2016] [:error] [pid 24937] [client
  49.151.91.8:58121] FastCGI: server "/var/www/cgi-bin/php5-fcgi-104.236.209.45-80-blogginger.com" stderr:
  PHP message: WP login failed for username: admin, referer:
  http://blogginger.com/wp-login.php

And this is my failregex line in attack.conf:
failregex = [[]client <HOST>[]] WP login failed.*

But it doesn't work. There is not any match.
What is the correct failregex line for find these log lines?
Thank you!

A: Try
failregex = \[client <HOST>:\d+\] .* WP login failed

You can use the fail2ban-regex utility to test regexes against example input files. That's a lot quicker and easier than trying to do this with the live logs.

A: try with
failregex = [[]client <HOST>[]] .*WP login failed.*


text:
Q: Designing a high-amperage, low-voltage AC voltage "breaker" for model train I'm trying to build a simple circuit that acts as a "voltage breaker" – meaning that if a voltage exceeds a certain threshold, analogous to a (current) circuit breaker it will open a circuit.  There are a couple of things that seem to make this a bit challenging because of its application – which is to serve as a speed limiter on a Lionel model train for my young son.  Little boys have a habit of turning the voltage up too high and running a train off the rails.
This implies a few constraints:

*

*The supply to be constrained is AC, operating in the 8 – 16V range.
I'd like to limit the voltage (i.e., train speed) to about 13-14V in
a way that can be adjusted to account for different engines'
operating characteristics.

*The current draw can be up to 5A on a regular basis.  Lionel used
universal motors until very recently and they can draw quite a bit of
current when pulling a consist of cars.  Other accessories also add
to the load as they draw power from the track.

*The circuit needs to be able to withstand occasional (but not rare)
full shorts that last a few seconds, as it is not uncommon to cause a
short for a variety of reasons (such as derailments that connect the
rails).  The variable output transformers used (I have a 1940's Type
V and a 1950's Type ZW, for those who know of such things…) can
output tens of amps when shorted and take a few seconds before
triggering their internal thermal breakers which are usual in the
5-15A range.

Balancing all of these constraints, what I've been able to come up with is the below circuit which:

*

*Creates an AC reference voltage that I don't want my son to exceed.
This is my LimitAC voltage source at the bottom portion of the
circuit.  The do-not-exceed voltage would be set at the transformer
using one of the multiple controls.

*Rectifies the AC in both the reference and track (this is my
TrackLevelAC2 voltage source at the top – more on the "2" in a
second) voltages, which I then…

*…feed into a suitable op-amp comparator (likely a power amp, to
provide the necessary current to actuate the relay's coil).  My
thought is that rectifying both sources will make the comparison
straight-forward.

*When the track voltage exceeds the reference voltage, have the op-amp
feed a separate 12V DC supply that triggers a NC relay to open the
track circuit (ActualTrackAC1 and ActualTrackAC2).  I'm simulating
the relay with just a voltage controlled switch at this point.

A few questions/suppositions:

*

*I've had to set up two identical voltage sources for the track to get
the full AC waveform instead of the rectified AC waveform. In the
real world, if ActualTrackAC1 and ActualTrackAC2 were one and the
same, wouldn't the track and the rectifier-to-op-amp portions both be
able to operate independently?  Related to this…  EDIT: simple reference question.

*…LTSpice doesn't power ActualLoad (which I've set at 4 ohms, a
reasonable approximation for an engine) as I'd expect.  In the real
world I would be drawing a couple of amps from the transformer, not a
few microamps.  What am I missing here?  Isn't an LTSpice voltage
component an "ideal" voltage source and thus capable of feeding
whatever current is required into the track circuit?  EDIT: simple .model error now corrected.

*Do I really need to rectify the sources to get the opamp to function
correctly?  If I don't, it would seem that the comparison will work
as intended on the positive half-wave but fail in the negative
half-wave (since the reference will be higher, i.e., less-negative,
than the track).

This all seems overly complicated given the conceptual simplicity of the goal, but given that I'm working with higher amperage AC and need to be able to withstand short circuits I seem unable to use solutions that are DC based, for low amperage, or are not very happy with full shorts (e.g., a simple Zener clipper – N.B. I'd settle for a clipper-type circuit instead of a breaker...)  This cannot be an uncommon need, but since I'm just a casual hobbyist – am I missing something?  Is there any way to improve this circuit?

A: I'd be tempted to go into the digital domain, but if you don't want to do that, what I'd suggest is to divide down the measured voltage with a voltage divider, rectify it, low pass filter it, and then compare it with a DC reference. An AC reference will be out of phase!
You can then change the voltage divider to set the target voltage, rather than having to set the reference. LEDs can be used as budget references since the whole thing doesn't need to be too accurate.
This has the added advantage that you can feed the measured voltage to a DC panel meter and draw a red line on it at the trip threshold.
Consider also having a latching relay that needs to be manually cleared, or is cleared when the voltage goes below a much lower threshold. That way it doesn't start up at full voltage.

A: I've done such "kid excitement limiters" before, and the simplest solution is mechanical if at all possible. Limit how far a knob can turn, how far a lever can swing, etc. This works not only for electrical controls but also for things like valves, throttle pedals in electric ride-on toys, etc. If you're looking for an excuse to buy a 3D printer - this may be it!
Otherwise, conceptually, such a circuit could be as follows:

simulate this circuit – Schematic created using CircuitLab
The rectifier can be Schottky-diode based, or using an ideal diode controller. The buck can be any reasonably high frequency (say 100kHz) buck circuit, set up for 18VDC output. When the input voltage is below \$\sqrt{2}\cdot 13{\rm\, V}\$, the switch in the buck regulator turns on continuously, and shorts input to the output directly. When the AC peak voltage starts exceeding 18V, the buck starts efficiently limiting the voltage, without stopping the train nor dissipating much heat.
The capacitors on the buck input and output can be fairly small and will have no effect at 50Hz. The buck will work fine with a variable input voltage as long as it has an auxiliary supply voltage available. An external "wall wart" can be used for that, or an accessory supply from the train transformer, etc.
The inverter is a basic H-bridge - the ones used for higher power stepper motors will work well for this.
The zero detector can be whatever you can think up :)
The buck frequency has to be selected not to interfere with digital communications used on the track (if any).
The concept can be simplified by using two bucks in parallel - one for positive, another for the negative voltage.

simulate this circuit
Instead of a full rectifier bridge and a full H-bridge, we only need half-bridges. The load is distributed between the two buck regulators, too.


text:
Q: Upload and read a txt file in zend without saving it I was wondering if its way in zend 1.12 that I can use to upload a txt file, read and make some parsing without have to save this file somewher.
I already have the upload form for that:
<form enctype="multipart/form-data" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
        Chose your file: <input name="uploadedfile" type="file" />
    <br />
    <input type="submit" value="Upload File" />
</form>

And also I've in the action:
function managementaccountingAction() {
        Zend_loader::loadClass('Zend_File_Transfer_Adapter_Http');
        if ($this->getRequest()->isPost()) {
            $adapter = new Zend_File_Transfer_Adapter_Http();
            //$adapter->setDestination('C:\temp');
            //$files = $adapter->getFileInfo();
            if (!$adapter->receive()) {
                $messages = $adapter->getMessages();
                echo implode("\n", $messages);
            }
        }
    }

Any suggestions?
Thanks

A: You will need to save the file somewhere to do operations on it but you can delete it afterwards.  In order to delete it, you can use the PHP unlink function.


text:
Q: how to change url management flow in yii i have implementing the project in yii. i done my project but i want to change instead of id to name. ie url management. i did uncomment in config.php then i added the following code. those follows:
my table name is recipe:
public function loadModel($id)
{
    $model=Recipe::model()->findByPk($id);
    if($model===null)
        throw new CHttpException(404,'The requested page does not exist.');
    return $model;
}

     public function loadModel2($name)
{
            $model=Recipe::model()->find('t.name=:name', array(':name' => $name));
    if($model===null)
        throw new CHttpException(404,'The requested page does not exist.');
    return $model;
}

except this i added top of the sitecontroller use Recipe. but it shows error is
The use statement with non-compound name 'Recipe' has no effect
please suggest me suitable answer

A: I personally use in my projects something like /product-name/p/1 and this is SEO friendly. To get your links to look like that you have to first change your url rules
    'urlManager' => array(
        'urlFormat' => 'path',
        'showScriptName' => false,
        'urlSuffix' => '/',
        'rules' => array(
            '<title:.*?>/p/<id:\d+>'=>'product/view',
        ),
    ),

Then use this to create your URLs.
Yii::app()->createUrl('product/view',array('id'=>$model->id, 'title'=>$model->name))

Now it works both ways, the create url will always create urls like /product-name/p/1 and further more you can show the product the normal way
/**
 * Displays a particular model.
 * @param integer $id the ID of the model to be displayed
 */
public function actionView($id)
{
    $model = $this->loadModel($id);
    $this->render('view',array(
        'model'=>$model,
    ));
}


text:
Q: Download Excel file into Unprotected View I am running a website written in ASP.net and any Excel file you download gets downloaded in Protected View. This causes an extra few clicks for the user to be able to edit it.
How can I alter this so the files always are downloaded in Unprotected View?

A: It is possible IF you have control over the computers who can download from your website. Than you can add your website to the trusted websites and everything will work fine.
How to do it, you have to google - our Admins had to google a lot to find it out, and I do not know the details :/

A: Check out the following links:

*

*Disable Protected View in Office 2010,
https://amsterdam.jira.com/wiki/display/MAN/How+to+disable+protected+view+in+Excel+2010

*Disable Protected View in Office 2007 and 2010 by using Trust
Settings,
http://helpmerick.com/solution-to-microsoft-outlook-2007-or-2010-not-opening-word-or-excel-attachments.htm

*How to edit your Excel settings.
http://office.microsoft.com/en-us/excel-help/what-is-protected-view-HA010355931.aspx
What is Protected View?
"Files from the Internet and from other potentially unsafe locations can contain viruses, worms, or other kinds of malware, which can harm your computer. To help protect your computer, files from these potentially unsafe locations are opened in Protected View. By using Protected View, you can read a file and inspect its contents while reducing the risks that can occur."
Why is my file opening in Protected View?
Protected View is a read-only mode in which most editing functions have been disabled. There are several reasons why a file opens in Protected View:
The file was opened from an Internet location - When you see the message in Protected View that states This file originated from an Internet location and might be unsafe. Click for more details., this is because the file is being opened from the Internet. Files from the Internet can have viruses and other harmful content embedded in them. We recommend that you edit only the document, if you trust its contents.
The file was received as an Outlook 2010 attachment and your computer policy has defined the sender as unsafe - When you encounter the message in Protected View that states This file originated as an e-mail attachment and might be unsafe. Click for more details., this is because the file was received from a potentially unsafe sender.
The file was opened from an unsafe location - When you encounter the message in Protected View that states This file was opened from a potentially unsafe location. Click for more details. the file was opened from a folder that is unsafe. An example of an unsafe location is your Temporary Internet Files folder.
The file is blocked by File Block
File validation failure - When you encounter a message in Protected View that states Office has detected a problem with this file. Editing it may harm your computer. Click for more details. It has occurred because the file did not pass file validation.
NOTE - You can learn more about file validation failures in Problem detected with a file.
The file was opened in Protected View by using the Open in Protected View option.     When you encounter the message in Protected View that states This file was opened in Protected View. Click for more details., this is because you chose to open the file in Protected View. This can be done by using the Open in Protected View option: Click the File tab. In the Microsoft Office Backstage view, click Open. On the Open dialog box, click the arrow on the Open button. From the list, select Open in Protected View. The following image is an example of Protected View appearing when Open in Protected View is selected.
 IMPORTANT   System administrators can extend the list of potentially unsafe locations to include additional folders also considered unsafe."


text:
Q: (MacBook Late 2009) Bootcamp/Win 7: No device drivers were found Recently I've been trying to install Windows 7 on my MacBook (Late 2009, macOS El Capitan, 10.11) using BootCamp.
However, when I'm about to install windows 7 it shows an error: "No device drivers were found", I've tried using this which are the drivers for the Late 2009 iMac, and even the drivers that are downloaded from BootCamp are also not detected, the Pen drive that I use is a 16gb USB 3.0 device.
I'm using a DVD to install Windows 7 Professional x64 with SP1.
Error Shown: Load driver: A required CD/DVD drive device driver is missing. If you have a driver, floppy disk, CD, DVD, or USB flash drive, please insert it now.
Note: If the windows installation media is in the CD/DVD drive, you can safely remove it for this step


text:
Q: React-native android toolbar going below status bar I am trying to set a status bar colour in react native. I am using react-native-material-ui for the toolbar component. My problem is that whenever I am setting status bar colour, the toolbar is moving up and below the status bar.
See the screenshots below:

I am using the following:
const uiTheme = {
    palette: {
        primaryColor: COLOR.green500
    },
    toolbar: {
        container: {
            height: 56
        }
    }
};

export default class RecentChatListScreen extends Component
{
    render() {
        return (
            <ThemeProvider uiTheme={uiTheme}>
                <View>
                    <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                    <Toolbar
                        leftElement="menu"
                        centerElement="Hola"
                        searchable={{
                            autoFocus: true,
                            placeholder: 'Search your chats',
                        }}
                        onLeftElementPress={() => this.props.navigation.navigate('DrawerOpen')}
                    />
                    <Text>List of recent chats.</Text>
                    <Button onPress={() => this.props.navigation.navigate('Chat')} title="Go to Chat"/>
                </View>
            </ThemeProvider>
        );
    }
}

A: In case any one facing the issue with expo, just add "paddingTop: Expo.Constants.statusBarHeight" in the root view of your App component
render() {
    return (
      <View style={styles.container}>
      //other components
      </View>)
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
    paddingTop: Expo.Constants.statusBarHeight
  }
});

A: Instead of using Expo-specific code, use the constant provided by react-native, in StatusBar. According to the documentation, StatusBar.currentHeight is only provided for Android implementations. I have not verified that the iOS version returns 0 versus undefined.
const uiTheme = {
    palette: {
        primaryColor: COLOR.green500
    },
    toolbar: {
        container: {
            height: 56,
            paddingTop: StatusBar.currentHeight || 0
        }
    }
};

A: As per the demo app here you should use a view of statusbar's height to avoid overlay. Like the code below after StatusBar:
<View style={{ backgroundColor: COLOR.green500, height: 24 }} />