text:
Q: Angular2 loading compoents dynamically fails I would like to load components duynamically in my view and this is what i have tried
in my html file
<p>
 <dynamic-component [componentData]="componentData"></dynamic-component>
</p>

Then in my ts file i have
export class ChatCmpComponent implements OnInit {
 private componentData = null;

 ngOnInit() {
  this.componentData  = {
    component: ChatInitButtonComponent,
  };
}

Now am getting an error
Can't bind to 'componentData' since it isn't a known property of 'dynamic-
component'.

1. If 'dynamic-component' is an Angular component and it has
'componentData' input, then verify that it is part of this module.

What could be wrong, how do i dynamically load components

A: you need to use ng-template and create a custom directive that will allow you to inject your component via a reference to a ViewContainerRef
for more information and an example, try here:
https://angular.io/guide/dynamic-component-loader


text:
Q: Stop jQuery parenting I simply have some html code that works fine but when I add the jQuery UI library, it also adds its own classes to my original element classes.
However, this is not a problem but it also parents some elements meaning that it adds a div parent to those (some) elements.
This prevents the css rules of those elements from taking effect and also requires to rewrite the entire code to include the added jquery classes and parent element tags.
Am using absolute css target paths to style these elements like so...
div#searchAPI>div.a>input{
    font-size:18px !important;
    color: #585858;
    padding:0 60px 0 50px;
    border:0  !important;
    outline: none !important;
    text-decoration: none;
    background: red;
}

And the target element would be....

        <input type="text">

But when the jQuery UI lib is added, it adds it own custom parent to the input tag element like...

            <input type="text">

Any sugguestions to how I can get rid of the extra parenting effect  are greatly appreciated, thanks...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to bind function as a property of object I have a function which takes an object property, in this object I want to pass a function as one of the properties. I will like to execute the function when the property is called. I need to bind the function as the this context is lost before the function will be executed.
    var myfunction = function () {
       console.log("Something");
    }

    // this works
    this.HeaderService.setState({
      leftButton: {
        click: this.myfunction.bind(this)
      }
    });

    // can't get this to work
    const self = this;
    this.HeaderService.setState({
      leftButton: {
        click() {
           return (function () {
              console.log("something");
           }).bind(this)
        }
      }
    })

I can get the function expression to work, but I cant get the second case where I want to define the function as the value of the property click. How do i do this?

A: Continuing what @JamieTorres suggested an arrow function fixes the issue
 const self = this;
   this.HeaderService.setState({
      leftButton: {
        click: () => {
           return (function () {
              console.log("something");
           }).bind(this)
        }
      }
    })


text:
Q: Mongodb query to find element value type of nested array or object in a field I have mongodb data model where I have some array fields that contain embedded objects or arrays.  I have some inconsistencies in the field in question because I've tweaked my application logic.  Initially, my model looked like this:
Initial Setup of Results collection
"competition" : "competition1",
"stats" : [
    {
        "stat1" : [],
        "stat2" : []
    }
]

However, I saw that this wasn't the best setup for my needs.  So I changed it to the following:
New Setup of Results collection
"competition" : "competition1",
"stats" : [
    {
        "stat1" : 3,
        "stat2" : 2
    }
 ]

My problem now is that documents that have the initial setup cause an error.  So what I want is to find all documents that have the initial setup and convert them to have the new setup.
How can I accomplish this in mongodb?
Here is what I've tried, but I'm stuck...
db.getCollection('results').find({"stats.0": { "$exists": true }})

But what I want is to be able to do something like
db.getCollection('results').find({"stats.0".stat1: { "$type": Array}})

Basically I want to get documents where the value of stats[0].stat1 is of type array and override the entire stats field to be an empty array.
This would fix the errors I'm getting.

A: $type operator for arrays in older versions works little differently than what you might think than $type in 3.6.
This will work in 3.6
db.getCollection('results').find( { "stats.0.stat1" : { $type: "array" } } )

You can do it couple of ways for lower versions and It depends what you are looking for.
For empty arrays you can just check
{"stats.0.stat1":{$size:0}}

For non empty arrays
{"stats.0.stat1": {$elemMatch:{ "$exists": true }}}

Combine both using $or for finding both empty and non empty array.
For your use case you can use below update
db.getCollection('results').update({"stats.0.stat1":{$size:0}}, {$set:{"stats":[]}})


text:
Q: Programmatically Restore a Microsoft SQL Server Database I wish to use ColdFusion to grab a database backup from a live server and restore it into a test environment. The grabbing bit is done, but I can't find a way of restoring the database programatically forcibly overwriting the database if its already there.
Any help would be appreicated, I figured there should be some SQL script or batch file that could do the job for me.
Obviously windows environment. SQL 2008, ColdFusion 9.

A: ----Put database into single user mode (terminates open connections - else restore fails)
ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE

RESTORE DATABASE YourDB
FROM DISK = 'D:\temp\YourDB.bak'
WITH REPLACE
,MOVE 'YourDB_Data' TO 'C:\Program Files\Microsoft SQL Server\MSSQL\Data\YourDB_Data.mdf'
,MOVE 'YourDB_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL\Data\YourDB_Data.ldf'

ALTER DATABASE YourDB SET MULTI_USER
GO


text:
Q: How do actions work with routes for rendered views? Can someone tell me why "Action" does not work here?  Has it got to do with my route?
{{#linkTo "content.friend" this}}
http://jsbin.com/EtOjuTe/17
http://jsbin.com/EtOjuTe/19 (Here is the version with it uncommented and thus no output)
Thank you.

A: The first argument to linkTo is the name of the route that you want to link to.  You don't have a route called content.friend, so Ember fails when trying to build the link.
I would expect that you would want to use contact.friend, but that's not working either.  I think this is due to the jsbin being set up with an old version of Ember.  I can get it to at least build the link by using just friend.  Since the friend route is nested under contact that means Ember needs two models to be involved in the link.
Since the contact is attached to the friend model as who, you can do this:
{{#linkTo "friend" who this}}

That gets the link to build, but the id for contact is undefined.  Again I suspect that an old version of Ember is at fault.
Here's the Ember docs about linking to routes with multiple dynamic segments.  http://emberjs.com/guides/templates/links/#toc_example-for-multiple-segments
Here's a semi working jsbin : http://jsbin.com/OdoHaGi/1/edit


text:
Q: Form xml element from SQL Server table I want to convert the sql table records into below xml format. Can you please give your suggestions in it.
SQL Server table:
id  name
-------------
1   Arun
2   Raghavan

I want to form the xml elements from the above table like the below format in a SQL query
<row>
    <Field Name="Customer.id" Value="id">
    <Field Name="Customer.name" Value="arun">
</row>

A: I think you need something like
SELECT 'Customer.id' AS [@Name]
      ,id AS [@Value]
FROM SomeTable
FOR XML PATH('Field'),ROOT('row');

If you really need this with the table's and the column's name concatenated like in your example, there is no easy-going. In this case John Cappelletti's answer is great!
But check these out-of-the-box approaches (AUTO will generate the table's name as element's name):
CREATE TABLE SomeTable (id int,name varchar(50))
INSERT INTO SomeTable VALUES
 (1,'Arun')
,(2,'Raghavan');

SELECT * FROM SomeTable FOR XML AUTO;
SELECT * FROM SomeTable FOR XML RAW;

--Result for first
<SomeTable id="1" name="Arun" />
<SomeTable id="2" name="Raghavan" />

--Result for second
<row id="1" name="Arun" />
<row id="2" name="Raghavan" />

A: This is where my thinking takes me.
This is a dynamic unpivot which is then converted back into a consolidated XML object.
I added Cross Apply C to hold the table name, but this can be a variable.
Declare @YourTable table (id int,name varchar(50))
Insert into @YourTable values
(1,'Arun'),
(2,'Raghavan')

Select D.*
 From  @YourTable A
 Cross Apply (Select XMLData=cast((Select A.* for XML Raw) as xml) ) B
 Cross Apply (Select TableName='Customer') C
 Cross Apply (
                Select row = (
                                Select [@Name]   = C.TableName+'.'+attr.value('local-name(.)','varchar(100)')
                                      ,[@Value]  = attr.value('.','varchar(max)')
                                 From  B.XMLData.nodes('/row') as A(r)
                                 Cross Apply A.r.nodes('./@*') AS B(attr)
                                 For XML Path('Field'),Type
                              )
            ) D
 For XML Path(''),Type

Returns
<row>
  <Field Name="Customer.id" Value="1" />
  <Field Name="Customer.name" Value="Arun" />
</row>
<row>
  <Field Name="Customer.id" Value="2" />
  <Field Name="Customer.name" Value="Raghavan" />
</row>

A: I place this as a second answer, as the approach is so completely different:
First I use SELECT ... FOR XML AUTO. This will create simple tags, where the table's name is the element's name and all fields are generated as attributes.
From this I continue with a FLWOR XQuery. First I read all nodes, then all attributes within the nodes. This is re-generated as the XML needed:
CREATE TABLE SomeTable (id int,name varchar(50))
INSERT INTO SomeTable VALUES
 (1,'Arun')
,(2,'Raghavan');

--The query (you can place any table's, view's or TVF's name instead of "SomeTable")
SELECT
(
SELECT * FROM SomeTable FOR XML AUTO,TYPE  --<-- Here is the simple SELECT
).query('
         for $nd in /*
         return <row>
         {
             for $attr in $nd/@*
             return <Field Name="{concat(local-name($nd),".",local-name($attr))}" Value="{$attr}"/>
         }
         </row>');
GO
--Clean up (careful with real data!)
--DROP TABLE SomeTable;
GO

The result
<row>
  <Field Name="SomeTable.id" Value="1" />
  <Field Name="SomeTable.name" Value="Arun" />
</row>
<row>
  <Field Name="SomeTable.id" Value="2" />
  <Field Name="SomeTable.name" Value="Raghavan" />
</row>


text:
Q: Get list of all checked nodes and its subnodes in treeview I have a treeview list check boxes and the list contains nodes, subnodes and in some cases subnode of subnode. When user check some items i want to get list of selected items.
On this why I get only selcted items of main node:
 foreach (System.Windows.Forms.TreeNode aNode in tvSastavnica.Nodes)
        {
            if (aNode.Checked == true)
            {
                Console.WriteLine(aNode.Text);
            }
        }

How to travers through whole treeview and get checked items in subnodes?

A: public void GetCheckedNodes(TreeNodeCollection nodes)
{
    foreach(System.Windows.Forms.TreeNode aNode in nodes)
    {
         //edit
         if(!aNode.Checked)
             continue;

         Console.WriteLine(aNode.Text);

         if(aNode.Nodes.Count != 0)
             GetCheckedNodes(aNode.Nodes);
    }
}

You don't make look back into the child notes, using recursion you can do it.
You need method like this ! In your code just call once GetCheckedNodes(tvSastavnica.Nodes) and all checked nodes should be displayed !

A: my way:
void LookupChecks(TreeNodeCollection nodes, List<TreeNode> list)
{
    foreach (TreeNode node in nodes)
    {
        if (node.Checked)
            list.Add(node);

        LookupChecks(node.Nodes, list);
    }
}

useage:
var list = new List<TreeNode>();
LookupChecks(TreeView.Nodes, list);

A: If you like LINQ, you can create an extension method that traverses the whole treeview:
internal static IEnumerable<TreeNode> Descendants(this TreeNodeCollection c)
{
    foreach (var node in c.OfType<TreeNode>())
    {
        yield return node;

        foreach (var child in node.Nodes.Descendants())
        {
            yield return child;
        }
    }
}

Then you can perform every operations you want using LINQ. In your case, getting a list of selected nodes is easy:
var selectedNodes = myTreeView.Nodes.Descendants()
                    .Where(n => n.Checked)
                    .Select(n => n.Text)
                    .ToList();

An advantage of this approach is it is generic.
However, because the Descendant() method traverses the whole tree, it might be a bit less efficient than the answer given by @mybirthname because it only cares about nodes that are checked with their parents. I dont known if your use case includes this constraint.
EDIT: Now @mybirthname answer has been edited, it is doing the same. Now you have the loop and the LINQ solution, both are recursive.


text:
Q: Modify Devise to check for permission to register? My app has a Permission model and permissions table with an email field. Existing users (User model) can add the email addresses of people who they would like to invite to view their information. Those email addresses are stored in the permissions.email field in the database.
How do I go about modifying Devise's registration process so that it only allows people with an email address in the permissions table to create an account?

A: did this before with a validator on the user model; e.g.
validates :email, :my_access_control => true

and then create something like this
class MyAccessControlValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    if ... not in permissions table..
      ... add to objects error collection why they cannot register
    end
  end
end


text:
Q: ArcGIS Javascript API Printing issue I am trying to print the ArcGIS JS API Web Map in Large prints (ANSI D, ANSI E) by using as per below code:
https://developers.arcgis.com/javascript/jssamples/widget_print_esri_request.html
The issue what I am facing is the print out which is on the map are shrinking on large pints outs, but coming properly in small prints (A4 and A3).
I tried below options, but no proper results are coming.
1.printTemplate.exportOptions = { width: map.width, height: map.height,                        dpi: 96 };
2.printTemplate.preserveScale = false;

A: It sounds like you may be requesting map image of higher resolution than can be exported from an ArcGIS service by default, for example (https://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/MapServer):
MaxImageHeight: 4096
MaxImageWidth: 4096
For ANSI E the longer side is 44'', which, at 96 dpi, corresponds to 4224 dots. I am not sure why ANSI D is not exporting properly, but, as Suttikeat Witchayakul suggested, providing the rest of printing parameters as well as the service(s) URL(s), which you are trying to export map from, may help.
The maximum image size that can be exported from a service can be specified at time the service is published. Alternatively, a lower resolution map image can be requested to prevent unexpected shrinking.

A: You need to customize or create new print template located at
..\ArcGIS\Server\Templates\ExportWebMapTemplates\ folder and restart print service.
now your new template will be added to the dropdown list of print templates.


text:
Q: windows stops working when upgrading to XP service pack 3 i have a laptop that i upgraded to windows XP service pack 3 (as i wanted to install some software that required SP3).  after installing it, and rebooting, my machine slowed down dramatically.  even with essentially nothing running, i couldn't bring up the task manager, the task bar at the bottom of the machine kept freezing and disappearing and overall it was essentially unusable.  I just tried uninstalled SP3 from Add/Remove Programs and rebooted and everything seems to work fine now.
is there any suggestions on why my windows XP laptop wont work after installing XP SP3.
in terms of the software that i have installed, its pretty bare:

*

*Internet Explorer 8

*Firefox

*McAfee Enterprise VirusScan

*MS Office (excel, word, etc)

any suggestions would be great because not having XP SP3 is a bottleneck in allowing me to install some new software that i would like to run.

A: Uninstall McAfee first, then install SP3, see if it runs well without McAfee, then decide what AV to install.


text:
Q: Relational database management system, not for server but client-side I am making a relational database for a friend who is not tech savvy.  I am looking for something that she can upload the correctly formatted excel files into and be able to see the relationships clearly.

(<1>[John Smith]<2>[Sam Jones] rather than <1><6><2><244>, etc.)

I know I can make my own web-based system but I was not sure if there was an open source (or freely available) system already available, either desktop-based or web-based.  I tried googling it but I am afraid that I am using the wrong keywords.  (I only got server-side systems)
Any thoughts?

A: It's ugly and expensive, but MS/Access does this well.  It's good for beginners and Excel integrates very well.  If she has Office Professional she already has it. It also supports ODBC so it can use other database engines.

A: As far as desktop DBMS goes, as Peter Wooster pointed out (+1) MS Access is the most user friendly for people who are used to Office (e.g. especially Excel).
If you are thinking of building something with a web GUI (i.e. with ASP.NET) then you can get SQL Server Express for free and it can be deployed on a client PC.
There are other typically server-based RDBMS systems with workstation-friendly editions, such as MySQL and even Oracle (although there is nothing friendly about Oracle, workstation or otherwise).


text:
Q: Difference between Minicart and Cart in Magento 2 I want to know the difference between Mini cart and Cart in details.

A: There are no major differences between cart and MiniCart.
There the are same entity of same module Magento_Checkout  & Magento_Quote
The main difference between two is that MiniCart showing to all page at header top right corner` and  Where Cart is a specific Page where current basket's all item of a current customer is shown.
Another difference, No of item show at the mini cart is limit,  depends on the setting.
Where at cart page show, basket all items.
If you are a developer, then there are main different two is that
MINicart data manage using https://devdocs.magento.com/guides/v2.3/extension-dev-guide/cache/page-caching/private-content.html
And where Cart page data depends on  Block class and layout files.


text:
Q: Yii2: How to show checked values in CheckboxList I want to show checked values in my checkboxlist in Yii 2.0. Following is my code:
Main Array:
<?php
$featureArr = array(
    'Change Requester' => 'Change Requester',
    'Clone Request' => 'Clone Request',
    'Suspend Request' => 'Suspend Request',
    'In-Process Requests Open in Edit Mode' => 'In-Process Requests Open in Edit Mode',
    'Allow On-the-Fly Notifications' => 'Allow On-the-Fly Notifications',
    'Additional Comments Field' => 'Additional Comments Field',
    'Do Not Validate Draft Requests' => 'Do Not Validate Draft Requests',
    '(Web-Only) Allow File Attachments' => '(Web-Only) Allow File Attachments',
);

Getting data from table to display checked items:
$formFeatureModel = FormFeatureForm::find()->where("form_id=" . $model->id)->all();

$checkedFeatureArr = array();
foreach ($formFeatureModel as $data) {
    $checkedFeatureArr[$data->feature] = $data->feature;
}
?>

Checkbox field
<?= $form->field(new FormFeatureForm, 'feature')->checkboxList($featureArr, ['class' => 'featureCls']) ?>

I am getting checked item in $checkedFeatureArr from database. Now I just want to show checked items. So, Where should I pass $checkedFeatureArr array? Getting stuck in this.
Any help would be appreciated.

A: When using it with model, you should fill feature model property with selected values instead.
$model->feature = $checkedFeatureArr;

Then it will be checked automatically.
Additional tips:

*

*It's better avoid concatenation in SQL, replace ->where("form_id=" . $model->id) with ->where(['form_id' => $model->id]).

*It's better create ActiveForm before rendering ActiveField.


text:
Q: Why is IntelliJ switching to one specific class anytime I try to run or debug anything? I am working on a project in IntelliJ where I need to make three methods in a class called Lab7, and then test all three in a separate class called Lab7Test. The code for Lab7 is from me, but the test class was given to us from our professor because we havent learned about junit and that seems to be how the tests are being run. Here is Lab7:
package Lab7;
import java.util.Scanner;

public class Lab7 {
    public static void main(String[] args){
        // variable declarations for part 1
        String title;
        String firstName;
        String lastName;
        Scanner in = new Scanner(System.in);

        // prompt for input for part 1
        System.out.print("Enter a title:");
        title = in.next();
        System.out.print("Enter your first name:");
        firstName = in.next();
        System.out.print("Enter a your last name:");
        lastName = in.next();

        // call the method for part 1
        greeting(title, firstName, lastName);

        // variable declarations for part 2
        int number1;
        int number2;

        // user prompts for part 2
        System.out.print("Enter first number:");
        number1 = in.nextInt();
        System.out.print("Enter second number:");
        number2 = in.nextInt();

        // call the methods max and sumTo inside the println statement
        System.out.println("The largest number is " + max(number1, number2));
        System.out.println("The sum of the numbers is " + sumTo(number1, number2));
    }
    /******************** greeting method goes here*********************/
    public static void greeting(String title, String firstName, String lastName) {
        System.out.println("");
        System.out.println("Dear " + title + " " + firstName + " " + lastName + ",");
        System.out.println("");
    }
    /***********************end of method*************************/

    /******************** max method goes here*********************/
    public static int max(int num1, int num2){
        if(num1 >= num2){
            return num1;
        }
        else{
            return num2;
        }
    }
    /***********************end of method*************************/

    /******************** sumTo method goes here*********************/
    public static int sumTo(int num1, int num2) {
        int counter = 0;
        int sum = 0;
        if(num1 == num2){
            sum = num1;
        }
        else if (num1 > num2) {
            counter = num2;
            while(counter != num1 + 1){
                sum = sum + counter;
                counter++;
            }

        }
        else if (num1 < num2){
            counter = num1;
            while(counter != num2 + 1){
                sum = sum + counter;
                counter++;
            }

        }
        return sum;
    }
    /***********************end of method*************************/
}

And heres Lab7Test:
import static org.junit.Assert.assertEquals;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Lab7Test {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();

    @Before
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));
    }

    @Test
    public void greetingTest() {
        Lab7.greeting("Mr.", "Buzz", "Lightyear");
        String rawOutput = outContent.toString();
        String[] outputLines = rawOutput.split("\n");
        assertEquals("", outputLines[0]);
        assertEquals("Dear Mr. Buzz Lightyear,", outputLines[1]);
    }

    @Test
    public void max10and2Test() {
        int max = Lab7.max(10, 2);
        assertEquals(10, max);
    }

    @Test
    public void max2and10Test() {
        int max = Lab7.max(2, 10);
        assertEquals(10, max);
    }

    @Test
    public void max50and50Test() {
        int max = Lab7.max(50, 50);
        assertEquals(50, max);
    }

    @Test
    public void maxMinus10andMinus2Test() {
        int max = Lab7.max(-10, -2);
        assertEquals(-2, max);
    }

    @Test
    public void maxMinus2andMinus10Test() {
        int max = Lab7.max(-2, -10);
        assertEquals(-2, max);
    }

    @Test
    public void max0and0Test() {
        int max = Lab7.max(0, 0);
        assertEquals(0, max);
    }

    @Test
    public void sumTo2and10Test() {
        int max = Lab7.sumTo(2, 10);
        assertEquals(54, max);
    }

    @Test
    public void sumTo10and2Test() {
        int max = Lab7.sumTo(10, 2);
        assertEquals(54, max);
    }

    @Test
    public void sumTo50and50Test() {
        int max = Lab7.sumTo(50, 50);
        assertEquals(50, max);
    }

    @Test
    public void sumToMinus10andMinus2Test() {
        int max = Lab7.sumTo(-10, -2);
        assertEquals(-54, max);
    }

    @Test
    public void sumToMinus2andMinus10Test() {
        int max = Lab7.sumTo(-2, -10);
        assertEquals(-54, max);
    }

    @Test
    public void sumTo0and0Test() {
        int max = Lab7.sumTo(0, 0);
        assertEquals(0, max);
    }

    @After
    public void cleanUpStreams() {
        System.setOut(null);
        System.setErr(null);
    }
}

Now, I should mention that I have to do the same thing with a different program(test the methods from one class in a different class) and it went really smoothly. The programs are called DebugLab and DebugLabTest, and I didn't have any trouble getting DebugLabTest to run the methods provided. When it comes to Lab7Test, however, the class does not recognize "Lab7" in any usage of "Lab7.(method)" and provides a cannot find symbol error code. not only does it not recognize Lab7 (which is in the same package), but any time I try to run any of the other three programs I've listed IntelliJ will jump straight back to Lab7Test and print the error codes. I have tried running the other programs from the run tab at the top, from the lightbulbs that appear beside class names, and from the buttons for running and debugging in the upper right. All of these yield the same result, the only way I have been able to run them is by deleting Lab7Test.

A: If I got your question right, class Lab7Test does not compile because it cannot file class Lab7.
If there is at least one compilation error, the whole project compilation will fail. This is how it works in a Java world, and intelliJ also works like this.
Since Tests are executed after the compilation (after all tests is driven by a regular java process, read, JVM spawned for this purposes) that obviously works with binary code, so you have compile the stuff first.
Now, say you have a complication error in Lab7Test. Since the compilation fails, this means that you won't be able to run any test in that module including DebugLabTest of course.
When you deleted the Lab7Test the error gone so you can proceed.
So far so good, now in terms of resolution.
You should always check what exactly the compilation errors are. The java compiler is really a "clever" piece of software and it can help you to resolve the error.
You haven't posted the actual compile error in Lab7Test class, but I guess it fails to file Lab7
If so, you should make sure that they reside in the same package. Because if they don't, Lab7Test must contain a line with an "explicit" import of Lab7. It looks like it doesn't, and the class Lab7Test resides in a default package (the is no line like package abc; in the File Lab7Test. So make sure that Lab7 also resides in the same (default) package, or alternatively add the line import foo.bar.Lab7; to Lab7Test.java assuming you really want Lab7 file to reside in the package foo.bar
P.S. this answer might probably look too scrupulous but obviously its asked by a person who does his/her first steps in programming, so it was by intention :)


text:
Q: Neil deGrasse Tyson says that electrons "teleport" between energy levels? This page:
https://blog.afach.de/?p=62
Discusses the error Neil deGrasse Tyson made when talking about electronic transitions (video included there). Tyson clearly said in his Cosmos series that electrons disappear from one level and appear in the other one.
The guy in the page discusses that this is wrong, because there is no proof of that, and because it breaks simplest rules of relativity, and because it contradicts the simplest quantum model.
Is his argument correct? And why would Tyson do such a horrible mistake?
For more information please visit the link.

A: Tyson claims that an electron disappears from one orbital and appears in another and claims that this is like going from the second floor of a building to the fourth floor without existing in between. This doesn't actually happen. What happens instead is that each possible state of the system has a continuous amplitude associated with it. In a transition from state 1 to state 2, the amplitude of state 1 continuously decreases over time while that of state 2 continuously increases. These states overlap in space and so there is no mysterious magical mystery about an electron hopping from one place to another or anything like that. There is just continuous evolution of continuous amplitudes of the discrete set of states in which the electron can be found upon measurement.
The confusion about this kind of issue is a result of the mess that is usually made of discussing how quantum mechanics should be understood when it comes to measurement. The standard story is that the state of a quantum system jumps or collapses into one of the possible outcomes on measurement, but this is false. A more accurate description goes like this. A measurement has to create information that can be freely copied so that where is was previously present only in one system it latterly becomes present in many. It is not necessarily true that the system that was originally measured has its state copied. The state can be wiped instead, it can be reset to some default state. But the measurement result itself has to be able to be copied, otherwise you can't discuss it because to know about it you have to copy it into your brain. And information that can be copied in this way is discrete and the copying process prevents interference, see
http://arxiv.org/abs/1212.3245.
Even this paper is not as clear as it should be. The author should state that in fact the state doesn't jump or collapse, it just evolves according to the appropriate equations of motion. The observer is often present in multiple states after the measurement but he can't experience any state other than the one he is in because the copying process prevents interference between the different versions of the measurement result.
See also
http://arxiv.org/abs/quant-ph/0104033.

A: Your questions reminds me of the movie "a serious men" by the Coen brothers (you should watch it regardless of the main character being a college physics professor). As some of the comments said, it is an oversimplification or a much more complex phenomenon. The only way to get some idea of what is happening is to understand the equations of quantum mechanics. But even if you do, there still is the problem of interpreting what they really mean. And not all physicists agree on that. That is a subject of study in foundations or philosophy of physics. There is still no agreement in the physics community on how to interpret the meaning of the equations of quantum mechanics. Much less in how to explain them to the general public!


text:
Q: Android Studio и gradle Плавно перехожу с Eclipse.
А можно как-то сделать, чтобы для всех новых проектов использовалась моя папка с gradle соответствующей версии?
А то сейчас получается она создаёт с 2.8, берёт этот gradle из подпапки android studio. И только после создания проекта, я могу зайти в настройки и указать версию и локальную папку с gradle.
А мне по большому счёта и папка gradle в android studio не надо. Потому что у меня разные версии gradle в совсем другом месте лежат.

A: ctrl+shift+A
Global gradle settings
Use local gradle distribution
и указать путь к локальному градлу
должно помочь


text:
Q: Multivariable limit $\lim_{(x, y) \to (0, 0)} \frac{x \sin(x^2 y^2)}{x^2 + y^2}$ I'm learning multivariable calculus, specifically multivariable limits and continuity, and need help to understand the solution to the following problem:

Let
$$f(x,y) = \begin{cases} \frac{x \sin(x^2 y^2)}{x^2 + y^2}, & (x,y) \neq (0, 0) \\ 0, & (x,y) = (0, 0).  \end{cases}$$
Show that $f$ is continuous at $(0, 0)$.

So we need to show that
$$\lim_{(x, y) \to (0, 0)} f(x, y) = f(0, 0)$$
that is
$$\lim_{(x, y) \to (0, 0)} \frac{x \sin(x^2 y^2)}{x^2 + y^2} = 0.$$
Solution: (from textbook)
We have that
$$\left| \frac{x \sin(x^2 y^2)}{x^2 + y^2}  \right| = \frac{\left|x\right| \left|\sin(x^2 y^2)\right|}{x^2 + y^2} \leq \frac{\left|x\right|x^2 y^2}{x^2 + y^2}  \leq \frac{\left|x\right|^3 y^2}{x^2 + y^2} \leq \left|x\right|^3.$$
Question:
I don't understand how the author found the upper bound for the sine function. Why does $\left|\sin(x^2y^2)\right| \leq x^2y^2$? When I first tried to solve this problem I used $\left|\sin(x^2y^2)\right| \leq 1$ without success. Can someone explein my error?

A: For all $t$, $$|\sin(t)|\leq |t|.$$
Indeed, using mean value theorem, for all $t$, there is $|c_t|\leq |t|$ s.t.
$$|\sin(t)|=|\sin(t)-\sin(0)|=\underbrace{|\cos(c_t)|}_{\leq 1}|t-0|\leq |t|$$

A: Can i point out another strategy?
$$
\lim_{(x, y) \to (0, 0)} \frac{x \sin(x^2 y^2)}{x^2 + y^2} = 0.
$$
changing to polar coords:
$$
\lim_{\rho \to 0} \frac{\rho \cos t\, \sin(\rho^4 \cos^2t\,\sin^2t)}{\rho^2} = ... \textrm{taylor expansion} ... = 0
$$
of course the method in the textbook is valid, proof for the sin inequality:
$$
 |sin(t)|= \left| \int_0^t \cos(x) dx \right| \leq \left| \int_0^t \left| \cos(x) \right| dx \right| \leq \left|\int_0^t 1 dx \right| =|t|
$$
so for all $t \in \mathscr R$:
$$
|sin(t)| \leq |t|
$$

A: Basically,
$$
(t-\sin t)'=1-\cos t\ge0
$$ then, since $0-\sin 0=0$, you get that
$$
t\ge \sin t, \quad t\ge0,
$$ and by parity
$$
|\sin t|\le |t|,\quad t \in \mathbb{R}.
$$


text:
Q: Change one value in first row only of each CustomerID group depending on condition I have a dataset like the below:
df <-
  read.table(textConnection("CustomerID   Code1 Code2
A 1 1
A 0 1
A 1 1
B 1 0
B 0 1
C 1 1
C 1 1
D 1 0
D 0 1
D 1 1 "), header=TRUE)

What I am looking to do is loop through each CustomerID and, if the first row of the group has Code1 = 1 and Code2 = 1, change the Code2 value to 0 for that row. So in the above case, below would be the correct final dataset - the change only applies to the very first row in each customer group, if it has a 1 for both Code1 and Code2.

CustomerID
Code1
Code2

A
1
0

A
0
1

A
1
1

B
1
0

B
0
1

C
1
0

C
1
1

D
1
0

D
0
1

D
1
1

Any help very much appreciated, thank you.

A: Here's a solution using dplyr::case_when(). Group by CustomerID, create an index within each group using row_number(), and apply the case_when logic to the first row.
library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.2.1
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

df <-
  read.table(textConnection("CustomerID   Code1 Code2
A 1 1
A 0 1
A 1 1
B 1 0
B 0 1
C 1 1
C 1 1
D 1 0
D 0 1
D 1 1 "),
header = TRUE)

df |>
  group_by(CustomerID) |>
  mutate(
    row = row_number(),
    Code2 = case_when(row == 1 &
                        Code1 == 1 & Code2 == 1 ~ as.integer(0),
                      TRUE ~ Code2)
  ) |>
  ungroup() |>
  select(-row)
#> # A tibble: 10 × 3
#>    CustomerID Code1 Code2
#>    <chr>      <int> <int>
#>  1 A              1     0
#>  2 A              0     1
#>  3 A              1     1
#>  4 B              1     0
#>  5 B              0     1
#>  6 C              1     0
#>  7 C              1     1
#>  8 D              1     0
#>  9 D              0     1
#> 10 D              1     1

Created on 2022-10-26 with reprex v2.0.2


text:
Q: Execute function after element has loaded I want to execute a function after an element has been loaded.
jQuery's load() event seems to make this easy, but it was deprecated in v1.8. I'm looking for a modern version of a similar thing to this:
$( "img.userIcon" ).load(function() {
  if ( $( this ).height() > 100) {
    $( this ).addClass( "bigImg" );
  }
});

Must be cross-browser, can be jQuery or vanilla JS.

A: The documentation page says that .load(callback) is shorthand for .on('load', callback)
The .load(callback) was deprecated because of ambiguity with the AJAX .load(callback) (see here)


text:
Q: rounded corners of an arrow in tikz I have an arrow that looks like in this:
    \documentclass[tikz]{standalone}
    \usetikzlibrary{shapes, arrows.meta, positioning}
    \tikzset{every picture/.style={/utils/exec={\sffamily\normalsize}}}

    \tikzstyle{textbox} = [rectangle, minimum width = 3.2cm, minimum height = 1cm, rounded corners = 1pt, line width = 1pt, draw = black, align = center]
    \tikzstyle{arrow}   = [solid, line width = 9pt, -{Triangle[width = 18pt, length = 12pt]}, color = black, shorten >= 3pt, shorten <= 3pt]

    \begin{document}
        \begin{tikzpicture}[node distance = 2cm and 1cm, outer sep = 0, inner sep = 0]

            \node [textbox]                  (box1) {box1};
            \node [textbox, right = of box1] (box2) {box2};
            \draw [arrow] (box1) -- (box2);

        \end{tikzpicture}
    \end{document}

My Goal is to round all the corners of the arrow by 1pt like I am doing it with the textboxes. I already tried line cap and rounded corners but it is not working. How am I able to round all the corners of the arrow head and also the of the line cap by 1pt?

A:   \documentclass[tikz]{standalone}
    \usetikzlibrary{shapes, arrows.meta, positioning}
    \tikzset{every picture/.style={/utils/exec={\sffamily\normalsize}}}

    \tikzstyle{textbox} = [rectangle, minimum width = 3.2cm, minimum height = 1cm, rounded corners = 1pt, line width = 1pt, draw = black, align = center]
    \tikzstyle{arrow}   = [solid, line width = 9pt, -{Triangle[width = 18pt, length = 12pt, round, line width=1pt]}, color = black, shorten >= 3pt, shorten <= 3pt]

    \begin{document}
        \begin{tikzpicture}[node distance = 2cm and 1cm, outer sep = 0, inner sep = 0]

            \node [textbox]                  (box1) {box1};
            \node [textbox, right = of box1] (box2) {box2};
            \draw [arrow] (box1) -- (box2);

        \end{tikzpicture}
    \end{document}

To make the left end rounded, you can add a rounded Square to the end like this:
\documentclass[tikz]{standalone}
    \usetikzlibrary{shapes, arrows.meta, positioning}
    \tikzset{every picture/.style={/utils/exec={\sffamily\normalsize}}}

    \tikzstyle{textbox} = [rectangle, minimum width = 3.2cm, minimum height = 1cm, rounded corners = 1pt, line width = 1pt, draw = black, align = center]
    \tikzstyle{arrow}   = [solid, line width = 9pt, {Square[round, line width=1pt, length= 2pt, width=9pt]}-{Triangle[width = 18pt, length = 12pt, round, line width=1pt]}, color = black, shorten >= 3pt, shorten <= 3pt]

    \begin{document}
        \begin{tikzpicture}[node distance = 2cm and 1cm, outer sep = 0, inner sep = 0]

            \node [textbox]                  (box1) {box1};
            \node [textbox, right = of box1] (box2) {box2};
            \draw [arrow] (box1) -- (box2);

        \end{tikzpicture}
    \end{document}

An other way to do this would be not to use an arrow at all, but to use a single arrow node shape.
Edit:
Using a single arrow node also rounds the inner corners, but of course it does not extend as a normal draw arrow:
\documentclass[tikz]{standalone}
    \usetikzlibrary{shapes, arrows.meta, positioning, shapes.arrows}
    \tikzset{every picture/.style={/utils/exec={\sffamily\normalsize}}}
    \tikzstyle{textbox} = [rectangle, minimum width = 3.2cm, minimum height = 1cm, rounded corners = 1pt, line width = 1pt, draw = black, align = center]
    \begin{document}
        \begin{tikzpicture}[node distance = 2cm and 1cm, outer sep = 0, inner sep = 0]
            \node [textbox]                  (box1) {box1};
            \node [textbox, right = of box1] (box2) {box2};
            \path (box1) -- (box2) node[midway, xshift= -2pt, draw, single arrow, minimum height=0.8cm, minimum width=0.7cm, single arrow head extend=0.01cm, single arrow tip angle=75,rounded corners=1pt, fill]{};
        \end{tikzpicture}
    \end{document}


text:
Q: steps to recover lost files and data in ubuntu 12.04 Recentlly i have installed ubuntu 12.04 and got to used with it ,but suddenly bymistake
i deleted few data and files ,so could you please tell me how to recovery the last data with steps .

A: did you empty the trash bin? otherwise check the "Trash"


text:
Q: Tabwidget not visible under toolbar/navbar in android studio I have constructed a TabHost inside my navigation drawer. That means I've created 3 Fragment with xml files each: ExhibitorFragment, TabInternationalFragment, and TabLocalFragment. Now the problem is, I can't see my tabwidget under the Toolbar even though it displays design xml in either two of the fragments.
below is my code for ExhibitorFragment.java:
public class ExhibitorFragment extends Fragment{

public ExhibitorFragment() {
    // Required empty public constructor
}

private FragmentTabHost mTabHost;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    mTabHost = new FragmentTabHost(getActivity());
    mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_exhibitor);

    Bundle arg1 = new Bundle();
    arg1.putInt("Arg for Frag1", 1);
    mTabHost.addTab(mTabHost.newTabSpec("Tab1").setIndicator("Frag Tab1"),
            TabInternationalFragment.class, arg1);

    Bundle arg2 = new Bundle();
    arg2.putInt("Arg for Frag2", 2);
    mTabHost.addTab(mTabHost.newTabSpec("Tab2").setIndicator("Frag Tab2"),
            TabLocalFragment.class, arg2);

    return mTabHost;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    mTabHost = null;
}

}

fragment_exhibitor.xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.guitarista.citem.Example">

    <TabHost android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"

                >

                <FrameLayout
                    android:id="@+id/International"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    />

                <FrameLayout
                    android:id="@+id/Local"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    />

            </FrameLayout>
        </LinearLayout>
    </TabHost>

</FrameLayout>

The TabInternationalFragment and TabLocalFragment are set to default when created same as their respected xml (fragment_tab_international, fragment_tab_local).

A: Your Java Code Is correct Try Changing the XML file to this format
 <android.support.v4.app.FragmentTabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_marginTop="55dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="45dp"/>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
</android.support.v4.app.FragmentTabHost>

A: Usr this code

    <TabHost android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                />

            <FrameLayout
                android:layout_below="@android:id/tabs"
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"

                >

                <FrameLayout
                    android:id="@+id/International"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    />

                <FrameLayout
                    android:id="@+id/Local"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    />

            </FrameLayout>
        </LinearLayout>
    </TabHost>

</FrameLayout>

A: FragmentTabHost mTabHost;
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("tab2"),
            tab1.class,null);

    mTabHost.addTab(mTabHost.newTabSpec("tab2")
            .setIndicator("tab2"), tab2.class, null);

A: I've followed this tutorial Android Tabs in Fragments. Though this one is likely similar to Pager Sliding tab strip. Take Note that you still need to implement fragment codes for this to work.


text:
Q: sumif range and criteria switching So I have a table of number of fiscal weeks in a year, and to calculate depreciation I'm trying to sum the number of weeks in the total life of the capital investment. So the first argument is the range, the second argument pulls the year from another cell, and then adds the expected life in years of the device. The third argument is the intended sum range.
SUMIF(YearWeeks[Year],"<="&LEFT(AS$14,4)+$H20,YearWeeks[Weeks])
This works fine. Pulls in the right numbers no problem.
However, whenever I try and drag this across other cells so that it can be used throughout my spreadsheet to caculate depreciation, it immediately switches the value for year and the value for weeks and becomes:
SUMIF(YearWeeks[Weeks],"<="&LEFT(AU$14,4)+$H20,YearWeeks[Year])
I cannot figure out why it is doing this. It is probably something simple, but it is completely evading me. Any help would be greatly appreciated.
Year   Weeks
2015    52
2016    53
2017    52
2018    52
2019    52
2020    52
2021    53
2022    52
2023    52
2024    52
2025    52
2026    52
2027    53
2028    52
2029    52
2030    52
Life

5
5
5
5
5
5
5
5
8
8
8
8
8
8

201504  201505  201506  201507  201508  201509  201510  201511  201512  201601  201602  201603

A: Instead of dragging the formula to the right, copy the cell and paste it in the cell at the right of it, etc... :
This will keep the column references unchanged (no change from YearWeeks[Weeks] to YearWeeks[Year]).
As specified on Microsoft's support website:

Moving, copying, and filling structured references
All structured references remain the same when you copy or move a formula that uses a structured reference.
When you fill a formula, fully qualified structured references can adjust the column specifiers like a series as summarized in the following table.

NB: YearWeeks[Weeks] is a structured reference, and fill is what many would call drag in this context.


text:
Q: Arango DB Filter query for print array of value Given the following document structure:
{
"name": [
{
  "use": "official",
  "family": "Chalmers",
  "given": [
    "Peter",
    "James"
  ]
},
{
  "use": "usual",
  "given": [
    "Jim"
  ]
},
{
  "use": "maiden",
  "family": "Windsor",
  "given": [
    "Peter",
    "James"
   ]
  }
 ]
}

Query:
FOR client IN Patient FILTER    client.name[*].use=='official' RETURN client.name[*].given
I have telecom and name array.
I want to query to compare if  name[*].use=='official' then print corresponding give array.
Expected result:
"given": [
"Peter",
"James"
]

A: client.name[*].use is an array, so you need to use an array operator. It can be either of the following:

*

*'string' in doc.attribute

*doc.attribute ANY == 'string'

*doc.attribute ANY IN ['string']
To return just the given names from the 'official' array, you can use a subquery:
RETURN { given:
  FIRST(FOR name IN client.name FILTER name.use == 'official' LIMIT 1 RETURN name.given)
}

Alternatively, you can use an inline expression:
FOR client IN Patient
  FILTER 'official' IN client.name[*].use
  RETURN { given:
    FIRST(client.name[* FILTER CURRENT.use == 'official' LIMIT 1 RETURN CURRENT.given])
  }

Result:
[
  {
    "given": [
      "Peter",
      "James"
    ]
  }
]

In your original post, the example document and query didn't match, but assuming the following structure:
{
  "telecom": [
    {
      "use": "official",
      "value": "+1 (03) 5555 6473 82"
    },
    {
      "use": "mobile",
      "value": "+1 (252) 5555 910 920 3"
    }
  ],
  "name": [
    {
      "use": "official",
      "family": "Chalmers",
      "given": [
        "Peter",
        "James"
      ]
    },
    {
      "use": "usual",
      "given": [
        "Jim"
      ]
    },
    {
      "use": "maiden",
      "family": "Windsor",
      "given": [
        "Peter",
        "James"
      ]
    }
  ]
}

… here is a possible query:
FOR client IN Patient
  FILTER LENGTH(client.telecom[* FILTER
    CONTAINS(CURRENT.value, "(03) 5555 6473") AND
    CURRENT.use == 'official']
  )
  RETURN {
    given: client.name[* FILTER CURRENT.use == 'official' RETURN CURRENT.given]
  }

Note that client.telecom[*].value LIKE "..." causes the array of phone numbers to be cast to a string "[\"+1 (03) 5555 6473 82\",\"+1 (252) 5555 910 920 3\"]" against which the LIKE operation is run - this kind of works, but it's not ideal.
CONTAINS() is also faster than LIKE with % wildcards on both sides.
It would be possible that there are multiple 'official' elements, which might require an extra level of array nesting. Above query produces:
[
  {
    "given": [
      [
        "Peter",
        "James"
      ]
    ]
  }
]

If you know that there is only one element or restrict it to one element explicitly then you can get rid of one of the wrapping square brackets with FIRST() or FLATTEN().


text:
Q: JAXB and CDATA - How to create external bindings I have an XML of this type
 <Cols>
     <Col name="Amount" oldValue="123">456</Col>
     <Col name="Text" oldValue="ABC">DEF</Col>
     <Col name="CDATAText" oldValue="ABC<"><![CDATA[DEF<]]></Col>
 </Cols>

My Schema is something like this
 <xs:complexType name="NonCDATACol">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute name="name" use="required" type="xs:string"/>
            <xs:attribute name="oldValue" use="optional" type="xs:string"/>
        </xs:extension>
    </xs:simpleContent>
 </xs:complexType>

 <xs:complexType name="CDATACol">
    <xs:complexContent>
        <xs:extension base="NonCDATACol"/>
    </xs:complexContent>
 </xs:complexType>

In the output when I Marshall CDATACol and and NonCDATACol I want them the element name to appear as Col. Also I am running to issues when customizing external bindings for CDATACol (CDATAAdapter). I get the error 'compiler was unable to honor this javaType customization. It is attached to a wrong place, or its inconsistent with other bindings.'
Any help/sample would be appreciated. Thanks!!
I would like to achieve this using just RI, using other packages I will have to jump through a lot of hoops


text:
Q: Remove newline character after pipe I want to do Base64 encode with a command
echo -en "my_message" | openssl sha1 -hmac "secret_key" | base64

The output string of openssl is as expected, but the output of base64 is not as the output from openssl has a new line character. If I run the command
echo -en "my_message" | openssl sha1 -hmac "secret_key" | xargs echo -n | base64

Then the final output is correct.
I wonder if there is a more elegant way for this command


text:
Q: Laravel, codesleeve asset-pipeline not working I am trying to get codesleeve asset-pipeline to work on my site. After wasting a full day, I finally got it working yesterday on my local development server. I have now uploaded the project to see if everything works on the live server. Guess what- it doesn't. I am guessing the problem is to do with the environment setting, ie:
$env = $app->detectEnvironment(array(
'local' => array('your-machine-name'),

));
So, I have changed that to my machine name when on my local server, which, as I say, I have working. So on the live server, what should this be? "localhost"? I have tried adding another array key for 'live' with my live server's IP address and domain name, as per this answer: http://tinyurl.com/pg6hwum Nothing works.
Also, according to the tutorials I am following:

When you are in the local environment, you will notice that all of your asset files will be included individually ... Once you are in the production environment, all of your assets will be concatenated into one.

That doesn't seem to be the case for me either, as pipeline seems to be half-working, ie. it is concatenating my js and css files, but somehow messing them up.
I'd really appreciate some pointers, as I have wasted a colossal amount of time with this thing now. Thanks.

A: First set your environment settings on your bootstrap/start.php file into something like this:
$env = $app->detectEnvironment(array(

    'local'       => array('http://localhost', '*.local', 'http://local.sitename'),
    'development' => array('http://dev.sitename.com'),
    'production'  => array('http://www.sitename.com', 'http://sitename.com'),

));

Second you need to check what enviroment does your laravel is running to check if your environment setup is working properly. By doing this:
App::environment()

So by doing that..you should have idea now what is causing the problem on codesleeve asset-pipeline.
note: see the documentation about environment for more details here

A: Asset pipeline will out of the box behave differently when on production compared to another environment (like local). I have put in a proposal to document some of these pain points and troubleshooting for new comers.
If you are using the most current version then there are two big behavior changes when switching environments:

*

*caching - production assets are cached. This means once you load a page you will be stuck with those assets until you do
$> php artisan assets:clean
This is why you should set your environment to local when developing.

*minification - assets are minified on production only. This can cause issues though because the minifiers sometimes break on code. There are some workarounds you can do to fix this. Something I normally do when having issues with a certain file (say Twitter Bootstrap) is use the .min.css extension which is then skipped by the minifier and written out as-is.
Note that this behavior is out of the box and can easily be modified by editing your configuration.
$> php artisan config:publish codesleeve/asset-pipeline

Then edit your file app/config/packages/codesleeve/asset-pipeline/config.php. For more information on these options visit the documentation here.
Hope this helps.


text:
Q: Will counting in file (PHP) result in clients receiving same number? I'm creating a small classroom-app website, where students will be logging in with a random generated code which the teacher will give them. I need every student to have a unique code so I'm using the following script
$count = file_get_contents($classcode . "/count.txt");
$count = $count + 1;
file_put_contents($classcode . "/count.txt", $count);

Now my question is, will clients be able to receive the same value for $count if they load up the page simultaneously? And maybe anyone has an better way to do such thing?

A: To answer your question, yes, the file can be overwritten unless you lock it
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);

Documentation: file_put_contents
More info - file_get_contents does not respect file locking


text:
Q: First time two independent Markov chains reach same state
Let $\{X_n\}$ and $\{Y_n\}$ two independent Markov chains with the
same state space $\{0,1,2\}$ and same transition probability matrix:
$$ P=\begin{pmatrix} 0.5&0.25&0.25\\ 0.25&0.25&0.5\\ 0&0.5&0.5 \end{pmatrix} $$
Define $T=\inf\{n: X_n=Y_n\}$. Assuming $X_0=0$ and $Y_0=2$, find
$\mathbb{E}[T]$ and $\mathbb{P}[X_T=2]$.

I think I know how to compute the probability, but I'm having trouble computing the expectation of $T$.
My attempt: I thought it would be easy if I consider
$$\mathbb{E}[T] = \sum_{i=0}^{2} \mathbb{E}[T\vert X_T = i]\cdot \mathbb{P}[X_T = i]$$
since the probability I need to compute in the first exercise is involved. So the only thing is left to compute is $\mathbb{E}[T\vert X_T = i]$ for $i=0,1,2$. I know how to solve this expected value if there's only one Markov chain involved, let's say if we want to know the first time $X_t = 2$ since $X_0 = 0$, using a recurrence argument, but I'm stuck when the problem involves two Markov chains.
On the other hand, I found this other question solving the analogous expected value for only one Markov chain, in a more direct way, without using conditional expected value, but I'm having trouble trying to apply a similar argument in this case.
Any help would be appreciatted.

A: Hint: $ET=\sum P(T>n)=\sum P(X_i \neq Y_i: 1\leq i \leq n)$.


text:
Q: Ansible: Remove item from dict I have a situation where i am trying to remove the item from a list. but i am not getting expected result. Please help me what I am doing wrong here?
here is the list :
    "get_ec2_id.instances[0].tags": {
    "Name": "test-db-system-2",
    "aws:cloudformation:logical-id": "DBInstance",
    "aws:cloudformation:stack-id": "arn:aws:cloudformation:us-east-1:123456789012:stack/test-db-system-2/0115v0a0-5d44-17e8-a024-503ama4a5qd1",
    "aws:cloudformation:stack-name": "test-db-system-2",
    "dbsystem:stack": "test-db-system-2",
    "dbsystem:type": "db"
}

}
I am trying to remove the all "aws:cloudformation" tags from a list using below filter:
    "{{ get_ec2_id.instances[0].tags | reject('search','aws:') | list }}"

I am getting the below result:
    ok: [10.52.8.101] => {
"instances_tags": [
    "dbsystem:type",
    "dbsystem:stack",
    "Name"
]
    }

but I am expected below result :
      "instances_tags": [
    "dbsystem:stack": "test-db-system-2",
    "dbsystem:type": "db"
    "Name" : "test-db-system-2",
]
  }

Help me to solve the issue.

A: More generic solution where input is a dict and blacklist is a list:
---
- set_fact:
    blacklist:
      - bad1
      - bad2
- set_fact:
    output: {}
- name: remove blacklisted items from input
  set_fact:
    output: "{{ output | combine({item.key: item.value}) }}"
  when: item.key not in blacklist
  loop: "{{ input | dict2items }}"

A:
Given the data
  get_ec2_id:
    instances:
    - tags:
        Name: test-db-system-2
        aws:cloudformation:logical-id: DBInstance
        aws:cloudformation:stack-id: arn:aws:cloudformation:us-east-1:123456789012:stack/test-db-system-2/0115v0a0-5d44-17e8-a024-503ama4a5qd1
        aws:cloudformation:stack-name: test-db-system-2
        dbsystem:stack: test-db-system-2
        dbsystem:type: db

Use rejectattr. For example
  dict2: "{{ get_ec2_id.instances.0.tags|
             dict2items|
             rejectattr('key', 'search', 'aws:')|
             items2dict }}"

gives
  dict2:
    Name: test-db-system-2
    dbsystem:stack: test-db-system-2
    dbsystem:type: db

Then, convert the dictionary into a list of dictionaries
  instances_tags: "{{ dict2|
                      dict2items|
                      json_query('[].[[key, value]]')|
                      map('community.general.dict')|
                      list }}"

gives
  instances_tags:
  - Name: test-db-system-2
  - dbsystem:stack: test-db-system-2
  - dbsystem:type: db

A: Use this:
---
- name: dictionary
  hosts: localhost
  gather_facts: False
  connection: local

  vars:
    get_ec2_id:
      instances:
        tags:
          Name: "test-db-system-2"
          "aws:cloudformation:logical-id": "DBInstance"
          "aws:cloudformation:stack-id": "arn:aws:cloudformation:us-east-1:123456789012:stack/test-db-system-2/0115v0a0-5d44-17e8-a024-503ama4a5qd1"
          "aws:cloudformation:stack-name": "test-db-system-2"
          "dbsystem:stack": "test-db-system-2"
          "dbsystem:type": "db"
    dict2: {}

  tasks:

    - name: Fact1
      set_fact:
        dict: "{{ get_ec2_id.instances.tags }}"

    - name: Debug1
      debug:
        var: dict

    - name: Fact2
      set_fact:
        dict2: "{{ dict2 | combine({item.key: item.value}) }}"
      when: "{{ item.key.find('aws:') }}"
      with_dict: "{{ dict }}"

    - name: Debug2
      debug:
        var: dict2

Output:
TASK [Debug2] ******************************************************************
ok: [localhost] => {
    "dict2": {
        "Name": "test-db-system-2",
        "dbsystem:stack": "test-db-system-2",
        "dbsystem:type": "db"
    }
}


text:
Q: How to redirect after Ember action completes inside component So I'm brand new to Ember (using ember-cli 3.0.4), and trying to understand how to do what to me are normal things. I've a form, inside a component, where the user updates information, and clicks Save. I've built an action that the component calls when the Save button is clicked, and that action calls save() on the model object. So far, so good.
My problem is that I want to redirect to a different page when the save() promise completes. I can't figure out how to do that. The emberjs guide for actions doesn't once mention redirecting, and only the Routing module seems to have any mention of redirecting.
Obviously, there's an "embery" way of doing things that I don't know yet, but so far I can't figure out what that is. How are simple redirects after save done best in Ember?
Component code:
export default Component.extend({
actions: {
    saveCountry() {
        var self = this;
        if (this.country.get('hasDirtyAttributes')) {
            this.country.save().then(
                //???
            );
        }
    }
}

The Route code:
export default Route.extend({
    model(params) {
       return this.get('store').findRecord('country', params.country_id);
    }
});

Thank you!

A: To transition or redirect from a component, you can inject the RouterService and use either transitionTo or replaceWith. Here's an example:
import Component from '@ember/component'
import {inject} from '@ember/service'

export default Component.extend({
  router: inject(),

  actions: {
    saveCountry() {
      // do stuff, validate etc.
      this.get('router').transitionTo('my-route')
    }
  }
})

Also see https://guides.emberjs.com/v3.1.0/routing/redirection/. Hope it helps.


text:
Q: Can Fluent NHibernate's AutoMapper handle Interface types? I typed this simplified example without the benefit of an IDE so forgive any syntax errors. When I try to automap this I get a FluentConfigurationException when I attempt to compile the mappings -

"Association references unmapped class
  IEmployee."

I imagine if I were to resolve this I'd get a similar error when it encounters the reference to IEmployer as well. I'm not opposed to creating a ClassMap manually but I prefer AutoMapper doing it instead.
public interface IEmployer
{
  int Id{ get; set; }
  IList<IEmployee> Employees { get; set; }
}

public class Employer: IEmployer
{
  public int Id{ get; set; }
  public IList<IEmployer> Employees { get; set; }
  public Employer()
  {
    Employees = new List<IEmployee>();
  }
}

public interface IEmployee
{
  int Id { get; set; }
  IEmployer Employer { get; set; }
}

public class Employee: IEmployee
{
  public int Id { get; set;}
  public IEmployer Employer { get; set;}
  public Employee(IEmployer employer)
  {
    Employer = employer;
  }
}

I've tried using .IncludeBase<IEmployee>() but to no avail. It acts like I never called IncludeBase at all.
Is the only solution to either not use interfaces in my domain entities or fall back on a manually defined ClassMap?
Either option creates a significant problem with the way my application is designed. I ignored persistence until I had finished implementing all the features, a mistake I won't be repeating again :-(

A: It's not a restriction imposed by Fluent or its AutoMapper, but by NHibernate itself.
I therefore don't think you'd get there with the manual class map. You'll have to lose the interfaces in the property and list definitions. You can keep the interfaces, but mapped properties and collections must use the concrete types of which NHibernate knows.

A: public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id);
        Map<Address>(x => x.Address); // Person.Address is of type IAddress implemented by Address
    }
}


text:
Q: Ubuntu crashes abnormally I'm using Ubuntu 17.04 32-bit edition and it crashes when I do some rendering in blender and also when I press add track for motion tracking.
My system configuration is as follows:

*

*Intel® core™ i3-3210 CPU @3.20GHz × 4

*2 GB ram

*Graphics: intel® ivybridge Desktop ×86/MMX/SSE2

*OS: ubuntu 17.04 32-bit

*Swap size: 1GB

I don't have any graphic card but it shows something in All Settings → Details, on Windows I saw "Intel HD graphics" there.
Here's the free -h output from the terminal while running blender as asked by @ByteCommander:
         Total    used    free    shared   buff/cache    available
 Mem:     1.7G    619M    423M      219M      663M         680M
Swap:     975M      0B    975M

When Ubuntu crashes, it takes me to somewhere where it asks to choose an operating system, one of it is "recovery mode". Whatever I choose from them, it takes me to a terminal like something and prints loads of errors. If I leave the PC for some hours, it's still doing something, also printing something:
Busybox 1.x type help to get a list of built in commands
 initframs:_

This morning, blender freezes again (4th time in 4 days) and crashes after it, then Ubuntu freezes, doesn't respond to clicks, suddenly restarts and finally takes me to the black screen, printing:
[4521.250846] EXT4-fs error (device sda5):
        ext4_final_entry:1463 inode #8519685: comm upowered:
        reading directory iblock 0

This message is sticked on 38th line of my screen and it's over 5 hours from then. What is it reading for so long?. To solve this I reinstalled again and again.
Shall I use Windows again instead, because I have animated some models in blender (on Windows) but in Ubuntu I end up with a crash even when just copying contents of a DVD to system.
Ubuntu login screen doesn't ask for password sometimes and lets anybody in to my desktop.
Also if this is a graphics card problem, what card would you recommend of 4GB which will work on blender, as blender is not supported by many graphic cards.


text:
Q: Fibonacci Calculator stack overflows at 93nd number in Swift My Fibonacci Calculator seems to stack overflow really rapidly, always at the same number
class FiboCalculator {

    private static let instance = FiboCalculator()
    private var cache: [Int] = [1,1]
    private init(){}

    // get the nth fibo number
    class func getZeroIndexed(n: Int) -> Int {
        if n < 0 {
            return 0
        }
        else if n < instance.cache.count {
            return instance.cache[n]
        }
        while n >= instance.cache.count {
            print("going down, right now i have \(instance.cache.count) values cached")
            instance.cache.append( instance.cache[instance.cache.count-1] + instance.cache[instance.cache.count-2] )
        }
        return instance.cache[n]
    }
}

I tried doing it recursively at first, but I got an EXC_BAD_INSTRUCTION every time when I tried to get the 91st value. Then I tried doing it the above way, iterative instead of recursive, and I get an EXC_BAD_INSTRUCTION every time I try and access the 93rd value. If I fill the cache up with 10 values from the start instead of 2, it still fails when trying to get the 93rd. If I split up the stack (resolve n/2 while cached count < n/2, then proceed) It still fails at 93. I'm also only testing this on a simulator. Am I missing something as to why this is failing?

A: The 93rd Fibonacci number is 12,200,160,415,121,876,738 which is more than 263 − 1, so it can't be represented as an Int anyway.
If you really want to support a number that big, you should use a BigInteger library.

A: You're overflowing the Int datatype, because the result of fib(93) (12,200,160,415,121,876,738, roughly 1.22 x 10^19) is larger than Int64.max (9,223,372,036,854,775,807, or roughly 9.22 x 10^18).
On 32 bit machines, this will crash even earlier, at fib(47) (2,971,215,073), because Int is a 32 bit type on 32 bit machines. Int32.max is only 2,147,483,647.


text:
Q: Two conditions in Google Sheets Function I have a question on using two functions with an if statement in Google Sheets as one complete function. Both variables have to be true, otherwise it returns false. I need one function to check the date 20 months back from today. If said cell is less than today's date 20 months back it's true, naturally. However, for the complete function to return true it also searches for another text value in another cell and has to be an exact match. Both conditions have to be true (the date and the exact match) for the function to be true. So if the date in the cell is less than today's date 20 months back and the text value in the other cell is an exact match, function is true.
Problem is that it seems like the date function does not seem to apply.
=IF(D2<DATE(YEAR(TODAY()),MONTH(TODAY())-20,DAY(TODAY())),AND(REGEXMATCH(M2,"text")),TRUE,FALSE)

A: You current formula is not set up correctly (nor logically). Given only what you've shown here, this should work:
=IF(AND( D2<DATE(YEAR(TODAY()),MONTH(TODAY())-20,DAY(TODAY())), REGEXMATCH(M2,"text") ),TRUE,FALSE)
Notice that the AND( ) contains both conditions here, whereas your original formula had it only around the second condition.
However, a shorter version of this would be as follows:
=AND( D2<DATE(YEAR(TODAY()),MONTH(TODAY())-20,DAY(TODAY())), REGEXMATCH(M2,"text") )
... since the result of a properly functioning AND( ) is always TRUE or FALSE anyway.

A: It looks like you're supplying 4 arguments to the IF statement:
=IF(DATECHECK,AND(TEXTCHECK),TRUE,FALSE)
The IF statement expects 3 arguments instead. 1) the condition, 2) the value if true, and 3) the value if false. You can combine your two conditions using an AND statement like this:
AND(DATECHECK,TEXTCHECK)
The final formula would then be:
=IF(AND(D2<DATE(YEAR(TODAY()),MONTH(TODAY())-20,DAY(TODAY())), REGEXMATCH(M2,"text")),TRUE,FALSE)


text:
Q: What is a View in Oracle? What is a view in Oracle?

A: regular view----->short name for a query,no additional space is used here
Materialised view---->similar to creating table whose data will refresh periodically based on data query used for creating the view

A: A view is a virtual table, which provides access to a subset of column from one or more table. A view can derive its data from one or more table. An output of query can be stored as a view. View act like small a table but it does not physically take any space. View is good way to present data in particular users from accessing the table directly. A view in oracle is nothing but a stored sql scripts. Views itself contain no data.

A: A view is simply any SELECT query that has been given a name and saved in the database. For this reason, a view is sometimes called a named query or a stored query. To create a view, you use the SQL syntax:
     CREATE OR REPLACE VIEW <view_name> AS
     SELECT <any valid select query>;

A: A View in Oracle and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query
SELECT customerid, customername FROM customers WHERE countryid='US';

To create a view use the CREATE VIEW command as seen in this example
CREATE VIEW view_uscustomers
AS
SELECT customerid, customername FROM customers WHERE countryid='US';

This command creates a new view called view_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this:
SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200;

And Oracle will transform the query into this:
SELECT *
FROM (select customerid, customername from customers WHERE countryid='US')
WHERE customerid BETWEEN 100 AND 200

Benefits of using Views

*

*Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called it's less likely to require parsing.

*Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to.

*Predicate pushing
You can find advanced topics in this article about "How to Create and Manage Views in Oracle."

A: If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views


text:
Q: How to calculate daily average frequency in a table in function of GROUP BY from another table? I want to know which cinema room is more frequented daily and I need the values as relative frequency.
My tables are:
table1:

client_id
cinema_room

1
A

2
B

3
C

4
C

5
A

6
C

7
B

8
A

9
B

10
B

11
B

12
A

13
C

14
A

15
A

16
B

Table 2:

day
client_id

01/01/2022
1

01/01/2022
1

01/02/2022
1

01/02/2022
2

01/02/2022
4

01/03/2022
8

01/04/2022
14

01/04/2022
15

01/04/2022
16

So I need results like:

day
cinema_room
avg_freq

01/01/2022
A
1

01/01/2022
B
0

01/01/2022
C
0

01/02/2022
A
0.33

01/02/2022
B
0.33

01/02/2022
C
0.33

01/03/2022
A
1

01/03/2022
B
0

01/03/2022
C
0

01/04/2022
A
0.66

01/04/2022
B
0.33

01/04/2022
C
0

What I've got by now is:
SELECT day , cinema_room, COUNT(t2.client_id) as t2_tot
FROM table1 t1
    LEFT JOIN table2 t2 ON t1.client_id = t2.client_id
GROUP BY day, cinema_room
ORDER BY day

Its insufficient results are:

NOTE 1: I'm counting, not even averaging.

NOTE 2: The first three rows are wrong af.

day
cinema_room
count_freq

None
A
0

None
B
0

None
C
0

01/01/2022
A
3

01/01/2022
B
0

01/01/2022
C
0

01/02/2022
A
1

01/02/2022
B
1

01/02/2022
C
1

01/03/2022
A
1

01/03/2022
B
0

01/03/2022
C
0

01/04/2022
A
2

01/04/2022
B
1

01/04/2022
C
0

A: You can try to use CROSS JOIN in a subquery which would be a calendar table, then aggregate table1 & table2 in another subquery the get count by each cinema_room per day.
SELECT t1.day , t1.cinema_room, SUM(IFNULL(t2.cnt,0)) / (SELECT COUNT(*) FROM table2 tt2 WHERE t1.day = tt2.day) as t2_tot
FROM (
  SELECT DISTINCT day,cinema_room
 FROM table2 t2 CROSS JOIN table1
) t1
LEFT JOIN (
 SELECT day,cinema_room,COUNT(*) cnt
  FROM table1 t1 INNER JOIN table2 t2
  ON t1.client_id = t2.client_id
  GROUP BY day,cinema_room
) t2 ON t1.day = t2.day AND t1.cinema_room = t2.cinema_room
GROUP BY t1.day , t1.cinema_room
ORDER BY t1.day

sqlfiddle


text:
Q: jQuery Adding New Table Row Not at the End of the Table I have an HTML Table and would like to allow the user to click a button to add a new Row, but the new Row will not be added at the end of the table but rather after the last row of input fields.
I've setup a sample JSFiddle at:
http://jsfiddle.net/n7Gup/2/
I have a New Row button but it's not cloning the last row of inputs (i.e the row where the New Row button is). I need to modify this so that it will insert a new row after the last of these input rows.
Here's the script which I found from an online tutorial:
$(document).ready(function($)
{
  // trigger event when button is clicked
  $("#button2").click(function()
  {
    // add new row to table using addTableRow function
    addTableRow($("#nextYear"));

    // prevent button redirecting to new page
    return false;
  });

  // function to add a new row to a table by cloning the last row and
  // incrementing the name and id values by 1 to make them unique
  function addTableRow(table)
  {
    // clone the last row in the table
    var $tr = $(table).find("tbody tr:last").clone();

    // get the name attribute for the input and select fields
    $tr.find("input,select").attr("name", function()
    {
      // break the field name and it's number into two parts
      var parts = this.id.match(/(\D+)(\d+)$/);

      // create a unique name for the new field by incrementing
      // the number for the previous field by 1
      return parts[1] + ++parts[2];
    // repeat for id attributes
    }).attr("id", function()
    {
      var parts = this.id.match(/(\D+)(\d+)$/);
      return parts[1] + ++parts[2];
    });

    // append the new row to the table
    $(table).find("tbody tr:last").after($tr);
  };
});

The new row that is created can have all the input fields empty as the user will start again. Also is there a way to have the New Row button only appear once, and that will always be at the last row of activity inputs. For example initially there will only be one row, but if you click the New Row button a 2nd row will be created below the initial row and the New Row button will now only appear on this newly created row.
Appreciate any help - I'm new to Javascript.

A: Here is a solution
http://jsfiddle.net/7vuZf/3/
Basically you simply pass the reference to the the button clicked and work out your positioning in the table from there - save the reference to the current last row (using closest(), clone it (with events), remove the new row button in the original (you probably need to replace it with a delete button), and insert the clone after the original.
Also now you probably do not need a reference to the table object passed to your click handler (I left it in the code though).


text:
Q: how to use Stack View of object library in Xcode 7 I recently installed Xcode 7 beta and found something
 new in object library like
Horizontal stack view and Vertical stack view.

When i put some controls inside it, stackview seems to be resizable
  according to the control size. When i present more controls the stack
  seems to be adjust automatically as of the stack view.
  Either
  adjusting horizontally or vertically?

Is it derived from some other mobile platform

A: A major advantage of using UIStackView is it uses Auto Layout to position and size its arranged UIViews. Therefore you dont need to worry about positioning UIViews in a UIStackView.For a horizontal stack, this means the first arranged view's leading edge is pinned to the stack's leading edge, and the last arranged view's trailing edge is pinned to the stack's trailing edge. You can try by inserting two or more controls to a horizontal stack view,how they align horizontally w.r.t each other.

The UIStackView class provides a streamlined interface for laying out
  a collection of views in either a column or a row. Stack views let you
  leverage the power of Auto Layout, creating user interfaces that can
  dynamically adapt to the device's orientation, screen size, and any
  changes in the available space. The stack view manages the layout of
  all the views in its arrangedSubviews property. These views are
  arranged along the stack view's axis, based on their order in the
  arrangedSubviews array. The exact layout varies depending on the stack
  view's axis, distribution, alignment, spacing, and other properties.

For how to use
Here is a detail tutorial from raywenderlich site:
http://www.raywenderlich.com/114552/uistackview-tutorial-introducing-stack-views
For More,Please have a look at https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/index.html


text:
Q: Can a single photovoltaic semiconductor junction ever produce a voltage much above it's own band gap? A simple model for a photovoltaic cell is a current source with a series resistor, and a few more items. The current from the current source is some fairly constant proportionality constant of the order of one electron hole pair per incident photon (with energy above the band gap).
In reality, I think the model breaks down at high intensity - I can't think of any way that a single photodiode run in photovoltaic mode could produce for example $100~\mathrm{V}$. The spontaneous recombination - a 2nd order process - would limit the current I of the current source in the basic model. The electrons and holes would simply be stuck in the junction if the external voltage were much above the band gap.
Question: Can the output voltage of a single photovoltaic cell ever exceed the band gap my more than a tiny amount? How much? Could a single silicon junction every produce $1.5~\mathrm{V}$? $2.0 ~\mathrm{V}$?
I need more than just a screen shot of a plot, I'd like to understand the physics that governs the maximum possible DC voltage that can be produced by a standard (e.g. silicon, GaAs-like, etc) semiconductor photovoltaic cell.


text:
Q: a question in projection Let $V=L^2(\Omega)$, and
$$k=\{v \in V ~s.t ~||v||_{L^2(\Omega)}\leq 1 \}$$
I need to find projection  for any $u \in V$ on $k$.
Please help me.I do not have any idea about this problem. I have many theorem about exisitence and uniqueness solution, but I do not know how to find it.
Thanks.


text:
Q: visual studio namespace in code behind file From some time whenever i download the webpages example from the Internet.In code behind file of .aspx page there is namespace mention before public partial class in some example.But it never worked for me. I'm using the vs2010 is this format used in previous version of Visual site and why vs2010 not support them.
Like in code behind file
namespace AutoCompleteTextBox
{
     public partial class AutoCompleteDemp : System.Web.UI.Page

A: Make sure your .aspx's <@page> directive has a matching Namespace:
<%@ Page Title="Contact" Language="C#" AutoEventWireup="true"
     CodeBehind="AutoCompleteDemp.aspx.cs" Inherits="AutoCompleteTextBox.AutoCompleteDemp " %>


text:
Q: How can I logout from Facebook from my application? I am new to Android. I am using fbrocket example for status post for my application, but I cannot log out from my application. Status message will be posted successfully from this application, but When I close my application, I want to also log out from Facebook.
How can i do this?
Please help me.
My code is here:
package com.drc.Incognito;

import net.xeomax.FBRocket.FBRocket;
import net.xeomax.FBRocket.LoginListener;
import net.xeomax.FBRocket.ServerErrorException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class Facebook extends Activity implements LoginListener {
    private FBRocket fbRocket;

    Bundle bundle;
    int i;
    String rname,rshopno,raddress,rcity,rphone,remail,rpostcode;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        rname=bundle.getString("keyshop_name");
        rshopno=bundle.getString("keyshop_no");
        raddress=bundle.getString("keystreet");
        rpostcode=bundle.getString("keypostcode");
        rcity=bundle.getString("keycity");
        rphone=bundle.getString("keyphone");
        remail=bundle.getString("keyemail");
        shareFacebook();

    }
    public void shareFacebook() {
        fbRocket = new FBRocket(this, "PitchFork TRY",
                "c3968bbdd9dc7f44a8e05b7346f46673");

        if (fbRocket.existsSavedFacebook()) {
            fbRocket.loadFacebook();
        } else {
            fbRocket.login(R.layout.main);
        }

    }
    @Override
    public void onLoginFail() {
        fbRocket.displayToast("Login failed!");
        fbRocket.login(R.layout.main);
    }
    @Override
    public void onLoginSuccess(net.xeomax.FBRocket.Facebook facebook) {
        // TODO Auto-generated method stub

        try {
            System.out.println("Incognito Shop:  " +"\n" +rname +"\n" +raddress+ "  " + rshopno +"\n" +rpostcode + " " +rcity + "\n" +rphone +"\n" + remail);
            fbRocket.displayToast("Login success!");
            facebook.setStatus("Incognito Shop:  " +"\n" +rname +"\n" +raddress+ "  " + rshopno +"\n" +rpostcode + " " +rcity + "\n" +rphone +"\n" + remail);

            fbRocket.displayDialog("Status Posted Successfully!! ");
        //  Intent in = new Intent(this,ShopDetail.class);
        //  startActivity(in);
            facebook.logout();
            finish();

        } catch (ServerErrorException e) {
            if (e.notLoggedIn()) {
                fbRocket.login(R.layout.main);
            } else {
                System.out.println(e);
            }
        }

    }
}

Can you tell me how can I log out from my application when I close my application?

A: Actually these applications are one-click go applications, so they require username and password only once. Then these application stores them in their private files, so whenever next time the application launches, the user is logged in automatically. This facility is given since the device on which they are using are personal, so no need to logout. But if you want to log out the application, the only way is Clear the data.. Go to Settings -> Applications -> Manage Application -> Select Application -> Clear Data.

A: I'm pretty sure fbRocket uses the Facebook Graph API. What you must remember is that Facebook Libraries uses an Authorization protocol called OAuth. This allows the end user to login to Facebook and, when sucessful, Facebook returns an access token. This token doesn't last forever (usually, they have a TTL (Time to live)).
This token exists per application and user authentication, so if the user logs out from Facebook, the access token will expire and will be deemed obsolete.
In this regard, you don't have to worry much.


text:
Q: nxn square within an mxm square How would we find the number of ways of placing an nxn square within an mxm square? For example, say we had a 3x3 square. There are 4 ways of placing a 2x2 square within this 3x3 square. Likewise, there are 784 ways of placing a 5x5 square within a 32x32 square. Please see the image below for what exactly is meant by a 'square'.

A: Consider first fixing the movement to one particular row. You can move $m-(n-1) = m -n  + 1$ ways. The same argument holds for the number of columns: $m - n + 1$. You then multiply the two together to get the resulting:
$$\begin{align}
(m - n + 1)(m - n + 1) &= m^2 - mn + m - nm + n^2 - n + m - n + 1 \\
                       &= m^2 - 2nm + m + n^2 - n + m - n + 1 \\
                       &= m^2 - 2nm + 2m - 2n + n^2 + 1
\end{align}$$

A: A basic principle of combinatorics is the following: If you can choose independently an element of some $m$ element set and an element of some $n$ element set there are $N=m\,n$ choices in total.


text:
Q: Forgotten rebase interactive - git I ran some times ago some git rebase -i command. But I completely forgot it. Now I want to change new commits order. So I ran git rebase -i HEAD~4, and I get normally
It seems that there is already a rebase-merge directory, and
I wonder if you are in the middle of another rebase.

But I don't even remember what this rebase was all about. How can I find what was the precise purpose of that rebase.

A: It seems like you unexpectedly quit from rebase and for this you get this error in terminal.
To solve this, you need to quit from current rebase and create a new one.
git rebase --quit

A: You probably want to read .git/rebase-merge/git-rebase-todo which contains the next rebase --interactive commands that will be run, however, it's much easier to just abort the rebase: git rebase --abort.

A: You can go to your_app/.git/rebase-merge and find some related informations.

A: If it's an old forgotten rebase and you already moved on with things, then you probably don't care anymore (except for learning purposes) and you could just abort the old rebase with
git rebase --abort


text:
Q: Using ajax with asp.net mvc I am a begineer in MVC and i need to know is it easy to use ajax with asp.net mvc ? i mean that if it is like asp applications when using ajax(JS file,web service or ajax toolkit)? I didn't try it b4 but what i need to know how can i use ajax with mvc application and i hope from any one give me an answer and put a link for articles about this topic not to put a link for general article about mvc i need a specific one about ajax with mvc and specially to be clear and with examples as i got confused from thoses articles that talked about this topic without any example.
I have read an article and noticed a code for calling ajax but i didn't understand it's structure so can any one tell me in steps and an example how to use ajax in MVC application? I am too sorry for this question that i restrict the answer but i am begineer in MVC and got confused and need a tutorial for any issue. And i need to know what are the consequences of using MVC in asp.net ? what are progress added to web programming after MVC is released in asp.net ? whate are improvements that had been added ?
Thanks in advance for any reply or answer

A: This is how to emulate UpdatePanel in ASP.NET MVC.
This is how you can submit form with Ajax.
This is another sample of using built-in AjaxHelper.

A: I echo the suggestions that you read up on the core concepts behind ajax. Once you do, the rest of my answer might be helpful to come back to :)
Back? Ok!
You will be very pleasantly surprised. You can really just include the jquery libs into your master page and then freely just use jquery in your views as you would in pure HTML.
Somehting I do is add a ContentPlaceHolder just before the close of the head tag int he site master template...
<asp:ContentPlaceHolder ID="JavascriptContent" runat="server" />

That way in my views, if I need some per view jQuery I can simply do somehting like..
<asp:Content ID="Content6" ContentPlaceHolderID="JavascriptContent" runat="server">
<script type="text/javascript">
    $(function() {
          alert("Hi!");
    });
</script>

And it just drops right in. On those pages where you don't need it, simply don't assign the placeholder.
Hope that helps!
Ken

A: You've meshed up two questions into one. I'll try to address them both.
Using AJAX in ASP.NET-MVC is no different from using it in WebForms. You define an action on your controller and call it via jQuery (or any other javascript library).
Consequences of using ASP.NET-MVC? Hmm, this is a tough one. I prefer the MVC approach over WebForms because it's cleaner and easier to maintain later (this is just my viewpoint). I suggest that you read a good book on the subject, 'cos I have a feeling that you're not quite grasped the concept. I would really recommend Pro ASP NET MVC Framework.


text:
Q: Test for an Inverse Function When I teach students about inverse functions, every textbook says that you have to test both $f(g(x))$ and $g(f(x))$ to see if they equal $x$.  However, I've never seen a case where one of those equals $x$ and the other doesn't which makes me question if you really have to look at both cases.
So my question is, are there two functions, $f$ and $g$, such that $f(g(x)) = x$ but $g(f(x)) \ne x$?

A: $g:[0,1]\rightarrow [0,2]$, $g(x)=x$ and $f:[0,2]\rightarrow [0,1]$, $f(x)=min(x,1)$.

A: Sure. Let $f$ be the only function from $\{0,1\}$ into $\{0\}$ and define $g\colon\{0\}\longrightarrow\{0,1\}$ by $g(0)=0$. Then you always have $f(g(x))=x$, but $g(f(1))\ne1$.

A: Adding to the list... consider the sequence space of $\ell_2$, the space of infinite square summable sequences.
The right-shift operator, $R$, takes a sequence and shifts the positions of each entry to the right, appending a zero to the beginning.  That is... $R(a_1,a_2,a_3,a_4,a_5\dots) = (0,a_1,a_2,a_3,a_4,\dots)$
The left-shift operator, $L$, takes a sequence and shifts the positions of each entry to the left, the initial term having nowhere to the left to go is just forgotten.  That is... $L(a_1,a_2,a_3,a_4,a_5,\dots) = (a_2,a_3,a_4,a_5,a_6,\dots)$
One can see then that $L(R(a_1,a_2,a_3,a_4,\dots)) = (a_1,a_2,a_3,a_4,\dots)$ while on the other hand $R(L(a_1,a_2,a_3,a_4,\dots)) = (0,a_2,a_3,a_4,\dots)$ showing that $R$ is a right-inverse to $L$ but not vice versa.

A: Let $X$ be a non-empty set. If $g: X \to X$ is one-to-one, but not onto (i.e. $g(x_1) =  g(x_2) \implies x_1=x_2$, but there exists $x \in X$ such that there is no $x_0 \in X$ with $f(x_0) = x$), then we may define $f: f(X) \to X$ on the range of $g$ as $f(g(x)) := x$. Then, $f(g(x))=x$ for all $x \in X$ by definition, but the expression $g(f(x))$ does not even make sense for all $x \in X$. More generally, in such a case $g$ is a right inverse of $f$, but not a left inverse.

A: For a function $g$, it has a left inverse if you can find $f_1$ such that $f_1(g(x))=x$ and a right inverse if you can find a function $f_2$ such that $g(f_2(x))=x$; $g$ has an inverse $f$ if both $f_1$ and $f_2$ exist and $f=f_1=f_2$.
Others above have given examples of functions which only have a one-sided inverse but let me give a perhaps more familiar one. Consider as $g$ the differentiation map $\frac{d}{dx}$ on polynomials (i.e. expressions of the form $p(x)=a_nx^n+a_{n-1}x^{n-1}+\cdots+a_0$ where $a_i$ are rational numbers.
As a possible inverse, consider $f$ to be the indefinite integral map $\int$. Then $g(f(p(x)))= \frac{d}{dx}(\int p(x) dx)=p(x)$ (where $p(x)$ is an element of the polynomial space we are acting on), so $f$ is a right inverse to $g$. However $f(g(p(x)))=\int(\frac{d}{dx} p(x)) dx$ is not always $p(x)$ due to the constant of integration; i.e. both $p_1(x)=x$ and $p_2(x)=x+1$ differentiate to the same element $1$, but when integrated we don't know which one it came from, due to the constant of integration.
(Caveat: here the integration isn't well-defined as I've not created an explicit map on polynomials but this could be done by setting the constant of integration to always be $0$).


text:
Q: how can i test the accelerometer sensors in my desktop PC with simulator of windows8 store app i download the Windows 8 app samples from Microsoft and one of these samples accelerometer sensor sample

i dont know how can i test it for planning my software for using this feature ?
i haven't surface device and want to know is there only one way for do that? why we cant test it and shake it by mouse? why sensors not work in simulator when i rotate it ? why in simulator doesn't exist any button for shake simulator with mouse?

A: Unfortunately the simulator doesn't emulate the accelerometer or other sensors other than location. You will need physical sensor hardware to test this.
From MSDN forum

A: Well, you can use the one from the Windows Phone Emulator
https://www.nuget.org/packages/XamlActions.AccelerometerSimulator/
ps: super-master-workaround. Use it at your own risk :)