text:
Q: What does "dish" really mean? Does it refer to a serving of food or a plate? Koreans will often say: "I had barbecue for lunch, with side dishes"
A Canadian English teacher says, 'You cannot say "I had barbecue for lunch with side dishes."  I would be thinking that you ate the plates.'
What about this question:
"What is your favorite Korean dish?" Is it correct?

A: Dish can correspond to either the physical plate or the food item, depending on the context. A side dish refers to a food item that accompanies the main course.
It is perfectly fine to say:

I had barbecue for lunch with side dishes.
What is your favorite Korean dish?

A: A side dish:
sometimes referred to as a side order, side item, or simply a side,is a food item that accompanies the entrée or main course at a meal.
Source: Collins Dictionary
Probably there was some misunderstanding with you teacher.

A: Both meanings are correct, and should be understood in context. Here's a definition from merriam-webster.com:

*

*a shallow container that you cook or serve food in; specifically : a shallow bowl

*the food served in a dish

*food that is prepared in a particular way

This is probably a case of metonymy, which is "a figure of speech in which a thing or concept is called not by its own name but rather by the name of something associated in meaning with that thing or concept". So you have food that is prepared and served, and a word that can describe the food, the container, or both of them together.
I will leave it up to the reader to decide which of the definitions is the original, if any is at all, and which was metonymically derived.

A: The earlier Collins dictionary example "...or simply a side,..." is not so commonly heard in UK English usage. In the UK it would more usually be "...or simply a side dish,..."
Dish in UK English can refer to either the food or the dish it is placed on, or both.
Richard D.

A: There is a cultural difference here which may have caused your confusion over the usage of the words.
A typical Korean meal, for example Kalbi, would have the main beef dish in the middle of the table and several other dishes - the side dishes - containing vegetables and garnish around the table.  The diners take their food from all the dishes present.
A typical Western meal would be served on one plate with a separate plate - a side dish - for items such as bread.  The diners each have their own side dish.  Although when dining in an Indian or Chinese restaurant this may vary.
The term side dish has the meanings that other answers have provided.  It can be used for both the item of crockery and the food upon it in all types of cuisine.  However, the cultural nuance may have caused confusion.  Especially over the difference in the manner of barbecues between Korea and Canada.


text:
Q: Fetch the Ordered Products through collection Background :
I can able to display the Customer's Orders in excel sheet....

Requirement :
Now I am trying to get the Ordered Product skus in excel sheet...
Issue :
Notice: Undefined variable: sku
<?php

$customerCount = 0;
try{
    //configure the collection filters.
    $collection = Mage::getResourceModel('customer/customer_collection')
    ->addAttributeToSelect('entity_id')
    ->addAttributeToSelect('firstname')
    ->addAttributeToSelect('email');

    do{
         //Tell the collection which page to load.
         $collection->setCurPage($currentPage);
         $collection->load();
         foreach ($collection as $customer){
             $customerArray = $customer->toArray();

  $newordercollection = Mage::getModel("sales/order")->getCollection()->addFieldToFilter('customer_id',$customerArray['entity_id']);
  $collection->setOrder('entity_id', 'ASC');
  $firstItem = $newordercollection->getFirstItem();
  $orderID = $firstItem->getIncrementId();

        foreach ($newordercollection as $orderkey => $ordervalue)
        {
             foreach ($ordervalue->getAllVisibleItems() as $item)
              {
                $name = $item->getName();
              }
              $eid = $ordervalue->getOrderId();
              $order = Mage::getModel("sales/order")->load($eid);
        }
            //write the collection array as a CSV.

            $customerREquiredArray['customer ID'] = $customerArray['entity_id'];
            $customerREquiredArray['First name'] = $customerArray['firstname'];
            $customerREquiredArray['Email'] = $customerArray['email'];
            $customerREquiredArray['order id']= $orderID;
            $customerREquiredArray['products']= $name;
            $customerCount++;
    }
}

Full code : https://pastebin.com/2bHGSZiw

A: I Have modified your code please use below code and you will get all customer orders in csv file.
<?php
require_once('app/Mage.php');
error_reporting(E_ALL);
ini_set('display_errors', 'On');
umask(0);
if (!Mage::isInstalled()) {
    echo "Application is not installed yet, please complete install wizard first.";
    exit;
}
// Only for urls // Don't remove this
$_SERVER['SCRIPT_NAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_NAME']);
$_SERVER['SCRIPT_FILENAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_FILENAME']);
Mage::app('admin')->setUseSessionInUrl(false);
Mage::setIsDeveloperMode(true); ini_set('display_errors', 1); error_reporting(E_ALL);
try {
    Mage::getConfig()->init();
    Mage::app();
} catch (Exception $e) {
    Mage::printException($e);
}
ini_set('memory_limit','500M');
$customerCount = 0;
try{
    //configure the collection filters.
    $collection = Mage::getResourceModel('customer/customer_collection')
    ->addAttributeToSelect('entity_id')
    ->addAttributeToSelect('firstname')
    ->addAttributeToSelect('email');

    //Add a page size to the result set.
    $collection->setPageSize(50);
    //discover how many page the result will be.
    $pages = $collection->getLastPageNumber();
    $currentPage = 1;
    //This is the file to append the output to.
    $fp = fopen('customers.csv', 'w');
    $header=array("Customer Id","First name",'Email',"order id","order date","products","product create time");
    fputcsv($fp, $header);
    do{
         //Tell the collection which page to load.
         $collection->setCurPage($currentPage);
         $collection->load();
         foreach ($collection as $customer){
             $customerArray = $customer->toArray();

  $newordercollection = Mage::getModel("sales/order")->getCollection()->addFieldToFilter('customer_id',$customerArray['entity_id']);

  $collection->setOrder('entity_id', 'ASC');
  $ordervalue = $newordercollection->getFirstItem();

        // get product information
        $result=array();
        $customerREquiredArray=array();
        foreach ($ordervalue->getAllVisibleItems() as $item)
          {
            $createdAt = $ordervalue->getCreatedAt();
            $myTimezone = new \DateTimeZone("Asia/Kolkata");
            $UTC = new DateTimeZone("UTC");
            $newDate = new \DateTime( $createdAt, $UTC );
            $newDate->setTimezone( $myTimezone );
            $createdAt = $newDate->format('Y-m-d H:i:s');

            $productCreatedAt=$item->getProduct()->getCreatedAt();
            $pNewdate = new \DateTime( $productCreatedAt, $UTC );
            $pNewdate->setTimezone( $myTimezone );
            $productCreatedAt = $pNewdate->format('Y-m-d H:i:s');

            $sku = $item->getSku();
            $eid = $ordervalue->getOrderId();
            $order = Mage::getModel("sales/order")->load($eid);
            $customerREquiredArray['customer ID'] = $customerArray['entity_id'];
            $customerREquiredArray['First name'] = $customerArray['firstname'];
            $customerREquiredArray['Email'] = $customerArray['email'];
            $customerREquiredArray['order id']= $ordervalue->getIncrementId();
            $customerREquiredArray['order date']= $createdAt;
            $customerREquiredArray['products']= $sku;
            $customerREquiredArray['product create time']= $productCreatedAt;
            fputcsv($fp, $customerREquiredArray);
            break;
        }
        }
            $currentPage++;
            $customerCount++;
         $collection->clear();
         echo "Finished page $currentPage of $pages \n";
    } while ($currentPage <= $pages);
    fclose($fp);
} catch (Exception $e) {
    Mage::printException($e);
}
echo "Saved $customerCount customers to csv file \n";

Here is output

A: I have updated your problematic code check.
foreach ($ordervalue->getAllVisibleItems() as $item)
          {
            $sku[] = $item->getSku(); //set sku in array
          }
          $eid = $ordervalue->getOrderId();
          $order = Mage::getModel("sales/order")->load($eid);

    }
        //write the collection array as a CSV.

        $customerREquiredArray['customer ID'] = $customerArray['entity_id'];
        $customerREquiredArray['First name'] = $customerArray['firstname'];
        $customerREquiredArray['Email'] = $customerArray['email'];
        $customerREquiredArray['order id']= $orderID;
        $customerREquiredArray['order date']= $createdAt;
        $customerREquiredArray['products']=  implode(",",$sku); // convert array to string

redpajama_set_name: RedPajamaStackExchange


text:
Q: EventEmitter Class in C++ : Listener and Emitter I am trying to implement a class that would allow listening on some events and when these emits are emitted, they would get notifications.
So i thought of using Functors,
 class MyFunctor {
    public:
        virtual void emit() {}
            vitual void compare() {}
 };

 class MyFunctorSpecial : public MyFunctor {
    void (*)() ab;
    public:
    MyFunctorSpecial(void (*a)()) : ab(a) {}
    void emit() { ab(); }
 };
 class EventEmitter {
   std::map<std::string, std::vector<MyFunctor> > eventMap;
   public:
    void On(const std::string &, const MyFunctor &) {
        // add to the map
    }

    void Emit(const std::string & eventName) {
        // emit the event
        // for all listeners in the vector for this event-name
         // call the emit of them.
    }
 };

 EventEmitter emitter;
 // some function - abc()
 MyFunctorSpecial funct(abc);
 emitter.On("hello", funct);
 emitter.Emit("hello");

But now i want to pass arguments to the listeners. Like
 emitter.Emit("hello", 45, false);

I think that this information would be available to Emit() at compile time, about the data-types of the various arguments. Can i use that information to make it happen , using templates or anything.
If there is another kind of pattern for this problem? How can I do this?

A: The common design pattern for your problem is called the Observer Design-Pattern.

Your so called "functors" are not functors.
If so they would have implemented an operator () method, and could have been called like functions ( thus the name functor). Yours are not.
For example, this is a functor: ( notice the operator())
class MyFunctor
{
    public:
        void operator()(){};
};

A: try this simple example as follow:
class event_manager {
    std::map<std::string, std::vector<std::function<void( std::string )>>> eventMap;
public:
    void on( const std::string &evt_name, std::function<void( std::string )> listener ) {
        auto it = eventMap.find( evt_name );
        if ( it != eventMap.end( ) ) {
            it->second.push_back( listener );
            return;
        }
        eventMap[evt_name] = std::vector<std::function<void( std::string )>>( );
        eventMap[evt_name].push_back( listener );
    };
    void emit( const std::string &evt_name, std::string data ) {
        auto evts = eventMap.find( evt_name );
        if ( evts == eventMap.end( ) ) return;
        for ( std::vector<std::function<void( std::string )>>::iterator it = std::begin( evts->second ); it != std::end( evts->second ); ++it ) {
            auto &func = *it;
            func( data );
        }
    }
};

and subscribe and emit event as like:
event_manager evt_mng;
evt_mng.on( "data", [&]( auto res ) {
  std::cout << res << std::endl;
} );
evt_mng.emit( "data", "Hello world" );


text:
Q: Failed to connect to docker hosted MSSQL I have a problem followng [this tutorial](https://hub.docker.com/r/microsoft/mssql-server-linux/
) where I try to connect to my docker hosted MSSQL via sqlcmd.
I executed the following in PowerShell from windows:
docker run -e 'ACCEPT_EULA=Y' --name mssql -e \
 'SA_PASSWORD=yourStrong(!)Password' -p 1433:1433 -it \
 -d microsoft/mssql-server-linux:latest /bin/bash

Note: "-it" and "/bin/bash" is added due to docker will be stopped automatically if there is no any activity detected.
I ran docker container ls -a to verify it is running:
docker container Is -a
CONTAINER ID      IMAGE                               COMMAND       CREATED          STATUS          PORTS                    NAMES
92cfc504ab70      microsoft/mssql-server-linux:latest "/bin/bash"   27 minutes ago   Up 27 minutes   0.0.0.0:1433->1433/tcp  mssql

I ran telnet local-ip:1433 on my host, it is working fine.
Problem lies when I do the following:
docker exec -it mssql /opt/mssql-tools/bin/sqlcmd -S localhost -U sa \
 -P yourStrong(!)Password

Error:

Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout
  expired. Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : TCP
  Provider: Error code 0x2749. Sqlcmd: Error: Microsoft ODBC Driver 17
  for SQL Server : A network-related or instance-specific error has
  occurred while establishing a connection to SQL Server. Server is not
  found or not accessible. Check if instance name is correct and if SQL
  Server is configured to allow remote connections. For more information
  see SQL Server Books Online..

I also tried to connect in using powershell via my host
Link:https://learn.microsoft.com/en-us/sql/linux/quickstart-install-connect-docker
Command:
sqlcmd -S 192.168.0.110,1433 -U SA -P yourStrong(!)Password

Note: 192.168.0.110(got this from running ipconfig in host machine.)
Any help ?

A: I found out the problems after some trials and errors, and re-reading the documents. I should use double quotes for the arguments when I executed my command in PowerShell.
I was looking into the wrong direction. Initially I executed the command:
docker run -e 'ACCEPT_EULA=Y' --name mssql -e \
 'SA_PASSWORD=yourStrong(!)Password' -p 1433:1433 -d \
 microsoft/mssql-server-linux:latest

Container stopped automatically by itself every time it starts.
Then, I did some googling and found:
docker run -e 'ACCEPT_EULA=Y' --name mssql -e \
 'SA_PASSWORD=yourStrong(!)Password' -p 1433:1433 -it -d \
 microsoft/mssql-server-linux:latest /bin/bash

It seemed fine on the surface. It got executed successfully in PowerShell. It didn't stop automatically anymore.If I dig deeper using
docker container logs mssql

to see the log for mssql. No error given, just that I don't see a lots of info given, which led me to think that there were no problems in my command.
But the right way to run these commands is using double quotes.
Link: https://hub.docker.com/r/microsoft/mssql-server-linux/
IMPORTANT NOTE: If you are using PowerShell on Windows to run these commands use double quotes instead of single quotes.
E.g.
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=YourStrong!Passw0rd" -p 1401:1433 --name sql1 -d microsoft/mssql-server-linux:2017-latest

I am also able to login using SSMS with:

*

*Server name: Hostip,1401

*Username: sa

*Password:yourpassword

A: Try 127.0.0.1 or 0.0.0.0 instead of localhost
For example :
docker exec -it mssql /opt/mssql-tools/bin/sqlcmd -S 127.0.0.1 -U sa -P 'yourStrong(!)Password'

A: docker run command syntax is the following:
Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

When you execute the command:
docker run -e 'ACCEPT_EULA=Y' --name mssql -e 'SA_PASSWORD=yourStrong(!)Password' -p 1433:1433 -it -d microsoft/mssql-server-linux:latest /bin/bash

/bin/bash in the end overrides CMD layer defined in the Dockerfile of microsoft/mssql-server-linux image.
So, just start a container without any additional command in the end:
$ docker run -e 'ACCEPT_EULA=Y' --name mssql -e 'SA_PASSWORD=yourStrong(!)Password' -p 1433:1433 -it -d microsoft/mssql-server-linux:latest

And now you are able to access a MSSQL:
$ docker exec -it mssql /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P 'yourStrong(!)Password'
1>

A: I'm new to Docker and I also I had the same issue when I try to connect to the SQL Server container from my application(or sqlcmd app container from Microsoft) which is also running in another Docker container. It looks like each container gets its own subnet IP address, so 'localhost' would never work if you're trying to connect to the SQL from another container.
The command below will give you the full list of IP addresses in the bridge network. You can specify the IP directly in the connection string.
docker network inspect bridge

A: From your message, it looks the server is not configured to access remotely. Can you follow the way mentioned below to enable it?
Using SSMS (SQL Server Management studio):
In Object Explorer, right-click a server and select Properties.
Click the Connections node.
Under Remote server connections, select  the Allow remote connections to this server check box.
Thanks,
Ananda Kumar J.


text:
Q: POSIX Characters not working on CodeBuild Server I am trying to use a linux command to get a version number from my package.json file in a node project during the build. I am using a Ubuntu 18.04 image in Codebuild. I have the following command that I would like to run from the buildspec.yml:
export PACKAGE_NAME=$(cat package.json | grep name | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g')

The problem with this command is that the awk -F: is invalid YAML. To remedy this, I added a POSIX space character:
export PACKAGE_NAME=$(cat package.json | grep name | head -1 | awk -F:[[:space:]] '{ print $2 }' | sed 's/[",]//g')

This command works on Git Bash in Windows, it works on Ubuntu WSL, it works on Ubuntu 18.04 launched in an EC2 instance, but it fails to work when run by CodeBuild (variable comes back empty), which doesn't make any sense to me as a Linux command should work the same on the same type of Linux. I verified that the package.json is in the root and accessible.
So is there a syntactically better way for me to achieve my goal, or is there a way to make CodeBuild read the command the same way the rest of linuxes do?

A: I solved this by installing jq on my image and then using it instead:
PACKAGE_VERSION=$(jq -r ".version" package.json)


text:
Q: Is Hibernate deprecated? This morning I was aboard a S-Bahn (German Subway) and I met a fellow student, who works for IBM. What he is doing there is Java EE optimization. I told him about my little project. And he recommended not to use 'oldschool' Hibernate. That's why my question is:
Is Hibernate deprecated?
(In combination with Java EE/Web Development)
..or did he just prate..

A: Hibernate, apart from being an implementation of JPA, does provide a lot of extra advanced feature that JPA lacks of (extra syntax in query, QBC support etc).  Some of them are really useful and hard to find a workaround in JPA world (yet).  Without providing such features, it is hard to say JPA can "replace" Hibernate (hence, saying Hibernate being deprecating)

A: Hibernate is the JPA provider offered by JBoss, which is a Java EE server, so I doubt that Hibernate as an implementation is deprecated.
Perhaps he meant that using Hibernate within a Java EE server , bypassing the container-provider persistence, is deprecated and you should rely on our container for such services.

A: No, Hibernate is not deprecated.
However, there's now JPA (Java Persistence API), which is a standard API for doing the things that Hibernate does.
Note that JPA is just an interface specification. You'll need something that implements JPA, and Hibernate is one of the implementations of JPA. Besides Hibernate, there are a few others such as EclipseLink (the official reference implementation for JPA) and Apache OpenJPA.

A: No, there is no way that Hibernate is deprecated. There is the JPA which is a persistence specification and Hibernate implements it. Also Hibernate has its own advanced features that JPA does not have and that's why Hibernate is the main source of new features that are added to the JPA standard.

A: One possible reason why he may have suggested you against Hibernate is that for a small project, the overhead of understanding Hibernate can be quite significant.
Hibernate is vast to say the least. Though it can be used in a simple way, but to find that out too, you'll need to comprehend a whole lot more.
but be rest assured that Hibernate is NOT deprecated, or going to be any time in the distant future. it's just that if your ORM needs are modest, you might want to try other solutions like iBATIS

A: JPA is only one way to do it. There's still Spring and all the other frameworks where Hibernate is well alive.

A: Based on what you said, it sounds like he may have been referring to Hibernate xml mappings, in contrast to using Hibernate annotations or JPA.  XML is most certainly old-school rubbish.


text:
Q: Integration of Alexa Voice Service with ionic I want to build a hybrid ionic application for android and ios device for my alexa skill. Where my ionic application will catch user's voice and send it to alexa skill and afterthat processing from lambda function, the result will be speak out from ionic application. Is it possible with Alexa Voice Service? How to do that?

A: That's not how the voice assistant devices work.
You can write a skill that can be used on the device.
Embedding Alexa into your application is not an option.
The only way Ionic Framework would come into play is if you built an admin panel to configure options for the skill.
You also asked about Alexa Voice Service in the comments. This is for embedding Alexa into your device. It is a full copy of Alexa added into your device, not a way to deploy your own Alexa Skill to a device.

A: Hi we can integrate aws lex in ionic app, below is the link for reference.
https://aws-amplify.github.io/docs/js/angular#ionic-4-components


text:
Q: Symfony3: Return a full JsonResponse loop I just created a project to try Algolia search solution and it's working good, but I'm not able to return a JSON response.
Here is my code
controller:
/**
 * @Route("/api/search/user/{query}", name="search_query")
 */
public function searchAction($query)
{
    $entityManager = $this->getDoctrine()->getManagerForClass(User::class);

    $users = $this->indexManager->search($query, User::class, $entityManager);

    if($users) {
        $result = $this->renderView('xxx/search_user.html.twig', [
            'users' => $users
        ]);

        return new JsonResponse(['success' => true, 'users' => [$result]]);
    }

    return new JsonResponse(['success' => false, 'users' => []]);
}

html:
{{ users[0].username }}

This code is working but only returning 1 user not all users, idem if I do a loop inside my twig file it will render all users but not in a good way:
screenshot
Thanks for the help and sorry for my english.

A: this is because twig creates the view on the server after the response.
I suggest you to simply create the users array directly inside the controller and remove the part of render view.
for example :
foreach($users as $user) {
$result[]['name'] = $user['name'];
}

and then use $result.
I hope it helps you, Regards


text:
Q: HorizontalScrollView don't works with buttons For some reasons, when I start adding buttons to  I received error.
I found in web, what someone changed android version and it's helped to him, I changed android version from 25 to 19, but this not helped to me.
<HorizontalScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minWidth="25px"
    android:minHeight="25px">
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="1"
    android:id="@+id/button1" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="2"
    android:id="@+id/button2" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="3"
    android:id="@+id/button3" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="4"
    android:id="@+id/button4" />
</HorizontalScrollView>

Need to show buttons, but I received an error
Indirect rendering enabled
Bridge [resources.resolve] Couldn't resolve resource @string/abc_action_bar_home_description
Failed to process message Load
mono.android.DesignerException: java.lang.IllegalStateException
    at mono.android.DesignerException.fromThrowable(DesignerException.java:54)
    at mono.android.DesignerSession.checkRenderResultForError(DesignerSession.java:215)
    at mono.android.DesignerSession.load(DesignerSession.java:302)
    at mono.android.DesignerSession.processMessage(DesignerSession.java:665)
    at mono.android.MessageListener.executeMessage(MessageListener.java:88)
    at mono.android.MessageListener$Runner.run(MessageListener.java:44)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: HorizontalScrollView can host only one direct child
    at android.widget.HorizontalScrollView.addView(HorizontalScrollView.java:251)
    at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:867)
    at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
    at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:866)
    at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:394)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:327)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:386)
    at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:270)
    at mono.android.DesignerSession.load(DesignerSession.java:289)

A: We can see the error log: java.lang.IllegalStateException: HorizontalScrollView can host only one direct child, so you can add a container to wrap these Buttons,e.g. a LinearLayout,  just as follows:
<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:minWidth="25px"
    android:minHeight="25px">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:id="@+id/button1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2"
            android:id="@+id/button2" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="3"
            android:id="@+id/button3" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="4"
            android:id="@+id/button4" />

    </LinearLayout>
</HorizontalScrollView>

The effect is:


text:
Q: how to control the sort order of shipping method's rates in the same carrier class? I'm trying to build a custom carrier-class (shipping method) that display shipping methods based on time/date related third party API, I tried to find out a solution to sort the below options but I failed
Has anyone faced such an issue? How does Magento sort these options?
Any help is really appreciated!
Thanks

adding code sample :
    /**
     * {@inheritdoc}
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }
        try {
            // get current quote id
            $quoteId = false;
            $items = $request->getAllItems();
            foreach ($items  as $item) {
                $quoteId = $item->getQuoteId();
                break;
            }
            /**  Quote $quote */
            $quote = $this->quoteFactory->create()->load($quoteId);
            $shippingAddress = $quote->getShippingAddress();
            $lat = (float) $shippingAddress->getData('latitude');
            $lng = (float) $shippingAddress->getData('longitude');
            if (!$lat || !$lng) {
                return false;
            }

            $isIn = $this->descartes->IsIn($lat, $lng);
            if (!$isIn) {
                // @todo handle logging here
                return false;
            }

            $shippingPrice = 10 ;
            $result = $this->_rateResultFactory->create();
            $slotsData = $this->descartes->getAvailableSlots();
            $lockBelow = (int) $this->getConfigData('capacitylock');
            $i = 1;

            foreach ($slotsData as $date => $slots) {
                foreach ($slots as $time => $slot_info) {
                    $capacity = (int) $slot_info['available_capacity'];
                    $id = (int) $slot_info['id'];
                    if ($capacity <= 0) {
                        continue;
                    }
                    switch ($capacity) {

                        case $capacity > $lockBelow:
                            $i = sprintf('%02d', $i);
                            /** @var Method $rate */
                            $rate = $this->_rateMethodFactory->create();
                            $rate->setCarrier($this->_code);
                            $rate->setCarrierTitle($this->getConfigData('title'));
                            $rate->setMethod($id);
                            $rate->setMethodTitle($date . "_" . $time);
                            $rate->setPrice($shippingPrice);
                            $rate->setCost($shippingPrice);
                            $rate->setSortOrder($i);
                            $result->append($rate);
                            break;
                    }
                    $i++;
                }
            }
            return $result;
        } catch (\Exception $e) {
            $this->manager->addErrorMessage($e->getMessage());
            return false;
        }
    }

sample slots API response :
array(2) {
  ["2020-05-13"]=>
  array(7) {
    ["2:00 PM-4:00 PM"]=>
    array(2) {
      ["id"]=>
      int(568)
      ["available_capacity"]=>
      int(-1)
    }
    ["4:00 PM-6:00 PM"]=>
    array(2) {
      ["id"]=>
      int(570)
      ["available_capacity"]=>
      int(24)
    }
    ["6:00 PM-8:00 PM"]=>
    array(2) {
      ["id"]=>
      int(555)
      ["available_capacity"]=>
      int(25)
    }
    ["8:00 PM-10:00 PM"]=>
    array(2) {
      ["id"]=>
      int(566)
      ["available_capacity"]=>
      int(25)
    }
    ["10:00 AM-11:59 AM"]=>
    array(2) {
      ["id"]=>
      int(482)
      ["available_capacity"]=>
      int(25)
    }
    ["10:00 PM-11:59 PM"]=>
    array(2) {
      ["id"]=>
      int(671)
      ["available_capacity"]=>
      int(25)
    }
    ["12:00 PM-2:00 PM"]=>
    array(2) {
      ["id"]=>
      int(678)
      ["available_capacity"]=>
      int(25)
    }
  }
  ["2020-05-14"]=>
  array(7) {
    ["2:00 PM-4:00 PM"]=>
    array(2) {
      ["id"]=>
      int(568)
      ["available_capacity"]=>
      int(25)
    }
    ["4:00 PM-6:00 PM"]=>
    array(2) {
      ["id"]=>
      int(570)
      ["available_capacity"]=>
      int(25)
    }
    ["6:00 PM-8:00 PM"]=>
    array(2) {
      ["id"]=>
      int(555)
      ["available_capacity"]=>
      int(25)
    }
    ["8:00 PM-10:00 PM"]=>
    array(2) {
      ["id"]=>
      int(566)
      ["available_capacity"]=>
      int(25)
    }
    ["10:00 AM-11:59 AM"]=>
    array(2) {
      ["id"]=>
      int(482)
      ["available_capacity"]=>
      int(25)
    }
    ["10:00 PM-11:59 PM"]=>
    array(2) {
      ["id"]=>
      int(671)
      ["available_capacity"]=>
      int(25)
    }
    ["12:00 PM-2:00 PM"]=>
    array(2) {
      ["id"]=>
      int(678)
      ["available_capacity"]=>
      int(25)
    }
  }
}

A: Ok, take a look here:
vendor/magento/module-shipping/Model/Rate/Result.php

There is function sortRatesByPrice();
This foreach puts all in array for sorting:
foreach ($this->_rates as $i => $rate) {
        $tmp[$i] = $rate->getPrice();
    }

If you change this $rate->getPrice() to $rate->getMethodTitle() it will sort by method title, that in your case is date and time.
I haven't looked deeper, but you can try to do plugin here or overwrite with preference. Just try and see. I think you will manage how to sort now.
That sortRatesByPrice() is called here vendor/magento/module-shipping/Model/Rate/CarrierResult.php, function public function getAllRates().

A: I think you can simply sort first the array before your foreach using at least asort()

asort() - sort associative arrays in ascending order:

asort($slotsData)
foreach ($slotsData......){}


text:
Q: How to convert pdo_sqlsrv code to pdo_odbc? I have the following code that is working fine.
$dsn = 'sqlsrv:server = tcp:my_server_host,my_port; Database = my_database';
$connection = new PDO($dsn, $user, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $connection->query('SELECT * FROM my_table');

But the problem is, on the production server the pdo_sqlsrv driver is not installed, and instead pdo_odbc is installed.
So how to convert the above code so that it uses the pdo_odbc driver?
I have tried with the following code.
$dsn = 'odbc:mssql;Server=my_server_host.net;Port:my_port;Database=my_database';
$connection = new PDO($dsn, $user, $passowrd);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $connection->query('SELECT * FROM my_table');

But I am getting the following error.
PDOException: SQLSTATE[IM002] SQLDriverConnect: 0 [unixODBC][Driver Manager]Data source name not found and no default driver specified

Note: My production server is not on Windows.


text:
Q: Bash command to determine is it the first ssh connection after the reboot? Like the following answer Bash command to determine first login for a particular time period, instead of for a duration I want to find out to check is the first time the user connected into machine using ssh.
Is it possible to find out it a specific user?

A: This line should print "First" if it's the first login by user "user" since reboot from non-local host:
[ $( last | sed '/^reboot/,$d' | egrep '^user +pts/' | wc -l ) -lt 2 ] && echo First

Note that the last log is usually rotated monthly, so the answer might be incorrect if the user has logged in more than one month ago.
I anchor the expression with ^ to make sure the user name is picked from the first column (should the user's name be still, we'd get a false hit on lines reading still logged in :-) and I also expect pts/ to appear, indicating a remote login (local logins are indicated with tty instead).
This should work even if the computer hasn't been rebooted current month. But it would not work if your user's login name is verbatim reboot.


text:
Q: can't get PORTB value in pic18f2550 I'm trying to send The PORTB to the serial port and receiving the data on pickit2 UART mode..
void main()
{
  TRISB = 0xFF;
  PORTB = 0;
  UART1_Init(9600); // Initialize UART module at 9600bps
  Delay_ms(100); // Wait for UART module to stabilize
  while (1)
  { // Endless loop
    UART1_Write(PORTB); // and send data via UART
    Delay_ms(500);
  }
}

I'm using MikroC pro. and the problem is I'm not getting proper data.
I've connected pullup resistors to each pin of PORTB and all i get is
RX: E0

which means only RB5, RB6, and RB7 are pulled up rest pins are low.
also noticed if i try to pull down any pin of portb then only these pins cause the value to change. any ideas what might be wrong?

A: According to the datasheet, on start-up RB4:RB0 are configured as analog inputs and will read as zero.
You need to make them digital inputs instead during initialisation, for example:
ADCON1 = 0x0E;

Alternatively, you can clear the PBADEN bit in the CONFIG3H register by changing your configuration settings.


text:
Q: Evaluating variable - output json file contents In the bash shell, I'm trying to read the json file and load to a variable
eri@xyz:~/Documents/inbound>e1=$(eval echo $(cat ./deploy/request.json))

Upon fetching the output of that variable, I'm seeing -bash - command not found along with the actual contents of the .json file
eri@xyz:~/Documents/inbound>"$e1"

-bash: { type:Pipeline, category:Software, risk:4, short_description:sample short description text, description:sample detailed description text, assignment_group: Services - Retail Services, cmdb_ci:Retail Service, u_version:1.0, start_date:2017-01-04 18:00:00, end_date:2017-01-04 19:00:00, backout_plan:see department for standard backout plan, implementation_plan:sample implementation plan, test_plan:sample text plan, production_system:false }: command not found

Is there a way to suppress the -bash - command not found in the output?.

A: No need for eval - just e1=$(< ./deploy/request.json) should do the trick.  (Thanks to @shellter for the syntax — you don't even need to use cat!)
To show the variable, you want
echo "$e1"

instead of just "$e1".  "$e1" by itself on the command line does not print out the value of $e1, unlike many programming-language REPLs.  Instead, it tells bash to try to interpret the entire contents of $e1 as the name of a command.  It isn't the name of a command, so bash tells you a command by that name cannot be found.


text:
Q: C# Invoke, The thread tried to read from or write to a virtual address for which it does not have the appropiate access We've had an application written in C# running somewhere for a few years.
After a few years, at random times the application crashed. It doesn't hang but just closed itself.
I started by adding a lot of logging through log4net to a textfile.
This way i discovered the application crashed on invoking a method from another class.
    log.Info("Class OPC - groupRead_DataChanged() - " + "beelden van inputname " + inputname + " op cameo zetten");
try
{
    cameoControl1.Invoke(new Action(() => cameoControl1.AddCameras(CameraGrid)));
}
catch (Exception exc)
{
    log.Info("Class OPC - groupRead_DataChanged() - " + "cameoControl1.Invoke werkte niet. " + exc);
    log.Error("Class OPC - groupRead_DataChanged() - " + "cameoControl1.Invoke werkte niet. " + exc.Message);
    log.Error("Class OPC - groupRead_DataChanged() - " + "cameoControl1.Invoke werkte niet. " + exc.InnerException);
    log.Error("Class OPC - groupRead_DataChanged() - " + "cameoControl1.Invoke werkte niet. " + exc.Source);
    log.Error("Class OPC - groupRead_DataChanged() - " + "cameoControl1.Invoke werkte niet. " + exc.StackTrace);
    log.Error("Class OPC - groupRead_DataChanged() - " + "cameoControl1.Invoke werkte niet. " + exc.TargetSite);
}
log.Info("Class OPC - groupRead_DataChanged() - " + "beelden van inputname " + inputname + " staan nu op cameo 1");
}

The log files show "beelden van inputname..... op cameo zetten".
But then, nothing... it doesn't even get to the logs in the catch.
I've set it up to create dump files on crash which gave me the following information:

Exception Code: 0xC0000005
Exception Information: The thread tried to read from or write to a
virtual address for which it does not have appropriate access

After looking this up, I came to the conclusion that there are multiple causes possible: https://www.stellarinfo.com/blog/how-to-fix-error-code-0xc0000005-in-windows/
RAM could be defect, disk errors, ...
We have 3 of the same PC's with a variant of this application.
Only 1 has these issues. So I made an image of another one, restored it on the faulty PC and put the correct application on it. The issue remained.
So now I'm wondering, could it really be a hardware defect?
How can defect RAM cause this kind of issues? Wouldn't the OS (Windows 10) be taking care of it?


text:
Q: Prime number checking function not working for negative numbers def is_prime(x):
    x = abs(x)
    if x == 0 or x == 1:
        return False
    elif x == 2:
        return True
    for i in range(2, x):
        if x%i == 0:
            return False
    return True

The tester says the above code shouldn't return true for x = -7.
Please help.
Thank you :)
**Edit: **
im so sorry, just read somewhere that any number less than 2 (i.e 0, 1 and all negative numbers are not prime

A: It does return True for me. Check the value of x after you call abs(x), it will maybe help.

A: It does return True for negative numbers for me.
Also you can run the loop from 2 to x/2 and reduce the complexity.

A: My Python is not good, but something like this should work better:
def is_prime(x):
    # Handle 1, 0 and negatives.
    if x < 2:
        return False
    # Handle even numbers.
    elif x % 2 == 0:
        return x == 2
    # Test with odd divisors.
    for i in range(3, sqrt(x), 2):
        if x % i == 0:
            return False
    return True

The sqrt(x) limit is a big time saver, and dealing with even numbers separately can halve the time with well mixed inputs.


text:
Q: How to tell a setup file to install to the Documents folder with Inno Setup compiler? I'm trying to create a setup file using Inno Setup Compiler, and I want it to install to the Documents folder as it needs to create and then delete a file, something that it can't do if it installs to Program Files. I've tried using %userprofile%\Documents as that works in File Explorer, but that simply creates a folder called %userprofile% wherever the Setup.exe is, and  C:\Users\%username%\Documents simply creates the %username% folder in the Users folder. How do I get it to install into the Documents folder no matter where it is?

A: While @GTAVLover is right, you will most probably want to use the {userdocs} or {commondocs} constant in standard Inno Setup sections, likes [Files].
The syntax is like:
[Files]
Source: "readme.txt"; DestDir: "{userdocs}"

Had you wanted to refer to environment variables (what is not the right way in this case), use {%NAME} syntax:
[Files]
Source: "readme.txt"; DestDir: "{%USERPROFILE}\Documents"

A: You should use Inno Setup Shell Folder Constants to do this.
See more at Inno Setup Help.
Use ExpandConstant('{userdocs}') where you want to get path of Documents folder (For current user).
It will return "OS Drive:\Users\CurrentUser\Documents".
Eg:
MsgBox(ExpandConstant('{userdocs}'), mbInformation, MB_OK);

For all users, you should replace userdocs with commondocs.
So, It will return "OS Drive:\Users\Public\Documents".


text:
Q: Can a point source be located more accurately out-of-focus or in-focus? Let's say I am taking a picture, and I know a priori that the image is of a single ideal point source of light at infinity.
With a perfect imaging system in focus, the image shows an Airy disk. I already knew to expect an Airy disk, so I can do some mathematical fitting to guess the center of the Airy disk. That's my best guess for the source location.
Alternatively, the imaging system might be somewhat out of focus. The image would show a much bigger blurry circle. Again, I can do some mathematical fitting to guess the center of the blurry circle. Again, that's my best guess for the source location.
My question is: Which approach would give me more accurate information about the location of the point source?
I can't see an obvious answer. In the out-of-focus image, you are drawing useful information from a much greater number of pixels, which is usually helpful in mathematical fitting. (Particularly if a large pixel size limits the resolution.) On the other hand, we normally say that defocusing an image simply erases its small-scale information, and I've never heard of anyone defocusing an imaging system on purpose like that!

A: If the Airy disk is smaller than a pixel (rather common), then you want to defocus.  Star trackers on satellites do this in order to get sub-pixel pointing accuracy.  If the Airy disk is much larger than a pixel, then you probably don't want to defocus.  In the latter case the situation is complicated by aberrations and the problem of modeling the shape of the spot on the focal plane, which in general is no longer circular.  That modeling problem might be more accurate for the in-focus case.   I suppose as a practical matter one might do the best one can in the design stage, but then actually measure point spread functions for various angles.  That is, calibrate the actual device.  (That's speculation.)
But if you calculate the size of the Airy disk for typical devices you will find that it's generally smaller than a pixel, so defocussing usually wins.

A: In the absence of noise they can both work the same (assuming you know the exact amount of defocusing, and you over-sample the Airy disk)
In the presence of realistic noise, you are better off focusing the object due to the details of the noise.  For intensity images, you are (likely) dealing with Riciean distributed data, and you are better off using a smaller number of samples with larger real intensity than a large number of samples all with low intensty.


text:
Q: Complex SQL queries I have a table called
Subscriptions (user_name varchar(50) , video_name varchar(50), watched_date date)

ravi      simsons         2016-01-01
ravi      dailyshow       2016-02-15
nitin     dailyshow       2016-02-24
nitin     simsons         2016-02-25
sam     simsons           2016-03-04
sam       dailyshow       2016-03-04
mat          simsons         2016-04-06
cranw  simsons         2016-04-15
cranw     dailyshow       2016-04-17
simsons and dailyshow are the names of the video
I need to find the distinct count of user_names who watched Simsons before dailyshow.
I'm struggling to do with a self-join and case statement but still cannot get the correct query.

A: This can be done with separate inline views for each video_name and joining them on user_name. Then use a where clause for the watched_date condition.
select count(distinct sdaily.user_name)
from (select * from subscriptions where video_name = 'simsons') ssim
join (select * from subscriptions where video_name = 'dailyshow') sdaily
on sdaily.user_name = ssim.user_name
where ssim.watched_date < sdaily.watched_date

A: I think this is easiest using aggregation:
select count(*)
from (select s.user_name,
             min(case when s.video_name = 'simsons' then s.watched_date end) as s_date,
             max(case when s.video_name = 'dailyshow' then s.watched_date end) as ds_date
     from subscriptions
     group by s.user_name
    ) u
where s_date < ds_date;


text:
Q: Passing non-temporary object to const string reference still prints garbage I was trying to write an iterator by myself for my_vec:
#define BEGIN true
#define END false
#include <vector>
#include <iostream>

template<typename Container>
class my_vec {
private:
    class iterator {
        const my_vec *this_vec;
        using iterator_type = typename std::vector<std::pair<int, const Container&>>::const_iterator;
        iterator_type itr;
    public:
        iterator(const my_vec &s, bool state) :
                this_vec(&s) {
            if (state == BEGIN) {
                itr = s.v.begin();
            } else { /*(state==END)*/
                itr = s.v.end();
            }
        }
        iterator& operator++() {
            itr++;
            return *this;
        }
        std::pair<int, const Container&> operator*() const {
            return std::make_pair(1, this_vec->dog);
        }
        bool operator!=(iterator other) const {
            return itr != other.itr;
        }
    }
    ;
public:
    std::string dog = "DOG";
    std::vector<std::pair<int, Container>> v;
    my_vec(int space) {
        v.reserve(space);
    }
    iterator begin() const {
        return iterator(*this, BEGIN);
    }
    iterator end() const {
        return iterator(*this, END);
    }
}
;

However, when running the following main.cpp:
#include "my_vec.h"

int main() {
    my_vec<std::string> t(6);
    t.v.emplace_back(std::make_pair(1, "HELLO"));
    t.v.emplace_back(std::make_pair(2, "BYE"));
    t.v.emplace_back(std::make_pair(3, "CAT"));

    for (const auto &pair : t) {
        std::cout << pair.first << std::endl;
        std::cout << pair.second << std::endl;
    }
    return EXIT_SUCCESS;
}

The expected output is:
1
DOG
1
DOG
1
DOG

However, the actual output is:
1

and then the program stops or prints garbage.
It seems like the problem is in this function:
std::pair<int, const Container&> operator*() const {
            return std::make_pair(1, this_vec->dog);
        }

Why is this behavior happening as 'dog' is not a local variable?
Also, how can it be fixed without changing the function definition of operator*?

A: std::make_pair(1, this_vec->dog) returns a temporary (let's name it t) of type std::pair<int, std::string>. Then the return value (let's name it r) of type std::pair<int, const std::string&> is constructed from t, whereby r.second is bound to t.second. Finally, the temporary t is destroyed and r is returned to the caller, holding a dangling reference. An attempt to use this return value exhibits undefined behavior.
Make it
return {1, this_vec->dog};

This constructs the return value directly, without an intermediate temporary pair.


text:
Q: Unable to load AWS credentials from any provider in the chain after upgrading to tomcat 8.5 Our legacy java web application runs on aws elastic beanstalk, which assumes IAM role to access SES. Today after upgrading elastic beanstalk environment from Tomcat 7 to Tomcat 8 and spring libraries from 3.2.1 to 4.0.0, SES client has stopped working. Below is code which was working fine until yesterday to send out emails:
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
                    .withCredentials(com.amazonaws.auth.DefaultAWSCredentialsProviderChain.getInstance())
                    .withRegion(Regions.US_EAST_1).build();

It is throwing following exception
SEVERE [http-nio-8080-exec-8] The email was not sent.
    com.amazonaws.SdkClientException: Unable to load AWS credentials from any provider in the chain: [EnvironmentVariableCredentialsProvider: Unable to load AWS credentials from environment variables (AWS_ACCESS_KEY_ID (or AWS_ACCESS_KEY) and AWS_SECRET_KEY (or AWS_SECRET_ACCESS_KEY)), SystemPropertiesCredentialsProvider: Unable to load AWS credentials from Java system properties (aws.accessKeyId and aws.secretKey), com.amazonaws.auth.profile.ProfileCredentialsProvider@79fc4ef8: profile file cannot be null, com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper@33e618b9: Unauthorized (Service: null; Status Code: 401; Error Code: null; Request ID: null)]

I have tried adding AWS_ACCESS_KEY_ID and AWS_SECRET_KEY as environment variables as well but it didn't work. Searched web, checked aws docs but without anyluck.

A: I resolved this by upgrading to the latest AWS SDK version.


text:
Q: sql join history table to active table SSRS report I'm trying to pull results from a database (sql server 2005) which takes 4 tables:
Subscriber S, Member M, ClaimLines L, ClaimHistoryLines H
Query is as follows:
select S.SBSB_ID, M.MEME_NAME,
(CASE L.CLCL_ID WHEN '' THEN H.CLCL_ID ELSE L.CLCL_ID END) AS CLAIM_ID
FROM CMC_CDDL_CL_LINE L, CMC_MEME_MEMBER M LEFT OUTER JOIN CMC_CLDH_DEN_HIST H
ON H.MEME_CK = M.MEME_CK, CMC_SBSB_SUBSC S
WHERE
S.SBSB_ID = '120943270' AND
L.MEME_CK = M.MEME_CK AND
M.SBSB_CK = S.SBSB_CK

This query successfully pulls in the result rows from the ClaimLines L table but no results from the History table are shown. I'm not sure how to do this, any sql experts out there that can help would be great. -Thanks!

A:
CMC_CDDL_CL_LINE L, CMC_MEME_MEMBER M LEFT OUTER JOIN CMC_CLDH_DEN_HIST H

don't mix obsolete implied join syntax with left join. They don't play well together. Use the correct ANSII standard join syntax. Infact stop using the obsolete syntax altogether.

A: This was a very silly mistake on my part. I neglected to think of using a UNION which solved my problem and allowed me to pull from both places into a single results set without creating massive duplicate rows. Glad someone pointed out the proper way to write sql using ANSII standards.
select S.SBSB_ID, M.MEME_NAME,
L.CLCL_ID AS CLAIM_ID
FROM
CMC_SBSB_SUBSC S INNER JOIN CMC_MEME_MEMBER M ON S.SBSB_CK = M.SBSB_CK
INNER JOIN CMC_CDDL_CL_LINE L ON L.MEME_CK = M.MEME_CK
WHERE
S.SBSB_ID = '120943270'
UNION
select S.SBSB_ID, M.MEME_NAME,
H.CLCL_ID AS CLAIM_ID
FROM
CMC_SBSB_SUBSC S INNER JOIN CMC_MEME_MEMBER M ON S.SBSB_CK = M.SBSB_CK
INNER JOIN CMC_CLDH_DEN_HIST H ON H.MEME_CK = M.MEME_CK
WHERE
S.SBSB_ID = '120943270'


text:
Q: Array Printing out Process for these lines I just want to know the process of how these two lines of code come up with the answer 7.
    int[] favNum = {2, 3, 5, 7, 1, 6, 4};
    System.out.println(favNum[favNum[favNum[4]]]);

A:
Analyze this:

!favNum[4] selects the value from cell (4) of array favNum so favNum[4]=1;
!favNum[favNum[4]] selects the value from cell favNum[4]=1 of array favNum so favNum[favNum[4]]=fanNum[1]=3;
*and so !favNum[favNum[favNum[4]]]=favNum[favNum[1]]=favNum[3]=7.
So you start reading this from inside and step by step to outside..

A: The expression favNum[favNum[favNum[4]]] has to be evaluated from inside to outside. Here I start with the innermost and end with the outermost

*

*favNum[4] -> fifth element of array, 1

*favNum[1] -> second element of array, 3

*favNum[3] -> fourth element, 7


text:
Q: Градиент фигуры, состоящей из кривых линий var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(0,0);
ctx.quadraticCurveTo(0,0,50,0);
ctx.quadraticCurveTo(5,5,0,50);
ctx.quadraticCurveTo(0,0,0,-50);
ctx.strokeStyle = '#FF0000'; // Цвет обводки
ctx.lineWidth = 3; // Ширина линии
ctx.stroke();

Этот код нарисует уголок закруглённый во внутрь (на треугольник смахивает). Как залить этот уголок градиентом?
A: Пример исходя из написанного на http://www.html5canvastutorials.com/tutorials/html5-canvas-linear-gradients/:
var grd = ctx.createLinearGradient(0, 0, 50, 50);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
ctx.fillStyle = grd;
ctx.fill();


text:
Q: Windows Phone 8. autocapitalize not supported in IE10 For iOS & Android, their webkit browsers support the autocapitalize property on an input element to control whether the first word of a sentence is capitalized.
On Windows Phone 8 IE10 this doesn't work. Does anyone know of an equivalent way of achieving auto-capitalization in IE10 on Windows Phone?

A: If it's not supported then you have to do it on your own via JavaScript. Assuming key and/or change events are being fired by the mobile browser, you could simply hook into these events and transform the input value accordingly.
Here's an example that transforms the very first letter which may be preceded by whitespace, and the first letter after a period that is followed by whitespace:
$('[autocapitalize="on"]').on('change keyup', function(event)
{
    var selectionStart = event.target.selectionStart;
    var selectionEnd = event.target.selectionEnd;

    var element = $(this);
    element.val(element.val().replace(/^\s*(.)|\.\s+(.)/g, function(letter)
    {
        return letter.toUpperCase();
    }));

    event.target.setSelectionRange(selectionStart, selectionEnd);
});

jsfiddle example


text: Q: Does the Polish character Ł have an established mathematical meaning I was suggested to use the slashed letter $\L$ (the European character Ł, which looks like the English letter L with a small bar crossing its vertical part) to denote the left half-plane. To avoid conflict with possible common usage, could someone tell me other usages of this notation in mathematics please?


text:
Q: How to create a listing on OpenSea by program? How can I create a new listing per program on OpenSea? If I use the GUI, I can create a new item and collections, and it doesn't cost anything (besides the first time I created the account), until someone buys it. But in the developer documentation I found only this:
https://docs.opensea.io/docs/setting-up-your-smart-contract-project
But looks like if I follow this, I already need to pay gas fee, and then not even one item is listed.
I understand that OpenSea uses lazy minting. It gets only minted when someone buys it. So how can I create such a lazy mint?


text:
Q: Unit Testing button_Click in WP7 Silverlight application I m not using MVVM model for my WP7(C#) application. Now I want to test button2_click function from my unit testing code so that the code inside the button_click gets executed. Please let me know if there is any possibility of doing this.
 private void button_Click(object sender, RoutedEventArgs e)
 {
         // Some code
 }

sample code could be really helpful.
Thanks,
Mugu

A: In general, UI code is not a good target for unit testing, regardless of whether you are using MVVM or not. You can unit test that button click handler just by calling it directly from your test. If the handler is using sender and expecting it to be a real button then you will have to work out the best approach to take, nobody can answer that without seeing your code.
Where MVVM would help you in this instance is it would allow you to move the code to the view model, and expose it via a property that returns an ICommand which you then bind to the Command property of the button. By using this approach you can encapsulate the code you would otherwise have embedded in the UI code behind and easily reuse the code in other commands (i.e. menu options).

A: I could suggest that you use an UI Autmation framework such as White but I won't.
I'd rather suggest that you separate your presentation/domain/whatever logic from your view using well established patterns like MVVM, MVP, MVC etc. The problem you just have run into is   one of the reasons why this is a good idea. Without it, you will run into more problems as you go.


text:
Q: C# Concurrent and Async Socket Connections I'm working on a simple socket server that is supposed to take in multiple connections and hand them off to a "connection" class by means of EndAccept() The problem is that after accepting a connection, the code doesn't accept anything further until the connection ends.
I create the socket in Main() like so, then I pass the socket to ServerEnvironment (static class) via Initialize().
MainSocket.Bind(new IPEndPoint(IPAddress.Parse(Addr), Port));
MainSocket.Listen(10);

ServerEnvironment.Initialize(MainSocket);

while (true)
{
    Console.ReadLine();
    Console.WriteLine(">>");
}

Once MainSocket has been passed, ServerEnvironment takes over from there.
static Socket MainSocket;

public static void Initialize(Socket _MainSocket)
{
    MainSocket = _MainSocket;

    AcceptGameConnection = new AsyncCallback(AddConnection);
    MainSocket.BeginAccept(AcceptGameConnection, null);
}

public static void AddConnection(IAsyncResult Result)
{
    Socket UserSocket = MainSocket.EndAccept(Result);
    ConnectionCount++;

    // Removed the stuff that happens to UserSocket because the same
    // symptoms occur regardless of their presence.

    MainSocket.BeginAccept(AcceptGameConnection, null);
 }

As I search about this question, I come to find that multithreading could be a necessity for my purposes. However, when I use Console.WriteLine(Thread.CurrentThread.ManagedThreadId); in both Initialize(); and AddConnection();, two different thread IDs appear, so I assume that multithreading is already a capability and I don't need to manually create a thread. That wouldn't explain my issue, though.
Is multithreading necessary for me to be able to have concurrent and asynchronous socket connectivity?
EDIT:
Binding error..was binding to my LAN address which caused some problems.

A: This is how you want to do this if you are using .net 4.0 or less
public static void Initialize(Socket _MainSocket)
{
    MainSocket = _MainSocket;

    AcceptGameConnection = new AsyncCallback(AddConnection);
    MainSocket.BeginAccept(result => {
        var userSocket = MainSocket.EndAccept(result);
        var thread = new Thread(AddConnection);
        thread.Start(userSocket);
        Initialize(MainSocket);
    }, null);
 }

 public static void AddConnection(IAsyncResult Result)
 {
     MainSocket.BeginAccept(AcceptGameConnection, null);
 }

 private static void AddConnection(Socket userSocket)
 {
     // Removed the stuff that happens to UserSocket because the same
     // symptoms occur regardless of their presence.
 }

But this is how you can do it in .net 4.5 or above.
public static void Initialize(Socket mainSocket)
{
    while(true)
    {
        var userSocket = await Task.Factory.FromAsync(
                                mainSocket.BeginAccept,
                                mainSocket.EndAccept);
        ThreadPool.QueueUserWorkItem(_ => AddConnection(userSocket));
    }
 }

 private static void AddConnection(Socket userSocket)
 {
     // Removed the stuff that happens to UserSocket because the same
     // symptoms occur regardless of their presence.
 }

A:
The problem is that after accepting a connection, the code doesn't accept anything further until the connection ends.

This happens because the next BeginAccept call is delayed by something, probably by code not shown here. Accepting asynchronously is almost always pointless. Don't copy blindly from the terrible Microsoft tutorials. Your accept loop should be:
while (true) {
 var socket = Accept();
 StartProcessing(socket); //Cannot block!
}

That's all.
You can implement StartProcessing using Task and await. This makes asynchronous socket IO rather simple to do. Alternatively, start a new task/thread per connection that you receive.

simple socket server

Such a thing does not exist. You better leave sockets alone and use a ready made higher level protocol such as WCF or HTTP.


text:
Q: Odoo V11 - how to set Kanban style with CSS class with field value as part of the class name There are some related questions online, but I haven't found a working answer yet, so here I go.
I have a custom module that adds a field to the crm.lead:
    xx_ue_brand_id = fields.Many2one('xx.ue.brand', string='Brand')

The related model holds not much more than a name and and active flag.
I'm using this already in the crm related views, so user can link a Lead to a specific brand.
Using the brand value, I would like to set a color on the kanban items.
As each brand has its specific color, I would prefer not to use the standard Odoo colors for the kanban-item, which can be set by the color picker and add a class like 'oe_kanban_color_5'
I defined my own css classes in a less file that is correctly loaded. There's a class for each brand, overruling the border color that is set on the kanban.
I included the brand name in the class definition, so it's clear for which brand the styling is used.
Like this:
    .crm_kanban_brand_*brandname-x* { &:after {background-color:#2E3092!important;} }

When I add this class via the developer tools of Chrome to a kanban item, the border is set in the right color.
But... (finally my question)
I can't get the classes set dynamically through an xpath expression, my best guess is something like the following.
    <xpath expr="//div[hasclass('o_dropdown_kanban')]/parent::div" position="attributes">
        <attribute name="t-att-class">'crm_kanban_brand_%s' % record.xx_ue_brand_id.name</attribute>
    </xpath>

Note, when I add the class definition without using a variable, the whole thing works as expected, adding the same class to all kanban items.
    <xpath expr="//div[hasclass('o_dropdown_kanban')]/parent::div" position="attributes">
        <attribute name="class">crm_kanban_brand_*brandname-x*</attribute>
    </xpath>

Any help on how I could use the field value as part of the class name would be greatly appreciated.

A: Thanks to the suggestion of CZoellner I finally ended up with using this as a working solution.
    <xpath expr="//div[hasclass('o_dropdown_kanban')]/parent::div" position="attributes">
        <attribute name="t-attf-class" separator=" " add="crm_kanban_brand_#{record.xx_ue_brand_id.value}"/>
    </xpath>

And found a reference to it in the Odoo documentation:
t-attf-$name
same as previous, but the parameter is a format string instead of just an expression, often useful to mix literal and non-literal string (e.g. classes):
    <t t-foreach="[1, 2, 3]" t-as="item">

<t t-esc="item"/>

    </t>

will be rendered as:

1

2

3


text:
Q: maven-war-plugin how to exclude provided jar from lib directory but include in manifest with prefix folder I am trying to build a skinny war for later inclusion in a large ear file.
The ear build is entirely separate to my war's project and expects me to provide a skinny war, with the correct manifest file, the ear promises to supply provided jars in its root /libs folder.
Problem I am facing is getting the war's manifest.mf file to specify that provided jar's are in the ear's /libs folder, and compile/runtime jars are in the war.
i.e. the manifest.mf class-path entry wants to look like this:
Class-Path: libs/commons-lang.jar commons-codec.jar

commons-lang is scoped to provided and expected to be in the ear's libs directory.
commons-codec is compile time and expected to be part of the war.
I've explored maven-war-plugin but can't figure out how to get it to supply the
classpathPrefix for just the provided dependencies.
Suggestions please?

The final adopted solution (thanks to all with tips and links)
Requires the dependencies provided by ear be scoped to provided and this, noticed the hack: fake-application.xml :
 <plugin>
    <!--required to fix the war's manifest and skinny the war-->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ear-plugin</artifactId>
    <version>2.10.1</version>
    <configuration>
        <defaultLibBundleDir>lib/</defaultLibBundleDir>
        <skinnyWars>true</skinnyWars>
        <generateApplicationXml>true</generateApplicationXml>
        <applicationXml>${project.basedir}/src/test/fake-ear/fake-application.xml</applicationXml>
    </configuration>
    <executions>
        <execution>
            <phase>verify</phase>
            <goals><goal>ear</goal></goals>
        </execution>
    </executions>
 </plugin>

I then deploy this new skinny war to the repository and did so using the maven deploy plugin:
<plugin>
    <!--used in release build to deploy skinny war to nexus-->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-deploy-plugin</artifactId>
    <version>2.8.2</version>
    <executions>
        <execution>
            <id>deploy-file</id>
            <phase>install</phase>
            <goals>
                <goal>deploy-file</goal>
            </goals>
            <configuration>
                <!--location of the skinny war after maven-ear-plugin builds it-->
                <file>${project.build.directory}/${project.artifactId}-${project.version}/${artifactid}-${project.parent.version}.war</file>
                <repositoryId>releases</repositoryId>
                <url>${distributionManagement.repository.url}</url>
                <groupId>${project.parent.groupId}</groupId>
                <artifactId>${artifactid}</artifactId>
                <version>${project.parent.version}</version>
                <packaging>war</packaging>
            </configuration>
        </execution>
    </executions>
</plugin>

A: @Tunaki's maven-ear-plugin suggestion seems better in a holistic manner, but anyway take a look: https://maven.apache.org/plugins/maven-shade-plugin/examples/executable-jar.html
You can modify the manifest this way:
<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.4.3</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <manifestEntries>
                    <Class-Path>libs/commons-lang.jar commons-codec.jar</Class-Path>
                  </manifestEntries>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>


text:
Q: Google Sheets: selecting cell values based on another cell MAX values I'm trying to make a database of students using Google Sheets. It contains info about students, groups and orders; orders can change students membership in groups (taken in a group, moved up to a new group, graduated, on leave, sent down). Here are sample database sheets and here is a detailed description of my DB structure (the sheet report_Groups is slightly changed, its previous variant, described on the link, is now named old_report_Groups).
I need a query that would select a list of present members of given group on the given date. That means that for each student I have to select
the name, the latter status before given date and corresponding group. And from this result select student names, where statuses are "Taken in" or "Moved Up" and group is the same as given one.
The problem is to select the latter status. It should be MAX(status), whose "since" date ≤ given date, but there's a well-known problem of selecting more than one field together with aggregate function. Here is a question which is very close to, but query from its "best" answer gives me error "QUERY:NO_COLUMN". I've even copied the sheet Raw from there and tried to perform proposed query (with the onliest modification — replacing commas with semicolons according to my locale restrictions) on the data it was reported to work on — same error (check Raw and report_Raw sheets in my DB). Other variant (via MMULT and TRANSPOSE) works, but it's perfomance is very poor.
What can you suggest me? Thanks in advance.
Update: I've found the solution with an issue (described in my answer).
To solve the issue I need to know an answer for a different question.

A: Here's the solution (with an issue described below).
A. Orders_Students is filtered for selecting rows, having "since" cell value ≤ given date (report_Groups!A2):
=QUERY(Orders_Students!B:E;"select E, B, C, D where E <= date '" & TEXT(report_Groups!A2;"yyyy-MM-dd") & "'";1)

This interim result is stored at the inner_report_Groups tab (it will be referenced few times in the next query).
B. inner_report_Groups is filtered for selecting MAX("since") values and corresponding row cell values for each student:
ARRAYFORMULA(VLOOKUP(QUERY({ROW(inner_report_Groups!A$2:A)\SORT(inner_report_Groups!A$2:D)};"select max(Col1) group by Col3 label max(Col1)''";0);{ROW(inner_report_Groups!A$2:A)\SORT(inner_report_Groups!A$2:D)};{3\4\5};0)

The formula above is used as inner query in report_Groups!D2 (also in D3, D4—with appropriate indeces).
C. The second query result is filtered to get students whose status is either "Taken in" or "Moved Up" and corresponding group is equal to the given group (report_Groups!B2 (also in B3, B4—with appropriate indeces)):
=TRANSPOSE(IFERROR(QUERY(<here is the formula from step B>);"select Col1 where Col3 = '" & B2 & "' and (Col2='Taken in' or Col2='Moved Up')";0)))

The formula above is used as outer query in report_Groups!D2 (also in D3, D4—with appropriate indeces). IFERROR is intended to display nothing if query result is #N/A.
That query displays the needed results as you can see in report_Groups tab. But as the query on step B searches the whole columns of inner_report_Groups, there's only a single given date can be analysed (or the  query interim results for other given dates should be placed in different columns of inner_report_Groups or at the different tab. Is there any way to give an alias for an interim result to refer it in a single cell formula instead of keeping it on different tab?


text:
Q: SQL to track customer's journey I have data of users visiting a website, then they register, sign in and continue. So when they land on the page, the user_id will be null. Once the user registers, a user_id is generated from the tracker. For example.
user_id   IP-address      page_url         domain_id   location
null      192.45.34.23    Landing page     A           ABC
null      192.45.34.23    Welcome page     A           ABC
null      192.45.34.23    FAQ              A           ABC
null      192.45.34.23    Help             A           ABC
null      178.34.12.54    Landing page     A           ABC
12345     192.45.34.23    Sign up          A           ABC
12345     192.45.34.23    Sign in-page1    A           ABC
12345     178.34.12.54    Sign in-page 2   A           ABC

When tracking a customer's journey, I need to map the user_id with null to ones after being assigned.
So in the table, top5 user id has to be 12345 if the IP address and domain_id are same.
user 12345 has 2 IP-address so when the IP address or domain_id matches, the user id has to be mapped.
The output should be like below
user_id   IP-address      page_url         domain_id     location
12345     192.45.34.23    Landing page     A             ABC
12345     192.45.34.23    Welcome page     A             ABC
12345     192.45.34.23    FAQ              A             ABC
12345     192.45.34.23    Help             A             ABC
12345     178.34.12.54    Landing page     A             ABC
12345     192.45.34.23    Sign up          A             ABC
12345     192.45.34.23    Sing in-page 1   A             ABC
12345     178.34.12.54    Sign in-page 2   A             ABC

A: Is this what you're after?  This uses the T-SQL syntax for SQL Server; though should be similar to what you'd need for most other database engines.
declare @example table
(
  Id bigint not null identity(1,1)
  , [user_id] bigint
  , [IP-address] nvarchar(15) not null
  , page_url nvarchar(1024) not null
  , domain_id  nvarchar(32) not null
  , location nvarchar(32) not null
)

insert @example([user_id],   [IP-address], page_url, domain_id, location)
values (null   , '192.45.34.23', 'Landing page'  , 'A', 'ABC')
     , (null   , '192.45.34.23', 'Welcome page'  , 'A', 'ABC')
     , (null   , '192.45.34.23', 'FAQ'           , 'A', 'ABC')
     , (null   , '192.45.34.23', 'Help'          , 'A', 'ABC')
     , (null   , '178.34.12.54', 'Landing page'  , 'A', 'ABC')
     , (12345  , '192.45.34.23', 'Sign up'       , 'A', 'ABC')
     , (null   , '123.1.2.3'   , 'Help'          , 'B', 'ABC')
     , (12345  , '192.45.34.23', 'Sign in-page1' , 'A', 'ABC')
     , (12345  , '178.34.12.54', 'Sign in-page 2', 'A', 'ABC')
     , (98765  , '123.1.2.3'   , 'Help'          , 'B', 'ABC')

select Id
, coalesce
(
    [user_id]
    ,
    (
        select top 1 [user_id]
        from @example b
        where [user_id] is not null
        and b.Id > a.Id
        and
        (
            b.[IP-address] = a.[IP-address]
            or b.domain_id = a.domain_id
        )
        order by Id
    )
)      [user_id]
,      [IP-address]
,      page_url
,      domain_id
,      location
from @example a

i.e. We select all rows from the table, but where the user id is not populated we derive it from the later entries using the criteria you gave (i.e. matching on domain or IP).
You've not specified it in your criteria, but I've taken the liberty of adding an ID field and using that to ensure that the entry we fetch is a later entry, and is the first entry to match.  This assumes that nulls will only occur before a user logs in (i.e. a user won't log out and continue to access the site).  The reason for including this rather than taking any match is I've assumed that potentially over time the same IP may be reassigned to a different user; so this gives you a best guess at which of the multiple matches is most likely to be the user you're after.


text:
Q: In Rust, how to "add" `flatten" to Option>? How can I "add" a flatten() method to Option<U>, which would only typecheck if and only if U is an Option<T>, or more simply to add it to Option<Option<T>>? Naively, I am trying to write the following, which doesn't compile:
impl Option<Option<T>> {
    fn flatten(&self) -> Option<T> {
        match self {
            None => None,
            Some(v) => v,
        }
    }
}

fn main() {
    let x = Some(Some(1));
    let y = x.flatten();
    println!("{:?}", y);
}

A: You can't write inherent implementations (what you're trying) to types you didn't define, due to coherence (if you could, how do you know someone else hasn't also defined something called flatten?).
Instead, you need to define and implement a trait with the method you want.  Anywhere you want the method, you use the trait:
trait Flatten<T> {
    fn flatten(self) -> Option<T>;
}

impl<T> Flatten<T> for Option<Option<T>> {
    fn flatten(self) -> Option<T> {
        match self {
            None => None,
            Some(v) => v,
        }
    }
}

fn main() {
    let x = Some(Some(1));
    let y = x.flatten();
    println!("{:?}", y);
}

Also note that I changed the subject of the method from &self to self: you can't move out of a borrow (especially not an immutable one), so taking self by reference doesn't really make sense here.


text:
Q: CoreData sqlite file in NSBundle I have a JSON file. The size is around 20MB.
Project 1.
So, I created a project and imported data from that JSON file to Core Data. Core Data creates the following sqlite files, entireDataList.sqlite, entireDataList.sqlite-shm and entireDataList.sqlite-wal.
It took 10 minutes to copy entire content from JSON to core data and its one time file creation.
Now in Project2.
I copied all the three files in MainBundle.I have to create .xcdatamodeld  as if I directly copy it from Project1, it does not find the .momd file.
    NSURL *storeURL = [[NSBundle mainBundle] URLForResource:@"entireDataList" withExtension:@"sqlite"];
    store =[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedModel]];
    NSError *error;
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];

So, is storeURL from NSBundle mainBundle is a reliable approach, where entireDataList.sqlite, entireDataList.sqlite-shm and entireDataList.sqlite-wal files are stored?
Generally they are into documents directory.

A: Generally speaking you should copy the files from the bundle into the documents folder on first launch, then open them from there. This approach will then allow you to edit the contents of the files and save the updates.


text:
Q: Как получить урл ссылки в переменную Есть HTML код.

            1

            1

Как получить урл например 1 ссылки в переменную?
Пробовал сделать так
elementList = window.content.document.querySelectorAll('.br .u a')[0].innerHTML;
alert(elementList);

Не получается.
И еще было бы не плохо посчитать их все и занести в переменную. Но это уже вторично, главное урл определенной ссылки получить.
Считать пробовал так, но не чего не получается.
elementList = window.content.document.querySelectorAll('.br .u a');
alert(elementList.length);

A: Вот код где я сохранил в массив array_tag_a все url из списка ul.br:

var matches = document.querySelectorAll("ul.br a");
var array_tag_a = [];
for (var i = 0; i < matches.length; i++) {
  array_tag_a.push (matches[i].getAttribute('href'));
}
console.log(array_tag_a);

            1

            1


text:
Q: How to handle large matrix in Dymola? I would like to know how to deal with large matrix in Dymola.  I have an Modelica code that needs to read the values from a large txt file, and store it into matrix. The following is an example code that shows a 1000x1000 matrix.  I want Modelica to read the value from a txt file that stores the values for w2 (TXT file (~13 MB): THE LINK). The txt file already has the matrix format in Modelica language.  However, there are too many elements, and I cannot just manually copy the values to Dymola.  If I do that, Dymola will stop responding.
model Unnamed
  Real[1000, 1000] w2;
end Unnamed;

Thank you very much!

A: You could also have a look at the ExternData library which supports a couple of more file formats.

A: Look at the ReadRealMatrixFromFile example for some inspiration. You will need to have the file in a supported format, which your own text format is not. In that case, you could write your own parser or convert the file to the MAT files that MSL knows how to read.


text:
Q: Transition on margin-top position causes window scroll I have created a tab animation. Here's a link to my codepen: http://codepen.io/MartinGonzal/pen/mPeMOd
(please ignore other bugs)
The transition in the yellow tabs is almost working how I want, I have one issue with them. When I have a smaller window that I have to scroll to the bottom of the page to see the tabs, the page scrolls up when I click a tab to open it. How can I stop it from scrolling back up?
Here's my code:

Tab 1

This is the content of tab 1

.tab_container {
  /* box-sizing: border-box;
  width: 150px;
  min-height: 176px;
  position: absolute;
  top: -50px;
  transition: margin-top ease 1s; */
  box-sizing: border-box;
  width: 150px;
  min-height: 176px;
  position: absolute;
  top: -50px;
  transition: top ease 1s;
}
/*test*/
.open_yellow_tab {
  top: -176px;
}

Thanks.

A: This is due to # inside your href. Instead use javascript:void(0) in your href of .
Use:

Tab 1

Instead of:

Tab 1

Hope this helps!

A: replace
href="#"

by
href="javascript:;"

in your  tag
edited thx to comment below

A: You need to stop the default browser's behavior for links with href="#". The browser tries to look for an element with an empty id but since he can't find any it just scrolls to the top.
To fix it use preventDefault() in your click handler:
$(".tab").click(function(){
    // this doesn't work
});

$(".tab").click(function(e){
    e.preventDefault();
    // this works
});

Example:

$(document).ready(function(){
  /***************** Green tab animation ****************/
  var slider_tab = $("#slider_tab");
  var green_slider = $("#green_slider");
  slider_tab.click(function(){
    if(green_slider.hasClass("open")){
      green_slider.removeClass("open");
    }else{
      green_slider.addClass("open");
    }
  });

  /***************** Yellow tabs animation ****************/
  $(".tab").click(function(e){
    e.preventDefault();
    //This is the parent div for the tab and content divs
    var content = $(this).parent().parent();

    //Get height and remove "px" from string
    var height = content.css("height");
    //Remove 50 pixels from the height to account for the tab height
    height = parseInt(height) - 50;

    var margin = content.css("marginTop").slice(0, -2);
    if(margin >= 0){
      /*If there is not a margin the tab is closed. Add
        negative margin to the top to make it move up*/
      content.css("margin-top", "-" + height + "px");
    }else{
      //Remove top margin to close tab
      content.css("marginTop", "0px");
    }

  });

  /*test - transition yellow tabs with top position*/
/*   $(".tab").click(function(){
    var content = $(this).parent().parent();
    content.toggleClass("open_yellow_tab");
  }); */

  /***************** Copyright bar ****************/
  $("#copy").keyup(function(){
    $("#output").text($(this).val());

    if (!($(this).val())){
          $("#output").text(" ");
       }
  });

  /***************** Canvas ****************/
  var c = document.getElementById("canvas");
  var ctx = c.getContext("2d");

  ctx.beginPath();
  ctx.moveTo(0, 100);
  ctx.lineTo(262, 46);
  ctx.lineTo(212, 0);
  ctx.lineTo(0, 0);
  ctx.fillStyle = '#eeca14';
  ctx.fill();

  ctx.font = "22px Oswald";
  ctx.fillStyle = '#000';
  ctx.fillText("CANVAS TEXT", 20, 35);

});
@import url('https://fonts.googleapis.com/css?family=Oswald|Roboto|Roboto+Condensed');
body {
  font-family: 'Oswald', sans-serif;
/*     position: relative;
  display: flex;
  flex-direction: column;
  max-height: 100vh; */
}
#wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  overflow: hidden;
}
a {
  text-decoration: none;
  color: black;
}
#top {
  background-color: #282526;
  height: 300px;
}
#hide_overflow {
  width: auto;
  height: auto;
  display: block;
  z-indez: 4;
}

/*********************************** GREEN TAB **********************/
#green_slider {
  position: fixed;
  left: -352px;
  margin-top: 100px;
  width: 343px;
  height: 115px;
  border: 9px solid #3fae29;
  border-right: 45px solid #3fae29;
  border-top-right-radius: 15px;
  border-bottom-right-radius: 15px;
  background-color: #fff;
  transition: margin-left ease 1s;
  z-index: 4;
}
#slider_tab {
  /*******Positioning******/
  position: absolute;
  top: 34px;
  left: 300px;
  width: 130px;
  height: 45px;
  transform: rotate(90deg);
  cursor: pointer;
  /*Round Corners to match green borders*/
  border: 1px solid transparent;
  border-radius: 15px 15px 0px 0;
  /*******Text*********/
  text-align: center;
  vertical-align: middle;
  line-height: 45px;
  font-family: sans-serif;
  font-size: 14px;
  font-weight: bold;
  color: white;
  /*This is so the text stops shaking during the transition*/
  -webkit-backface-visibility: hidden;
}
#green_content {
  width: 100%;
}
#green_content_left {
  max-width: 60%;
  margin: 0;
  padding: 0;
  float: left;
}
#green_content_left p {
  margin: 10px 5px 5px 5px;
  padding: 0;
  font-size: 19px;
  font-weight: bold;
  text-transform: uppercase;
}
#green_content_left p:nth-child(2) {
  margin-top: 5px;
  font-family: 'Roboto Condensed', sans-serif;
  font-size: 14px;
  font-weight: 100;
}
#green_content_left p:nth-child(3) {
  font-size: 24px;
  font-weight: bold;
  color: #cf112b;
  letter-spacing: 1px;
  margin-top: 20px;
}
#green_content_right {
  position: relative;
  width: 39%;
  hegith: 300px;
  margin: 0;
  padding: 0;
  float: right;
}
#green_content_right img {
  width: 60px;
  height: 60px;
  margin: 5px 5px 5px 5px;
  float: left;
}
#green_content_right span {
  display: inline-block;
  position: absolute;
  top: 24px;
  right: -8px;
  max-width: 72px;
  font-size: 21px;
  font-weight: bold;
  color: #3fae29;
  transform: rotate(90deg);
}
#green_content a {
  display: inline-block;
  float: right;
  width: 106px;
  margin: 2px 5px;
  padding: 10px 12px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  font-weight: 400;
  color: #fff;
  background-color: #313131;
  background: linear-gradient(to bottom, #777777 0%, #222222 100%);
  border: 1px solid transparent;
  border-radius: 6px;
}
.open {
  position: relative;
  margin-left: 352px;
}

/*********************************** MIDDLE SECTION **********************/
#middle_section {
  position: relative;
  width: 100%;
  height: 290px;
  margin: 0;
}
#content {
  width: 899px;
  /* height: 290px; */
  margin: auto;
}
#content p {
  width: 654px;
  margin: 20px auto;
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  color: #000;
}
#content p span {
  display: block;
  width: 35px;
  height: 80px;
  float: left;
  font-family: "Times New Roman", sans-serif;
  font-size: 24px;
}

/*********************************** YELLOW TABS **********************/
#tabs_wrapper{
  position: relative;
  display: flex;
  width: 100%;
}
#all_tabs {
  width: 899px;
  margin: auto;
}
.tab_container {
  box-sizing: border-box;
  width: 150px;
  min-height: 176px;
  position: absolute;
  top: -50px;
  transition: margin-top ease 1s;
/****** TEST TO TRANSITION WITH TOP POSITION *******/
  /*   box-sizing: border-box;
  width: 150px;
  min-height: 176px;
  position: absolute;
  top: -50px;
  transition: top ease 1s; */
}
/*test*/
.open_yellow_tab {
  top: -176px;
}

.tab_area{
  width: 100%;
  height: 50px;
  box-sizing: border-box;
}
.tab{
  display: inline-block;
  min-width: 120px;
  height: 20px;
  text-align: center;
  background-color: #EEC917;
  padding: 15px;
  text-transform: uppercase;
  font-size: 18px;
}
.tab_content {
  width: 500px;
  min-height: 176px;
  background-color: #EEC917;
  padding: 15px;
  font-family: 'Roboto', sans-serif;
  font-size: 12px;
  box-sizing: border-box;
}
#tab1 {
  z-index: 3;
}
#tab2{
  margin-left: 160px;
  z-index: 2;
}
#tab3{
  margin-left: 320px;
  z-index: 1;
}

/*********************************** FOOTER **********************/

footer {
  width: 100%;
  height: 271px;
  /* height: 281px; */
  background-color: #282526;
  z-index: 3;
}
#footer_content {
  width: 100%;
  height: 100%;
  /* height: 90%; */
  background-color: #282526;
}
#copyright_bar {
  width: 100%;
  /* height: 10%; */
  min-height: 30px;
  background-color: #fff;
  z-index: 3;
}
#copyright_bar p {
  padding: 0;
  margin: 0;
  font-size: 12px;
  font-weight: 300;
  color: #555;
  text-align: center;
  line-height: 28px;
}

/*********************************** COPY BAR **********************/
#copyright_bar input {
  outline: none;
  outline-style: none;
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: 1px solid #000;
  margin-left: 5px;
  padding-left: 4px;
  font-size: 14px;
}
#output {
  margin-left: 10px;
  font-size: 14px;
}

I am the title

I am the longer sub title.

content!

          Green

        button text

HELLO :)

      <canvas id="canvas" width="272" height="100"></canvas>

A:Lorem ipsum dolor sit amet, morbi amet aenean ante pede blandit, vitae magna sit orci, quis sagittis purus sed senectus dis malesuada. Mi nibh elit veritatis nunc eget nunc, sit magna vivamus cras velit justo purus, vestibulum turpis mauris massa in eleifend dolor. Mauris vitae id, neque mi ultricies risus ridiculus.

Tab 1

This is the content of tab 1

Tab 2

Lorem ipsum dolor sit amet, morbi amet aenean ante pede blandit, vitae magna sit orci, quis sagittis purus sed senectus dis malesuada.

Mi nibh elit veritatis nunc eget nunc, sit magna vivamus cras velit justo purus, vestibulum turpis mauris massa in eleifend dolor. Mauris vitae id, neque mi ultricies risus ridiculus, consectetuer vitae congue morbi pellentesque a mollis.

Tab 3

Lorem ipsum dolor sit amet, tellus facilisis elit est suspendisse elit quis, erat ipsum dignissim donec imperdiet vitae, aenean egestas pellentesque dui sed, metus ornare blandit sociosqu sit duis tellus, non arcu ipsum metus at.

 Viverra ut, amet nec orci, vitae diam, bibendum donec a placerat nulla ad. Lorem ipsum dolor sit amet.

Donec est dictum velit pellentesque quis.

Dui nascetur sociis mi nascetur, omnis sed fugiat erat amet dignissim condimentum. Tellus facilisis elit est suspendisse elit quis.

Massa quis diam duis, lacus erat nec libero, eu ullamcorper mi magna mauris felis ante, eu in gravida ut lorem aliquam.

Sapien ullamcorper pellentesque orci fermentum nunc.

Aliquam erat, ultrices quisque erat.

Pede lorem vestibulum velit sed, suspendisse sollicitudin, vitae lorem sed sed posuere leo, nullam autem ad, neque ante purus nec pede venenatis dis.

Hi I am the copy bar. Enter something here:<input type="text" id="copy">


text:
Q: VueJS: Complete dynamic component transition before rendering new component I have some components that i swap out using VueJs's dynamic component option. I set up transitions on the dynamic component. My issue is as follows:
-Currently, if a change the current view(or component) the transition effect starts(the leave transition)
-As soon as the transition effect begins the next view/component starts its own transition. In essence, both transitions occur simultaneously. What i want is for the (leave) transition for the first component to complete before the (enter) transition for the new component begins.
<template>

Current page: {{currentView}}

        <transition name="fade">
            <component @stateCPchanged="changeView" v-bind:is="currentView"></component>
        </transition>

</template>

A: mode="out-in" should be what you want.

A: This may not exactly solve it, but this can reduce the effect of overlapping of transitions.
You can use cubic-bezier functions to your advantage, by controlling  when the transition will be fast during the duration.
You can use ease-out CSS property on the moving out component, so transition will be : fast/abrupt at the beginning, slow at the end. Use ease-in on the component moving in, so transition will be: slow at the beginning, fast/abrupt at the end, giving you overall effect. More details here.


text:
Q: php check open through iframe I want to check using php if the current page is called by an iframe and not directly in the browser.
It's a page that gets some $_POST parameters while the sending form's target is an iframe, so the page will display in an iframe.
I want to check that using PHP, How?
Thanks.

A: You can't. PHP runs serverside.  It is for all intents and purposes the same thing as the webserver -- it sees HTTP requests and returns responses.  An iframe is a clientside mechanism implemented by the browser that simply allows you to display 2 or more html pages (the response payload).

A: You can use the SERVER HTTP_REFERER
$_SERVER['HTTP_REFERER'];


text:
Q: How can we identify whether a function is inlined or not during GDB debugging? While debugging a C program using GDB, running the command bt would list the function call stack. The later version of GDB displays inlined functions just like non-inlined functions. They appear in backtraces. However from the below article I understand it is possible to differentiate whether the function is inlined or not.
Link - GDB_Inline_Func
They have quoted -

You can check whether a function was inlined by using the info frame
  command.

I am unable to understand how can I interpret the information shown up on executing the command info frame to determine whether the current function is inlined function or not.

A: For example you can disassemble [Function] and if it is inlined you'll get an error


text:
Q: Returning user password expiry date - Powershell I'm working on a command to pull users and the date/time that their password will expire.  Trying to make it look somewhat decent.  I feel like this should work, but it's not working as planned.  Can someone with fresh eyes take a look and let me know what I did incorrectly?
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Displayname", {Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

A: You're almost there, but you've missed a single character.
You need to turn:
{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

into a hash table:
@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

Just that one little @ symbol is all you need.


text:
Q: PyQt: QFileDialog.getExistingDirectory using a default directory, user independant When using the QFileDialog.getExistingDirectory I've found the way to specify the default path to a directory. I wanted to use a default directory somewhere in my (user) home folder on my Linux (Mint) machine. I used:
my_dir = QtGui.QFileDialog.getExistingDirectory(
    self,
    "Open a folder",
    "/home/my_user_name/",
    QtGui.QFileDialog.ShowDirsOnly
    )

Which worked beautifully. The next 'level' is now to be able to do this for every user. I tried the standard Linux way and change /home/my_user_name/ to ~/. That did not work. It resulted in the working directory instead of the user's dir.
Should I use more system arguments when calling my app from the terminal? Or am I missing a PyQt function?

A: You can also get home folder for any user by obtaining the environment variable "HOME" through os.getenv(varname).
>>> import os
>>> os.getenv("HOME")
'/home/my_user_name'

Your code could look like this:
import os
home = os.getenv("HOME")

my_dir = QtGui.QFileDialog.getExistingDirectory(
    self,
    "Open a folder",
    home,
    QtGui.QFileDialog.ShowDirsOnly
    )

A: You can get the user's home directory by using os.path.expanduser
>>> from os.path import expanduser
>>> expanduser("~")
/home/user_name

This works on Windows and Linux.
Your code block will look like this then
my_dir = QtGui.QFileDialog.getExistingDirectory(
    self,
    "Open a folder",
    expanduser("~"),
    QtGui.QFileDialog.ShowDirsOnly
)


text:
Q: How to use a Data Object created in business central ui on a custom Work Item Handler in jBPM? I am following the steps on the tutorial from jBPM documentation to create a business application.
The project is made of the structure:

*

*The KJAR where is the business assets

*The service where the project will be running

*The model where data structures will be implemented

I have implemented a custom Work Item Handler in the service project, and a question came to my mind: What if I need to reference a Data Object created in business central (via UI) and use this class in the custom work item handler to process it and return to the next tasks?
What I have tried was to add the dependency of the KJAR project on service project pom and it worked fine. But I haven't seen in the documentation nothing related to a solution using this approach.
First, does it makes sense? Second how could I "link" assets created in KJAR project inside the service project?

A: I haven't been able to find the documentation either.
However the kjar seems to have many of the properties of a java jar. I've successfully managed to define objects in the business central UI, and after uploading them to nexus repository, it is possible to add a standard maven dependency on the jar.
This way, I was able to use the model defined using the business central UI like standard java objects (if you look inside the jar, you can see some familiar java objects as well as the rules definition).
It seems like you were able to achieve the same thing so I am not sure what exactly you are asking :)
If by "link" you mean import into the project then you can do it whatever way you import other dependencies - one way is to add them to the pom.xml - which you seem to have done already. You can get the package and name in the settings section of the business central ui.
If you have your own repository (nexus for example) you can manually upload it there using mvn deploy command.