text:
Q: Illegal mix of collations error in mysql query Is there any way to compare the generated range column in the mysql query ?
SELECT ue.bundle,ue.timestamp,b.id,bv.id as bundleVersionId,bv.start_date,bv.end_date, bv.type,ue.type from (
 SELECT bundle,timestamp,tenant, case when Document_Id ='' then 'potrait'
 WHEN Document_Id<>'' then 'persisted' end   as type from uds_expanded ) ue
 JOIN bundle b on b.name=ue.bundle  join bundle_version bv on b.id=bv.bundle_id
 WHERE ue.tenant='02306' and ue.timestamp >= bv.start_date and ue.timestamp <=bv.end_date and **ue.type=bv.type ;**

I am getting the following error when I try to compare the types
 Error Code: 1267. Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,IMPLICIT) for operation '=' 0.000 sec

A: Stick to one encoding/collation for your entire system. Right now you seem to be using UTF8 one place and latin1 in another place. Convert the latter to use UTF8 as well and you'll be good.
You can change the collation to UTF8 using
alter table <some_table> convert to character set utf8 collate utf8_general_ci;

A: I think sometimes the issue is we use different orm utilities to generate table and then we want to test queries either by mysql command line or MySql workbench, then this problem comes due to differences of table collation and the command line or app we use. simple way is to define your variables (ones used to test the query against table columns)
ex:
MySQL>
MySQL> set @testCode = 'test2' collate utf8_unicode_ci;
Query OK, 0 rows affected (0.00 sec)

MySQL> select * from test where code = @testCode;

full details

A: Be aware that the single columns can have their collation.
For example, Doctrine generates columns of VARCHAR type as  CHARACTER SET utf8 COLLATE utf8_unicode_ci, and changing the table collation doesen't affect the single columns.
You can change the column's collation with this command:
ALTER TABLE `table`
CHANGE COLUMN `test` `test` VARCHAR(15) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'

or in MySql Workbench interface-> right click on the table-> Alter Table and then in the interface click on a column and modify it.

A: Use ascii_bin where ever possible, it will match up with almost any collation.


text:
Q: Why ConstraintLayout slower than LinearLayout in RecyclerView item? I'm changing the xml item of recyclyerView from LinearLayout to ConstraintLayout.
When I'm scrolling the recyclerView horizontal, it lags and renders very slowly than LinearLayout.
ConstraintLayout

LinearLayout

Here i am sharing my xml for ConstraintLayout.
my ConstraintLayout Item
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="85dp"
    android:layout_height="wrap_content">

<android.support.constraint.ConstraintLayout
    android:id="@+id/merchant_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginEnd="5dp"
    android:layout_marginStart="5dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/merchant_img"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:transitionName="profile"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="UnusedAttribute"
        tools:src="@drawable/avatar" />

    <com.max.xclusivekotlin.customViews.MyTextView
        android:id="@+id/merchant_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:maxWidth="72dp"
        android:minWidth="72dp"
        android:textAlignment="center"
        android:textColor="@color/blackFont"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="@id/merchant_img"
        app:layout_constraintStart_toStartOf="@id/merchant_img"
        app:layout_constraintTop_toBottomOf="@id/merchant_img"
        tools:text="Chili's" />

    <com.max.xclusivekotlin.customViews.MyTextView
        android:id="@+id/merchant_offer_percent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/redColor"
        android:textSize="12sp"
        app:layout_constraintBottom_toTopOf="@id/tv_distance"
        app:layout_constraintEnd_toStartOf="@id/merchant_offer_type"
        app:layout_constraintStart_toStartOf="@id/merchant_name"
        app:layout_constraintTop_toBottomOf="@id/merchant_name"
        app:textBold="bold"
        tools:text="25%" />

    <com.max.xclusivekotlin.customViews.MyTextView
        android:id="@+id/merchant_offer_type"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:lines="1"
        android:textColor="@color/blackFont"
        android:textSize="12sp"
        app:layout_constraintBottom_toTopOf="@id/tv_distance"
        app:layout_constraintEnd_toEndOf="@id/merchant_name"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toEndOf="@id/merchant_offer_percent"
        app:layout_constraintTop_toBottomOf="@id/merchant_name"
        tools:text=" | Refund " />

    <com.max.xclusivekotlin.customViews.MyTextView
         android:id="@+id/tv_distance"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:ellipsize="end"
         android:lines="1"
         android:textAlignment="center"
         android:textColor="@color/greyFont"
         android:textSize="14sp"
         android:visibility="gone"
         app:layout_constraintBottom_toBottomOf="parent"
         app:layout_constraintEnd_toEndOf="@id/merchant_img"
         app:layout_constraintStart_toStartOf="@id/merchant_img"
         app:layout_constraintTop_toBottomOf="@id/merchant_offer_percent" />
    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>

my LinearLayout Item
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="85dp"
    android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/merchant_layout"
    android:layout_width="75dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="5dp"
    android:layout_marginStart="5dp"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="10dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/merchant_img"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:transitionName="profile"
        tools:ignore="UnusedAttribute"
        tools:src="@drawable/avatar" />

    <com.max.xclusivekotlin.customViews.MyTextView
        android:id="@+id/merchant_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:maxWidth="72dp"
        android:minWidth="72dp"
        android:textAlignment="center"
        android:textColor="@color/blackFont"
        android:textSize="14sp"
        tools:text="Chili's" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="5dp"
        android:orientation="horizontal">

        <com.max.xclusivekotlin.customViews.MyTextView
            android:id="@+id/merchant_offer_percent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/redColor"
            android:textSize="12sp"
            app:textBold="bold"
            tools:text="25%" />

        <com.max.xclusivekotlin.customViews.MyTextView
            android:id="@+id/merchant_offer_type"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ellipsize="end"
            android:lines="1"
            android:textColor="@color/blackFont"
            android:textSize="12sp"
            tools:text=" | Refund " />
    </LinearLayout>

    <com.max.xclusivekotlin.customViews.MyTextView
        android:id="@+id/tv_distance"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:lines="1"
        android:textAlignment="center"
        android:textColor="@color/greyFont"
        android:textSize="14sp"
        android:visibility="gone" />
    </LinearLayout>
</android.support.v7.widget.CardView>

How can I solve this?

A: Maybe for lot of constraint you are using in the ConstraintLayout or maybe RecyclerView performance.
i recommend you using RelativeLayout
these link can help you :
Improve RecyclerView performance
RelativeLayout and ConstraintLayout Performance
How Make RecyclerView Smoothly

A: Relative Layout:
RelativeLayout is an approach to actualize complex formats with level (one level of settling) outline. By its outline, it's overlaying things, not at all like LinearLayout that never does that Its name says independent from anyone else, RelativeLayout is awesome at situating things in respect to other. Suppose you have undetermined view width and you need to put a thing to one side of it and to the base of it in the meantime. You can do that with LinearLayout, however, it would take two settled, with RelativeLayout it got way cleaner.
Constraint Layout:
The center is RelativeLayout where things can overlay. Be that as it may, what makes ConstraintLayout awesome is it can supplant the various designs: Frame, Relative, Linear. Truly, there are numerous different formats, yet those are wrappers What I like about ConstraintLayout is that it's extremely awesome at utilizing as a part of Design mode before I didn't care for it by any means. For the most part in view of the poor execution of my fair equipment (for Android Studio) and regular rendering bugs ConstraintLayout properties really are so long and appalling that it's better utilizing it Design mode. It can control position and measurements (not at all like RelativeLayout) of perspectives. Keep in mind, that parameters beginning with layout_ are implied for wrapping format. The view itself doesn't deal with those
So you can utilize your most loved weight from LinearLayout in ConstraintLayout by imperative chains, land left/right/top/base of from RelativeLayout, overlay things like in straightforward FrameLayout I think no one uses GridLayout, it's far excessively disappointing, constantly favored settled LinearLayout, with ConstraintLayout you can do that effortlessly
Constraint Layout Disadvantage:
Despite the fact that it's awesome, outline mode still isn't as immaculate as XML. It gets jumbled simple, you have to zoom in on perspectives and it drives you to have simply ConstraintLayout, in the event that you endeavor to include some settled design – you'd think twice about it.
Hope this will help you.

A: Because ConstraintLayout is slower than FrameLayout, and maybe other layouts (I've only tested FrameLayout). I have a ConstraintLayout with 5 items in it, its onMeasure method costs about 50ms. When I change this ConstraintLayout to a FrameLayout, its onMeasure method costs just 1 or 2ms.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Append dynamic javascript variable to HTML tag. InnerHTML & insertAdjacentHTML both incorrect I have a couple of javascript variables that are being updated as an animation plays out.
What I'd like to do is append these to HTML elements but I'm having a few problems.  I can make it work by introducing a span tag into the HTML and targeting that instead but I'd like to know how I can do it without.
The code that currently works:

Current Depth:

  var bla = $('bla');

  function updateInfoPanel(){

    bla.innerHTML = scaleControl.value;
}

I've removed code that isn't required.
What I'd like to do is just append the variable to to the p tag instead.  When I try this is repeats the value several times instead of replacing it.
Thanks for any help

A: Since you are using jQuery there is no need to overwrite $ to create a element selector. Use jQuery id selector along with manipulation methods like .html()/.append() like
So try the below after removing the var $ = function(){...}
$('#infoCurrentScale').append('sdfsdf');


text:
Q: JSON encoding problem in IE6 and IE7 Can someone tell me how to change this getJSON request to a .ajax call so I can set the contentType option?
$.getJSON('json/showreel.json', function(data) {
    //get total number of JSON objects and generate random numder
    var total = data.length;
    var randnum = Math.floor(Math.random()*total)

    //Loop through each of the JSON objects to check if matches random number
    $.each(data, function(entryIndex, entry) {

        if(entryIndex === randnum){
            var info = '
';
            info += entry['title'] + '
';
            info += '' + entry['website'] + '';
            info += '
';

            $('#head-contact,#head-contact a').css('color',entry['colour']);

            //create new image object to preload image
            var img = new Image();
            //once image has loaded execute this code
            $(img).load(function () {
                //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
                $(this).hide();
                $('#showreel').removeClass('loading').append(this);
                $(this).fadeIn(3000);
            }).error(function () {
                // notify the user that the image could not be loaded
            }).attr('src', entry['image_src']);
        }
        $('#info').append(info);
    });
});

Many thanks,
C

A: contentType is used to set the type of sent data. GET requests do not send data so you may be talking about the type of received data, this is changed using the dataType option.
Replace:
$.getJSON('json/showreel.json', function(data) {
    ...
});

by:
$.ajax({
    type: 'get',
    url: 'json/showreel.json',
    dataType: 'application/json'
    success: function(data) {
        ...
    }
});


text:
Q: Django/Python ImportError: No module named admin As a result of attempting to update admin.py of one of my Django apps, I now get a Server Error (500) that has brought my site down. When I import admin from django.contrib, I get the following traceback:
 Traceback (most recent call last):
   File "/usr/local/lib/python2.7/dist-packages/django/utils/module_loading.py", line 74, in autodiscover_modules
     import_module('%s.%s' % (app_config.name, module_to_search))
   File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
     __import__(name)
 ImportError: No module named admin

Using print_stack() gives me a little deeper insight:
File "/home/ubuntu/gather/src/foodshop/wsgi.py", line 21, in <module>
  application = get_wsgi_application()
File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_application
  django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
  apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 115, in populate
  app_config.ready()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/apps.py", line 22, in ready
  self.module.autodiscover()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/__init__.py", line 24, in autodiscover
  autodiscover_modules('admin', register_to=site)
File "/usr/local/lib/python2.7/dist-packages/django/utils/module_loading.py", line 74, in autodiscover_modules
  import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
  __import__(name)
File "/home/ubuntu/gather/src/recipes/admin.py", line 6, in <module>
  class RecipesAdmin(admin.ModelAdmin):
File "/home/ubuntu/gather/src/recipes/admin.py", line 9, in RecipesAdmin
  traceback.print_stack()

I use this module in several other apps within my project, so I don't understand why it's not working for this particular app. You can see my very simple Python code below, which is for an admin.
admin.py
from django.contrib import admin
from .models import Recipes

class RecipesAdmin(admin.ModelAdmin):
        list_display = ["__unicode__", "title", "rating", "date_modified"]
        prepopulated_fields = {"slug": ("SKU",)}
        class Meta:
                model = Recipes

admin.site.register(Recipes, RecipesAdmin)

urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.conf.urls import patterns, url, include
from djangoratings.views import AddRatingFromModel

urlpatterns = [

    url(r'^$', 'customers.views.home', name='home'),
    url(r'^home/', 'customers.views.home', name='home'),
    url(r'^about/', 'recipes.views.about', name='about'),
    url(r'^menu/', 'recipes.views.menu', name='menu'),
    url(r'^donate/', 'recipes.views.menu', name='menu'),
    # url(r'^contact/', 'recipes.views.contact', name='contact'),

    url(r'^admin/', include(admin.site.urls)),

    url(r'^about/healthy/', 'recipes.views.healthy', name='healthy'),
    url(r'^about/premade/', 'recipes.views.premade', name='premade'),
    url(r'^about/exceptional/', 'recipes.views.exceptional', name='exceptional'),

    url(r'^accounts/', include('registration.backends.default.urls')),

    url(r'^cart/', 'cart.views.get_cart', name='get_cart'),
    url(r'^add/', 'recipes.views.menu', name='menu'),
    # url(r'^add/(?P<product_id>[-\w]+)/id=(?P<quantity>[-\w]+)/$', 'cart.views.add_to_cart', name='shopping-cart-add'),
    url(r'^update/(?P<product_id>[-\w]+)/$', 'cart.views.specific_qty', name='shopping-cart-specify'),
    url(r'^remove/(?P<product_id>[-\w]+)/$', 'cart.views.remove_from_cart', name='shopping-cart-remove'),
    url(r'^subtract/(?P<product_id>[-\w]+)/$', 'cart.views.subtract_from_cart', name='shopping-cart-subtract'),
    url(r'^clear_cart/', 'cart.views.clear_cart', name='shopping-cart-clear'),

    url(r'^contact/$','contact.views.email',name='email'),
    url(r'^feedback/$','contact.views.feedback',name='feedback'),
    url(r'^thanks/$', 'contact.views.thanks',name='thanks'),
    url(r'^profile/$', 'cart.views.profile', name='profile'),
    url(r'^profile/new/$', 'cart.views.new_profile', name='new_profile'),
    url(r'^profile/error/$', 'cart.views.qty_error', name='qty_error'),
    url(r'^profile/cancel/$', 'cart.views.cancel_sub', name='cancel_sub'),
    url(r'^profile/feedback/$', 'recipes.views.feedback', name='feedback'),

    url(r'^rate/(?P<object_id>\d+)/(?P<score>\d+)/', AddRatingFromModel(), {
        'app_label': 'recipes',
        'model': 'recipes',
        'field_name': 'rating',
    }),

    url(r'^charge/$', 'cart.views.charge', name='charge'),
    url(r'^subscription/charge/$', 'cart.views.pay', name='pay'),

    url(r'^frequently_asked/$', 'cart.views.frequently_asked', name='frequently_asked'),
    url(r'^tender/$', 'cart.views.weekly_orders', name='weekly_orders'),
    url(r'^tender_postmates/$', 'cart.views.tender_postmates', name='tender_postmates')

] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I have ensured that I am importing django.contrib.admin in settings.py, and in my urls.py file, I have from django.contrib import admin and url(r'^admin/', include(admin.site.urls)). This just started when I tried changing the admin.py file above; even after reverting back to the original file, the server error occurs. Unfortunately, this has brought my entire site down.
I'm using an Ubuntu machine and an Apache2 server. Any insights would be much appreciated!
Update 1: Even after doing a git reset --hard to origin/master, the error is still occurring.
Update 2: I have removed every .pyc file and restarted my Apache2 server, but the problem persists.
Update 3: In the manage.py shell, when I do >>> from django.contrib import admin as a, >>> a resolves to <module 'django.contrib.admin' from '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/__init__.py'>. This explicitly shows the module exists, but the problem is still occurring.


text:
Q: Why do these divs begin to wrap if bootstrap is fluid? Everything's all nice and fluid here:
http://jsfiddle.net/52VtD/3288/

It's all percentage based, so no matter how wide you go, those stripes take up the same amount of proportional space. So why is it that, when I make the screen mobile sized, the divs begin to wrap? Really irritating.

A: it's due to padding.
if you override col-xs-1 like this :
.col-xs-1 {
    padding: 0;
}

it working.
or if you dont want override bootstrap, set in style :

A: There is no row-fluid in bootstrap 3, just row. And rows need to be in a container.


text:
Q: Display the inserted data in wordpress custom template Hi I am developing a word press website. I created a custom template, where in I have a form and fields are inserted into the database(mySql).  The Codes are shown below.Insert into database
Now I require to display the data which are already inserted into the database in front end in form of a table or grid. How I am able to do that.
I need the output something like this.
      Ritual Name   Ritual Active
      ---------------------------
      Test1        |    Y
      Test2        |    Y

Any help appreciated.
function.php
function childtheme_style_andscripts(){
    //wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css'  );
    wp_enqueue_script('ajax-function',  get_stylesheet_directory_uri() .   '/js/ajaxfunction.js', array('jquery'), '1.0', true );
    wp_localize_script( 'ajax-function', 'usersubmitform', array(
'url'=> admin_url('admin-ajax.php'),
    'security'=> wp_create_nonce('our-nonce')
    ) );
}

add_action('wp_enqueue_scripts','childtheme_style_andscripts');

function form_action_function() {
    require_once(dirname( __FILE__ ).'/../../../wp-load.php');
    $data = $_POST['data'];
    global $wpdb;
    if( !check_ajax_referer('our-nonce', 'security' ) ) {
        wp_send_json_error('security failed');
        return;
    }
    //var_dump($data);
    $rname=$data['rname'];
    $ractive=$data['ractive'];

    $table_name = "rituals";
    $wpdb->insert($table_name, array ('Ritual_Name' => $rname, 'Ritual_Active' => $ractive) );

    //$wpdb->show_errors();
    //$wpdb->print_error();
    echo 'From Submitted Successfully';
    die();
}
add_action('wp_ajax_nopriv_form_action_function','form_action_function');
add_action('wp_ajax_form_action_function','form_action_function');

ajaxfunction.js
jQuery(document).ready(function($){
var submitButton = document.getElementById('usersubmit');
var ajaxFunctionformprocess = function(fromdata, action){
    $.ajax({
        type:'post',
        url: usersubmitform.url,
        data:{
            action:action,
            data:fromdata,
            security:usersubmitform.security,
        },
        success:function(reponse){
            $('div.msg').html(reponse);
        },
        error:function(response){
            alert(response);
        }
    });
}

submitButton.addEventListener('click', function(event){
    event.preventDefault();
    var fromdata = {
        'rname':document.getElementById('rname').value,
        'ractive':document.getElementById('ractive').value,
    };
    ajaxFunctionformprocess(fromdata, 'form_action_function');

    });
  });

Samplepage.php(custom template)

User Form

        <form  class="userform">
            Ritual Name: <input type="text" id="rname" name="rname" />

            Ritual Active: <input type="text" id="ractive" name="ractive" />

            <input  id="usersubmit"type="submit" Value="Submit" />
        </form>

A: Case 1 :Create a template for display information  from table
<?php
/*

Template Name: Disply Ritural
Description: display ritual information in table formate

*/

global $wpdb;
$table_name = "rituals";

$result = $wpdb->get_results ("SELECT * FROM  $table_name");

foreach ( $result as $ritual_info )
{
        echo $ritual_info['Ritual_Name'];
        echo $ritual_info['Ritual_Active'];
}

Case 2 :Create a shortcode make it easy to use.open your functions.php file add code there.
function show_ritual_info(){
global $wpdb;
$table_name = "rituals";
$query="SELECT * FROM  $table_name";
$result = $wpdb->get_results ($query);

foreach ( $result as $ritual_info )
{
        echo $ritual_info['Ritual_Name'];
        echo $ritual_info['Ritual_Active'];
}

}
add_shortcode('show_ritual_info','show_ritual_info');

How to use shortcode

*

*Inside php file
<?php echo do_shortcode('[show_ritual_info]'); ?>

*Inside admin page
['show_ritual_info']

A: Something like this:
<?php
        global $wpdb;
        $table_name = "rituals";
        // this will get the data from your table
        $retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name" );
        ?>
        <?php if( ! empty($retrieve_data) ):?>

                 Ritual Name
                 Ritual Active

            <?php foreach ($retrieve_data as $retrieved_data): ?>

                <?php echo $retrieved_data['Ritual_Name'];?>
                <?php echo $retrieved_data['Ritual_Active'];?>

            <?php endforeach; ?>

        <?php endif; ?>

Not check but must work.)


text:
Q: Какую джумлу выбрать - 2.5 или 3.2? Есть желание научиться сайтостроению, хочу попробовать на джумле. Для начала хочу сделать небольшой информационный сайт. Опыта особого нет, так, верхушки, но есть понимание. С какой версии лучше начать - 2.5 или 3.2 - и почему?

A: Выбирайте последнюю стабильную версию. Сейчас это версия 3.3. Почему? Как правило, это безопасность. Каждая новая версия закрывает имеющиеся уязвимости + добавляет новый функционал.
Поддержка версии 2.5 будет осуществляться только до декабря 2014 года. Поэтому выбор в вашем случае очевиден.
A: Пользуйтесь версией 3.2, она функциональна, и больше возможностей.


text:
Q: How to modify the title area for the Crisp Chat Wrapper Library How do i make modifications to the form that holds the Crisp Chat form. Please find attached. I cannot set the title to the form or better yet remove the title area so that the chat occupies the whole form.
I updated the cnlib1 with the update that you made and its working well @Shai but now am getting a runtime error with the following details.
Exception in thread "JavaFX Application Thread" netscape.javascript.JSException: TypeError: undefined is not an object
    at com.sun.webkit.dom.JSObject.fwkMakeException(JSObject.java:156)
    at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
    at com.sun.webkit.WebPage.executeScript(WebPage.java:1511)
    at javafx.scene.web.WebEngine.executeScript(WebEngine.java:1005)
    at com.codename1.impl.javase.SEBrowserComponent.executeImpl(SEBrowserComponent.java:496)
    at com.codename1.impl.javase.SEBrowserComponent.access$600(SEBrowserComponent.java:67)
    at com.codename1.impl.javase.SEBrowserComponent$12.run(SEBrowserComponent.java:509)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)

A: I pushed an update to the library that should fix this. The update should appear in the download section within 3 hours or so. See https://github.com/codenameone/CrispCodenameOneSDK/commit/7b70120d054c080e4c21c1971e4ece4acd640873


text:
Q: PyQGIS select layer by original table name As far as I see, on QgsMapLayerRegistry.instance() there is a method to select layers:
mapLayersByName(Qstring)

and the method
mapLayer(QString)

respectively, wich accesses a layer by its id.
As the name says, mapLayersByName() selects layers by their name in the legend, wich causes scripts or plugins to fail if a user renames a layer/table (i.e. renaming a table '160520_parcels' to 'Parcels').
So is there a way to access a layer by the name of it's origining table in PyQGIS?
update
something like ...
def selectLayerByOriginalName(tablename):
    # return layers whose orininal names start with 'tablename'
    llist = []
    for l in QgsMapLayerRegistry.instance().mapLayers().values():
        if tablename in l.id():
           if l.id().index(tablename) == 0:
               llist.append(lyr)
    return llist

... works, but is there a more convenient approach?

A: You can do it this way:
def get_layer_by_tablename(self, tablename):
    """ Iterate over all layers and get the one with selected @tablename """

    # Check if we have any layer loaded
    layers = self.iface.legendInterface().layers()
    if len(layers) == 0:
        return None

    # Iterate over all layers
    layer = None
    for cur_layer in layers:
        uri_table = self.get_layer_source_table_name(cur_layer)
        if uri_table is not None and uri_table == tablename:
            layer = cur_layer
            break

    if layer is None:
       print ("Layer not found")

    return layer

def get_layer_source_table_name(self, layer):
    """ Get table or view name of selected layer """

    if layer is None:
        return None

    uri_table = None
    uri = layer.dataProvider().dataSourceUri().lower()
    pos_ini = uri.find('table=')
    pos_end_schema = uri.rfind('.')
    pos_fi = uri.find('" ')
    if pos_ini <> -1 and pos_fi <> -1:
        uri_table = uri[pos_end_schema+2:pos_fi]

    return uri_table


text:
Q: How to create Docker-Image for c++ executable without having to add all dependencies I have a programm which I compile on my host machine and want to run it in a Docker-Container.
Now, it needs very many dependencies to run.
First I tried to find out all dependencies with running
ldd ./my_prog
and then started copying them to my docker ubuntu image.
But then the copied dependencies need more dependencies such that this did not seem promising if I did not want to copy my whole host system into the container.
Then I read that statically linking my program might cure this.
But since I have a CMake-project I don't know what to do to make it statically link my dependencies. Is this even a valid approach? And if so, how do I do this?
TL;DR: I have a c++ programm which I want to run in a docker-container and try to avoid to copy very many dependencies to the image.
Edit: running my prog with ldd gave me a list of dependencies which I extracted all paths from and I copied all these .so files into my container. Yet it still complained of not finding everything.


text:
Q: How do I break a link in java (using @link or @see tags) if I cannot use more than 80 characters? I have the following problem when using javadoc the @see tags: I cannot exceed the 80 characters but the link itself is longer than that. How can I break it to comply with that restriction?
For example, if I want to use a @see tag to refer the javadoc reader to the Java Naming Conventions, how can I break it in two lines without affecting the javadoc?
The link is:
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367

Thanks!

A: The following Javadoc worked without any problem for me:
/**
 * Some content.
 *
 * @see Java Naming Conventions
 */

It then generated an appropriate See Also: section with the link correctly displayed:

A: You can use a URL shortener. For example, you could use https://goo.gl/ (from Google) to generate a a short URL to put it in the JavaDoc.


text:
Q: How to play multi-audio files on click Could anyone tell me how to play an audio when clicking on the
?
This code plays all the audio at the same time.
let containerItem = document.querySelectorAll('.container__item');
  let audio = document.querySelectorAll('.audio');
  containerItem.forEach((a)=>a.addEventListener('click',playAudio));
  function playAudio(){
  audio.forEach((a)=>a.play());
}

  <audio class="audio" src="cry.mp3"></audio>

  <audio class="audio" src="dance.mp3"></audio>

A: The playAudio() function is applying .play() on every audio element.
Use the function's this keyword to select the clicked element and start its audio only selecting its child (.audio element) using querySelector.
function playAudio() {
  this.querySelector('.audio').play();
}

A: Since you have added the click event to each containerElement and not each audio element you need to change your playAudio function to this
function playAudio(){
  this.children[0].play();
}

or you can do it like this

document.querySelector("#container").onclick = function(e) {
  if(e.target.nodeName === "I") {
    var button = e.target, audio = e.target.nextElementSibling;
    if(audio.paused) {
      audio.play();
      button.className = "fa fa-pause-circle-o";
    }else {
      audio.pause();
      button.className = "fa fa-play-circle-o";
    }
  }
}
* {
  box-sizing: border-box;
}
#container {
  display: flex;
  width: 300px;
  background-color: lightgreen;
  border-radius: 15px;
  box-shadow: 1px 1px 2px #555;
}
.container__item {
  width: 60px;
  height: 50px;
  border-radius: 40%;
  background-color: #ccc;
  box-shadow: 0 0 50px 15px #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 2px;
}
.container__item i {
  font-size: 35px;
  cursor: pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <audio class="audio" src="http://soundbible.com/grab.php?id=1858&type=mp3" onended="this.previousElementSibling.className = 'fa fa-play-circle-o'"></audio>

    <audio class="audio" src="http://soundbible.com/grab.php?id=1858&type=mp3" onended="this.previousElementSibling.className = 'fa fa-play-circle-o'"></audio>

    <audio class="audio" src="http://soundbible.com/grab.php?id=1858&type=mp3" onended="this.previousElementSibling.className = 'fa fa-play-circle-o'"></audio>

    <audio class="audio" src="http://soundbible.com/grab.php?id=1858&type=mp3" onended="this.previousElementSibling.className = 'fa fa-play-circle-o'"></audio>

    <audio class="audio" src="http://soundbible.com/grab.php?id=1858&type=mp3" onended="this.previousElementSibling.className = 'fa fa-play-circle-o'"></audio>

    <audio class="audio" src="http://soundbible.com/grab.php?id=1858&type=mp3" onended="this.previousElementSibling.className = 'fa fa-play-circle-o'"></audio>

A: Here you are:

document.querySelectorAll('.container__item')
  .forEach(a => a.addEventListener('click', playAudio));

function playAudio() {
  this.querySelector('audio').play();
}
.container__item {
  display: inline-block;
  width: 100px;
  height: 100px;
  border: solid 1px
}

1
  <audio src="http://ice3.somafm.com/defcon-128-mp3" crossorigin="anonymous">
 </audio>

2
  <audio src="http://ice3.somafm.com/bagel-128-mp3" crossorigin="anonymous">
 </audio>

A: Being the issue playing only the sound selected, as to me is better to put the function play outside the main code.
Added a class to the div which is the target of the selection.
Plays audio linked to the class a or b.

var itemLenght= document.querySelectorAll(".container__item").length;

for (var i = 0; i < itemLenght; i++) {

    document.querySelectorAll(".container__item")[i].addEventListener("click", function(){

        var eventClass = this.classList[0];

        makeSound(eventClass);

    })
}

function makeSound(key){

    switch (key) {
        case "a":
            var audio1 = new Audio("cry.mp3");
            audio1.play();
        break;

        case "b":
            var audio2 = new Audio("dance.mp3");
            audio2.play();
        break;

        default:
            console.log(event);
        break;
    }
}

       <audio class="a audio " src="cry.mp3"></audio>

       <audio class="b audio " src="dance.mp3"></audio>


text:
Q: why is there an error in the snapshot.data in main.dart inside body while trying to build app using newsapi?  FutureBuilder(
         future: client.getArticle(),
         builder: (BuildContext context, AsyncSnapshot<List<Article>> snapshot) {
           //let's check if we got a response or not
           if (snapshot.hasData) {
             //Now let's make a list of articles
             List<Article> articles = snapshot.data;
             return ListView.builder(
               //Now let's create our custom List tile
               itemCount: articles.length,
               itemBuilder: (context, index) =>
                   ListTile  (title: Text(articles[index].title),),
             );
           }
           return Center(
             child: CircularProgressIndicator(),
           );
         },
       ),
     );    } }

The above code does not work as it shows an error.

A: According to the error message you got you need a cast like this:
List<Article> articles = (List<Article>)snapshot.data!;


text:
Q: Basic Concurrency code example Java I am reading concurrency from Thinking in Java, 4th edition by Bruce Eckel. Here is a basic example code from the book to demonstrate the need of synchronization.
//SerialNumberGenerator.java

    public class SerialNumberGenerator {
        private static volatile int serialNumber = 0;
        public static int nextSerialNumber() {
            return serialNumber++; // Not thread-safe
        }
    }

//: concurrency/SerialNumberChecker.java
// Operations that may seem safe are not,
// when threads are present.

import java.util.concurrent.*;
// Reuses storage so we don't run out of memory:
class CircularSet {
    private int[] array;
    private int len;
    private int index = 0;
    public CircularSet(int size) {
        array = new int[size];
        len = size;
// Initialize to a value not produced
// by the SerialNumberGenerator:
        for(int i = 0; i < size; i++)
            array[i] = -1;
    }
    public synchronized void add(int i) {
        array[index] = i;
// Wrap index and write over old elements:
        index = ++index % len;
    }
    public synchronized boolean contains(int val) {
        for(int i = 0; i < len; i++)
            if(array[i] == val) return true;
        return false;
    }
}
public class SerialNumberChecker {
    private static final int SIZE = 10;
    private static CircularSet serials =
            new CircularSet(1000);
    private static ExecutorService exec =
            Executors.newCachedThreadPool();
    static class SerialChecker implements Runnable {
        public void run() {
            while(true) {
                int serial =
                        SerialNumberGenerator.nextSerialNumber();
                if(serials.contains(serial)) {
                    System.out.println("Duplicate: " + serial);
                    System.exit(0);
                }
                serials.add(serial);
            }
        }
    }
    public static void main(String[] args) throws Exception {
        for(int i = 0; i < SIZE; i++)
            exec.execute(new SerialChecker());
        // Stop after n seconds if there's an argument:
        if(args.length > 0) {
            TimeUnit.SECONDS.sleep(new Integer(args[0]));
            System.out.println("No duplicates detected");
            System.exit(0);
        }
    }
}

The output he has mentioned in the book is any number like this:
Duplicate: 8468656

When I ran the code, I got the output:
Duplicate: 3484
Duplicate: 3485

I know the program is thread unsafe and that the numbers could be different but, why am I getting 2 duplicate consecutive values here? How is this possible?
Can anyone explain(the low level details) the process of Duplicate number generation in the above program?

A: The statements
System.out.println("Duplicate: " + serial);
System.exit(0);

do not prevent other threads from performing actions in-between. Therefore, if you run n threads, all calling the unsafe code, thus potentially executing these two statements, there might be up to n threads printing their message before one of these threads manages to execute System.exit(0);

A: It comes from the SerialNumberGenerator. Replace the int value by an instance of AtomicInteger and you should never get duplicates.
Ah.. What Holger wrote is right.

A: Okay, Holger's answer is okay for explaining 2 duplicates and on the whole he has explained about Thread unsafe code leading to various indeterminate possibilities. I agree with that. However, I am posting low level details that could help in explaining one of those many possibilities due to which above code might have arisen.
javap -c SerialNumberGenerator.class

Compiled from "SerialNumberGenerator.java"
public class SerialNumberGenerator {
  public SerialNumberGenerator();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static int nextSerialNumber();
    Code:
       0: getstatic     #2                  // Field serialNumber:I
       3: dup
       4: iconst_1
       5: iadd
       6: putstatic     #2                  // Field serialNumber:I
       9: ireturn

  static {};
    Code:
       0: iconst_0
       1: putstatic     #2                  // Field serialNumber:I
       4: return
}

As you can see here, there is an instruction between iadd and ireturn. Its possible that, while one thread loaded the value of serialNumber and blocked another would have loaded it too and when one of them increments it and adds it to the queue. Other thread holding the unincremented value now increments it to get the same value and a check against the array returns "Duplicate". Then as, Holger said,
The statements
System.out.println("Duplicate: " + serial);
System.exit(0);

do not prevent other threads from performing actions in-between. Its possible that one thread got blocked before got executing the exit(after printing the println statement) and other one also executed the prinln statement. When the scheduler got back to the first thread, it exited. This are just a typical possibility from many others. The intent is to visualize the process that could have led to the output so that the picture becomes more clear.

A: try to use:
public static synchronized int nextSerialNumber()
{
    return serialNumber++;
}

this 'synchronized' solve your problem
but you should use java.util.concurrent.atomic.AtomicInteger - better solution.


text:
Q: Xcode delete pod files folder and schema after discard all changes when I use Xcode 9 source control everything was good.
When I updated Xcode up to 10 and when I press discard all changes - Xcode has deleted pod files, run schemas, and one folder where I store .xliff files.
When I pressed to 'Discard all changes' I see this alert

I know that I can reinstall Pods and made new schema, but I don't won't do it every time.
Please give me advise to fix this problem.
Please give me my source control back)))

A: I had a similar issue and I solve it with this way.
In Terminal
cd "your project dir"
git add


text:
Q: How to make Umbraco form with validation work correctly? I couldn't find even one tutorial that correctly and fully explains how to make a form with validation.
More specifically I have the following issue - when the errors are passed, the filled content by the user is lost.
I am using Umbraco v7, but I imagine the concept is the same with 8 and 9?!
Option 1
Generally, what people do in the tutorials is that there is 1 action RenderForm (get) and then another SubmitForm (post). From what I get, if validation fails, you have to call CurrentUmbracoPage() to basically reload the .cshtml page and include this data. This is where the problem come in: the render from is done through an action which usually looks like that:
 Html.RenderAction("RenderForm", "Contact", new ViewModel());

and thus it resets the data to a new blank Model. I still have the errors, but whatever the user prefilled is now lost. I imagine there must be a way to just pass the model here, but I couldn't find out how.
Option 2
An alternative way of dealing with forms is to have only the POST controller action and load the form through a partial in the .cshtml:
Html.RenderPartial("~/Views/Partials/Forms/_ContactUsForm.cshtml", new ViewModel());

which brings us to the same problem - errors show but ViewModel data is blanked.
I tried calling it without a model, but it throws an error. I would expect you could prepare the model, and then just use it in the .cshtml or the partial .cshmtml but I wasn't able to find out how.
By prepare model I mean that I have to set a bunch of variables, prefill information, set dropdowns etc. before I render form. This should be done in the controller somehow before I load both the blank form and the filled form with errors.

My research:
The official documentation has no mention of errors:
https://our.umbraco.com/Documentation/Fundamentals/Code/Creating-Forms/index-v7
These tutorials show you how to make forms but again, don't show you how to show data when form is invalid:

*

*https://www.youtube.com/watch?v=3V0A1AYJbys

*https://www.youtube.com/watch?v=LumPhKQvUCQ

*https://www.youtube.com/watch?v=3EF13vcGE18

*https://www.youtube.com/watch?v=vxGG4dWyBEQ

A: So in my main page I would usually have
@Html.Action("Render", "Form");
This calls the Render method on the FormController
The render method prepares the form model and then calls the partial
var model = new FormViewModel{
    enter instantiation code here as required
}
return PartialView("~/Views/Partials/Form.cshtml", model);

Submitting the form will call the Submit method on the same controller
Usually in your submit method you would have
    if (!ModelState.IsValid)
{
    return CurrentUmbracoPage();
}
//Depending on your production set up, an option is to use TempData here to
send some sort of success flag if the form was processed successfully by the backend
TempData.Add("Success", true);
return RedirectToCurrentUmbracoPage();

Instead of RedirectToCurrentUmbracoPage on success you might prefer to just redirect to a success page, if you have one, with RedirectToUmbracoPage(pageId)
Assuming you know how to set up the form model in mvc with required attributes etc as the ModelState.IsValid will rely on those for validation.
How is your partial set up by the way, are you using BeginUmbracoForm
using (Html.BeginUmbracoForm<FormController>("Submit", null, new
    {
...
}


text:
Q: Solution of SDE that is almost geometric Let the SDE be defined by
$$dS_t=\frac{l-S_t}{\tau} dt+mS_t dB_t$$
I tried solving it using the given general solution on wikipedia page with
$c_t= \frac{l}{\tau}$, $a(t)=\frac{-1}{\tau}$, $m=b(t)$, $d(t)=0$. Then $\Phi$ equals
$$\exp\left( \frac{t}{\tau} - \frac{m^2t}{2}  +m W_t\right)$$
and so
$$S_t=-\tau S_0\exp\left( \frac{t}{\tau} - \frac{m^2t}{2}  +m W_t\right)-\tau S_0e^{-t/\tau}$$
Is this correct? where can I read more about this type of SDE?
https://en.wikipedia.org/wiki/Stochastic_differential_equation


text:
Q: Use onboard gpu with plugging cables into external gpu In windows,

*

*My two monitors plugged into the external gpu,

*I disabled external gpu from device manager and onboard gpu took it's place.

In ubuntu,

*

*I do not want to use my external gpu so i disabled it with sudo prime-select intel

*PC started to use onboard gpu as i wanted,

*But now it does not work while the monitor cables are plugged into external gpu

*Since 3. situations worked with windows, i wonder if it can work in ubuntu too.

My external gpu makes a lot of noise and my onboard gpu only has 1 input place.
Thank you.
ps: i do not know what to include, so please ask.


text:
Q: Nativescript Angular Detect Swipe to Back for IOS In Nativescript Angular, I can swipe from left edge to right to go back on iOS. Is there any way i can detect or capture this swipe back?
The reason for this is because I have a button on screen that execute "this.routerExtensions.back()" when tapped. I would like to identify whether a "Back action" is from this button or iOS swipe event.
Thanks

A: NativeScript has this property on pages.
https://docs.nativescript.org/api-reference/classes/ui_page.page.html#enableswipebacknavigation
If you set that to false, you should then be able to create your own gesture for going back. Even on native iOS, I am not sure you can directly tap into the back gesture without instead replacing it with your own.

A: This is how I was able to solve it for Android and iOS:

*

*adjust constructor to manipulate the pullToLeft function from Android, and disable the default swipe back from iOS:

constructor(...) {
    if (isAndroid) {
      Application.android.on(
        AndroidApplication.activityBackPressedEvent,
        (data: AndroidActivityBackPressedEventData) => {
          data.cancel = true;
          ...yourCustomFunction()
        }
      );
    } else {
      page.enableSwipeBackNavigation = false;
    }
  }

*for Android it is already working - for iOS you need then to write a function you can use on a template (this is also how you can recognize the swipe action):

public onSwipe = (args: SwipeGestureEventData) => {
    if (!isAndroid) {
      if (args.direction === SwipeDirection.right) {
        ...yourCustomFunction()
      }
    }
  };

*disable the default PopGestureSerializer and add the swipe function on top of your template/element and it should work on iOS as well:

<StackLayout [interactivePopGestureRecognizer]="false" (swipe)='onSwipe($event)'>
...
</StackLayout>


text:
Q: H-minor free Graph Recently I cam across a statement which divides graphs into different classes w.r.t. the complexity of problems on them.
planar < bounded genus < H-minor free < general graphs
My question regards the definition of H-minor free graphs.
What I don't understand is that apparently H is not fixed.
Is it true that as long as I can be sure that my (large) graph G doesn't contain some! minor, then some problems might be easier to compute on G then on general graphs regardless of what the actual minor is?
Thank you

A: Your statement is correct. If there's a class of graphs that excludes some H-minor (for any H), then this class has special structure that in principle will lead to more efficient algorithms. The "in principle" part is the killer though, since it can be quite difficult to determine the structure in order to exploit it.


text:
Q: Retrieving the progress of getObject (aws-sdk) I'm using node.js with the aws-sdk (for S3).... When I am downloading a huge file from s3, how can I regularly retrieve the progress of the download so that the front-end can show a progress bar? Currently I am using getObject. (https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property)
The code to download the file works. Here's a snippet of my code...
 return await new Promise((resolve, reject) => {
  this.s3.getObject(params, (error, data) => {
    if (error) {
      reject(error);
    } else {
      resolve(data.Body);
    }
  });

I'm just not sure how to hook into the progress as it's downloading. Thanks in advance for any insight!

A: You can utilize S3 byte-range fetching which allows the fetching of small parts of a file in S3. This capability then allows us to fetch large objects by dividing the file download into multiple parts which brings the following advantages:

*

*Part download failure does not require full re-downloading of the file.

*Download pause/resume capability.

*Download progress tracking

*Retry packets that failed or interrupted by network issues

*Sniff headers located in the first few bytes of the file if we just need to get metadata from the files.

You can split the file download by your size of choice (I propose 1-4mb at a time) and download the parts chunk by chunk, when each of the get object promises complete, you can trace how many have completed. A good start is by looking at the AWS documentation.

A: STREAMING OPTION
Another option is to use a stream and track the amount of bytes received:
    const { ContentLength: contentLength } = await s3.headObject(params).promise();

    const rs = s3.getObject(s3Params).createReadStream();

    let progress = 0;
    rs.on('data', function (chunk) {
      // Advance your progress by chunk.length
      progress += chunk.length;
      console.log(`Progress: ${progress / contentLength}%`);
    });

    // ... pipe to write stream


text:
Q: How do I raw URL encode/decode in JavaScript and Ruby to get the same values in both? I am working on a web application where I have to encode and decode a string at the JavaScript side and Ruby backend of the code. the only problem is that the escape methods for JavaScript and Ruby have a small difference. in JavaScript the " " is treated as "%20" but in ruby the " " is encoded to "+".
Any way to solve this? Another Ruby method to encode a string in raw URL encode?
After some Selenium testing I noticed that for some reason the URI.unescape mixes up between the "£" and the "?". If I use encodeURIComponent("£"); in JavaScript and then URI.unescape("%C2%A3") in Ruby which is the value we get when we encode the "£" sign, I get the "?" sign returned. Any solution?

A: URI.escape was deprecated, an alternative is ERB::Util.url_encode.
ERB::Util.url_encode(foo)

If you are using it inside an .erb file you can do:
u(foo)

A: Use
URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

in ruby, and
encodeURIComponent(foo);

in javascript
Both these will behave equally and encode space as %20.

A: require "uri";
puts URI.escape "1 2;", Regexp.new("[^0-9a-z\\-_.!~*'()]", "i");


text:
Q: Three individuals have now commented the exact same comment on old answers of mine?
Possible Duplicate:
Why do I get exactly the same comment by different users for my link-only answer?

I have noticed that over the last few days the exact comment

This is really a comment, not an answer to the question. Please use "add comment" to leave feedback for the author.

has shown up from three individuals I've never seen before to old answers of mine.  None seem to be moderators.
I was wondering why this is.  Is there a campaign running?  Is there a new button I've not seen for this adding exactly that as a comment?

A: This is one of the canonical reasons provided to users who are reviewing low quality posts and recommend deletion of an answer they come across. The comment is automatically posted on their behalf.

It looks like the actual result doesn't match what's displayed in the dialog though. It may have changed at some point.

A: When users are reviewing Low Quality Posts (2K only), and mark any answer as "This is a comment, not an answer," that comment is automatically added for the reviewer.
And now the comment is changed to:

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.


text:
Q: Importing .vue template globally with a custom tagname I wants to name my .vue file as Application.vue, for instance, but using the tagname my-application.
With Vue.component() I can just call like Vue.component('my-application'), but as I am importing my component with template (from import), then I can't name it.
I wants that this component be registered globally on my application element (from new Vue()), then I like to use that inner any element inside my application element.

My current code is something like:
import "vue/Application.vue";
new Vue({ el: appNode});

Component:
<template>

Test

</template>

A: You have to put your import in a variable (by using import x from 'x'), and then you can use Vue.component(name, component) to register the component:
import Application from 'vue/Application.vue'
Vue.component('my-application', Application')

Then, in the Component where you want to use it
<template>
  <my-application>Test</my-application>
</template>


text:
Q: Sync SqlServer and MySql I  have two separate database on two separate host .one is MySQL and another is SQLServer. what is the best approach to sync them every week for example.

A: I think you need to make Linked Server.


text:
Q: Paypal Payment Invalid when redirecting with javascript? I have a problem with Paypal SDK REST, ASP.NET MVC 5 (C#) and javascript redirection.
I'm creating all the required components (ItemList, Address, Details, Amount,...) to make a Payment object for Paypal (not using credit card, so FundingInstruments are empty). After it is created, I use a View with a JavaScript Redirection to the URL Payment object has given to me. But everytime I see a 'Transaction is not valid...'
But, If I copy/Paste the URL ("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=...") to my browser MANUALLY, it works ! I'm going crazy...
Please have you got a solution ? (Find Enclosed the c# file, the payment in json format and the small html redirection component)

*

*C# Payment Class

using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using PayPal;
      using PayPal.Api;
      using System.Configuration;
      using System.Threading;
namespace WizziqWebApp.Paypal
{
    public class PaymentService
    {
        public enum EPaymentMethod { Paypal, CreditCard };
        public static readonly Dictionary<EPaymentMethod, string> PaymentMethods = new Dictionary<EPaymentMethod, string>() {
            { EPaymentMethod.Paypal, "paypal" },
            { EPaymentMethod.CreditCard, "credit_card" }
        };

        private OAuthTokenCredential _authToken;
        private APIContext _api;

        public Payment CreatePayment(Models.OrderModel order, EPaymentMethod paymentMethod, string cancelUrl, string returnUrl)
        {
            ItemList itemList = CreateItemList(order.shoppingCart);
            //itemList.shipping_address = (ShippingAddress) CreateDeliveryAddress(order.fullRegisterModel);
            Address InvoicingAddress = CreateInvoiceAddress(order.fullRegisterModel);
            Details details = CreatePaymentDetails(order.shoppingCart);
            Amount amount = CreateAmount(order.shoppingCart, details);

            Payer payer = null;
            if (paymentMethod == EPaymentMethod.CreditCard)
            {
                CreditCard creditCard = CreateCreditCard(InvoicingAddress);
                FundingInstrument fundingInstrument = CreateCreditCardFundingInstrument(creditCard);
                List<FundingInstrument> lst = new List<FundingInstrument>();
                lst.Add(fundingInstrument);
                payer = CreatePayerCreditCard(lst);
            }
            else if (paymentMethod == EPaymentMethod.Paypal)
            {
                payer = CreatePayerPaypal();
            }

            var transactionList = new List<Transaction>();
            Transaction transaction = CreateTransaction(amount, itemList, order);
            transactionList.Add(transaction);

            var payment = new Payment
            {
                transactions = transactionList,
                intent = "sale",
                payer = payer,
                redirect_urls = new RedirectUrls
                {
                    cancel_url = cancelUrl,
                    return_url = returnUrl
                }
            };

            payment = payment.Create(this.Api);

            System.IO.File.WriteAllText(@"d:\devel\PaymentObject.json",

payment.ConvertToJson());
            return payment;
        }

        public Payment ConfirmPayment(string token, string payerId)
        {
            var paymentExecution = new PaymentExecution
            {
                payer_id = payerId
            };

            var payment = new Payment { id = token };

            return payment.Execute(this.Api, paymentExecution);
        }

        private ItemList CreateItemList(Models.ShoppingCart Cart)
        {
            ItemList PaypalItemList = new ItemList();
            List<Item> itms = new List<Item>();

            if (Cart != null)
            {
                foreach (Models.ShoppingCartLine line in Cart.Lines)
                {
                    Item item = new Item();
                    item.name = line.Product.ArticleId;
                    item.currency = line.Currency.ShortCode;
                    item.price = line.UnitPrice.ToString("0.00", Thread.CurrentThread.CurrentCulture);
                    item.quantity = Convert.ToString(line.Quantity);
                    item.sku = line.Product.ArticleId;
                    itms.Add(item);
                }
            }

            PaypalItemList.items = itms;
            return PaypalItemList;
        }

        private Address CreateInvoiceAddress(Models.FullRegisterModel model)
        {
            Address Address = null;

            if (model != null && model.InvoicingAddress != null)
            {
                Address = new Address();
                Address.city = model.InvoicingAddress.City;
                Address.country_code = model.InvoicingAddress.Country;
                Address.line1 = model.InvoicingAddress.StreetAddress;
                Address.postal_code = model.InvoicingAddress.ZipCode;
                Address.state = model.InvoicingAddress.State;
            }

            return Address;
        }

        private ShippingAddress CreateDeliveryAddress(Models.FullRegisterModel model)
        {
            ShippingAddress Address = null;

            if (model != null && model.DeliveryAddress != null)
            {
                Address = new ShippingAddress();
                Address.city = model.DeliveryAddress.City;
                Address.country_code = model.DeliveryAddress.Country;
                Address.line1 = model.DeliveryAddress.StreetAddress;
                Address.postal_code = model.DeliveryAddress.ZipCode;
                Address.state = model.DeliveryAddress.State;
                Address.recipient_name = model.LastName + ", " + model.FirstName;
            }

            return Address;
        }

        private CreditCard CreateCreditCard(Address invoiceAddress)
        {
            CreditCard creditCard = null;
            {
                creditCard = new CreditCard();
                creditCard.billing_address = invoiceAddress;
                creditCard.cvv2 = "874";  //card cvv2 number
                creditCard.expire_month = 4; //card expire date
                creditCard.expire_year = 2020; //card expire year
                creditCard.first_name = "Aman";
                creditCard.last_name = "Thakur";
                creditCard.number = "4032034438655220"; //enter your credit card number here
                creditCard.type = "visa"; //credit card type here paypal allows 4 types
            }
            return creditCard;
        }

        private Details CreatePaymentDetails(Models.ShoppingCart Cart)
        {
            Details details = null;
            if (Cart != null)
            {
                details = new Details();
                details.shipping = Convert.ToString(Cart.DeliveryFee.Total);
                details.subtotal = Convert.ToString(Cart.GetTotal());
                details.tax = "0";
            }
            return details;
        }

        private Amount CreateAmount(Models.ShoppingCart Cart, Details details)
        {
            var total = Cart.GetTotal() + Cart.DeliveryFee.Total + Convert.ToDecimal(details.tax);

            var amount = new Amount
            {
                currency = Cart.Currency.ShortCode,
                details = details,
                total = total.ToString()
            };

            return amount;
        }

        private Transaction CreateTransaction(Amount amount, ItemList itemList, Models.OrderModel model)
        {
            Transaction transaction = new Transaction();
            if (amount != null && itemList != null)
            {
                transaction.amount = amount;
                transaction.description = "WIZZIQ products";
                transaction.invoice_number = Convert.ToString(model.OrderNumber);
                transaction.item_list = itemList;
                //transaction.notify_url = "";
                //transaction.order_url = "";
            }
            return transaction;
        }

        private FundingInstrument CreateCreditCardFundingInstrument(CreditCard creditCard)
        {
            return new FundingInstrument()
            {
                credit_card = creditCard
            };
        }

        private Payer CreatePayerCreditCard(List<FundingInstrument> listFundingInstruments)
        {
            Payer payer = new Payer();
            if (listFundingInstruments != null)
            {
                payer.funding_instruments = listFundingInstruments;
                payer.payment_method = PaymentMethods[EPaymentMethod.CreditCard];
            }
            return payer;
        }

        private Payer CreatePayerPaypal()
        {
            Payer payer = new Payer();
            payer.payment_method = PaymentMethods[EPaymentMethod.Paypal];
            return payer;
        }

        private OAuthTokenCredential ApiAccessToken
        {
            get
            {
                if (this._authToken != null)
                {
                    return this._authToken;
                }

                var clientId = ConfigurationManager.AppSettings["clientId"];
                var secretToken = ConfigurationManager.AppSettings["secretToken"];
                var config = new Dictionary<string, string> { { "mode", "sandbox" } };

                this._authToken = new OAuthTokenCredential(clientId, secretToken, config);

                return this._authToken;
            }
        }

        private APIContext Api
        {
            get
            {
                return this._api ?? (this._api = new APIContext(this.ApiAccessToken.GetAccessToken()));
            }
        }
    }
}

*HTML Redirection

@{
    ViewBag.Title = "_Redirect";
    Layout = "~/Views/Shared/Layout/_LayoutEmpty.cshtml";
}

Please wait...

While redirecting to Paypal...

*JSON Payment

{
   "id":"PAY-14N977666S5313604KWP4CGQ",
   "intent":"sale",
   "payer":{
      "payment_method":"paypal",
      "payer_info":{
         "shipping_address":{

         }
      }
   },
   "transactions":[
      {
         "related_resources":[

         ],
         "amount":{
            "currency":"EUR",
            "total":"18033.45",
            "details":{
               "subtotal":"18033.45"
            }
         },
         "description":"WIZZIQ products",
         "invoice_number":"4",
         "item_list":{
            "items":[
               {
                  "quantity":"1",
                  "name":"IQREPAIRKIT",
                  "price":"1500.00",
                  "currency":"EUR",
                  "sku":"IQREPAIRKIT"
               },
               {
                  "quantity":"3",
                  "name":"IQBUR010",
                  "price":"9.20",
                  "currency":"EUR",
                  "sku":"IQBUR010"
               },
               {
                  "quantity":"1",
                  "name":"IQBUR016",
                  "price":"9.20",
                  "currency":"EUR",
                  "sku":"IQBUR016"
               },
               {
                  "quantity":"250",
                  "name":"IQREP20INJ",
                  "price":"49.90",
                  "currency":"EUR",
                  "sku":"IQREP20INJ"
               },
               {
                  "quantity":"1",
                  "name":"IQPOLISH",
                  "price":"3.75",
                  "currency":"EUR",
                  "sku":"IQPOLISH"
               },
               {
                  "quantity":"2",
                  "name":"IQTRANSFO",
                  "price":"8.95",
                  "currency":"EUR",
                  "sku":"IQTRANSFO"
               },
               {
                  "quantity":"5",
                  "name":"IQSTARTERKIT",
                  "price":"800.00",
                  "currency":"EUR",
                  "sku":"IQSTARTERKIT"
               }
            ]
         }
      }
   ],
   "state":"created",
   "create_time":"2015-07-10T12:56:58Z",
   "update_time":"2015-07-10T12:56:58Z",
   "links":[
      {
         "href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-14N977666S5313604KWP4CGQ",
         "rel":"self",
         "method":"GET"
      },
      {
         "href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-4HC32806NW4529238",
         "rel":"approval_url",
         "method":"REDIRECT"
      },
      {
         "href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-14N977666S5313604KWP4CGQ/execute",
         "rel":"execute",
         "method":"POST"
      }
   ]
}

Thank you very much ! I'm really stuck...

A: For the record, here's how I fixed it:
Ok, that was my fault, the redirection was not what I expected to be... To correct it, don't forget to put your URL from RAZOR in RAW mode :).

Anyway, thanks to the Paypal team for trying to help but too late :)


text:
Q: Access 2000 blocking access to file by other users Sometimes when a user tries to open a specific file, Access 2000 produces this message:
"The database has been placed in a state by user 'Admin' on machine '(whoever the user is)' that pevents it from being opened or locked."
The company I work for has the file located on the Printer public folder at \PRINTER\Public, and all users access the file by opening it from this location on their machines.  There are a total of 15 users.
Does anyone know why this happens or, more importantly, how I can get this to NOT happen?
If it is helpful, I notice the user who is usually blocking access according to the error message is 'WOODY-PC', which is also a network folder.
Thanks in advance for the help in advance.

A: This happens because the database was simply never designed to be used like this.
Access 2000 (especially) should be used as a desktop application for a single user accessing a single database or multiple users using it in order to access a database server back end - such as SQL server.
There is no easy solution, but if you have 15 users, I am guess the company is growing - you should invest in your IT infrastructure and possibly at this point, I would recommend using a spare machine to install SQL (not sure Express allows 15 users?), then upgrade the Database to run on that.
This may take additional work, but it should be a scalable solution to push the business in to the future.

A: You can't share an Access database like that.
The app should be split into front end (queries, forms, reports, etc. -- everything but tables) and back end (tables only), and the front end will have linked tables pointing to the back end.
Then each user gets an individual copy of the front end.
The back end (with the tables) stays on the file server in a location accessible (and writable) to all users (putting in the printers folder seems very odd, but is perhaps a clever way to store it on a server that otherwise has no user-writable shares that are accessible to all users).
Attempting to share front-end objects never works reliably in the long run (the error your getting is just the beginning), and can lead to all sorts of weird problems, and to corruption of the shared front-end database.
Many people object to this because they think it makes it harder to distribute updates to the application. It actually doesn't, because all you have to do is copy over top of the old front end with the updated one. This can be done any number of ways, and it's basically a triviality.


text:
Q: How do you properly implement a robust stack in C Prior Knowledge
I've read and understand a bit about stacks and data structures, but couldn't find the answer to this specific question. I know that any programmer worth anything will implement security exception handling beyond the default in their programs.
Situation
I would like to understand how a program could be written in C that establishes a relatively robust stack with exception handling for some arbitrary case S.
My goal is to discern from this very specific information why (from what I understand) it is always possible to exploit the SEH in a program and execute arbitrary code.
The issue is not that I do not understand the concept of overflowing a buffer - I do not understand why (in very specific, CPU architecture related reasons) the security implemented on the stack (canaries, etc) cannot sufficiently address these issues (like heap overflows cannot be stopped?).
Reference Information
"There is no sane way to alter the layout of data within a structure; structures are expected to be the same between modules, especially with shared libraries. Any data in a structure after a buffer is impossible to protect with canaries; thus, programmers must be very careful about how they organize their variables and use their structures. In C and C++, structures with buffers should either be malloc()ed or obtained with new."
- via http://en.wikipedia.org/wiki/Buffer_overflow_protection#Implementations
Also:
http://blogs.msdn.com/b/michael_howard/archive/2006/08/16/702707.aspx
If anyone knows a good resource for understanding this material or can provide a code snippet, I would be very grateful.

A: The security of the stack can be made secure enough to cope with stack overflows:
http://msdn.microsoft.com/en-us/library/9a89h429(VS.80).aspx
The question as to why you need registered exception handlers (safe-SEH) and why normal exception handlers won't cut it is because of the case where you get very large stack overflows.
Let's suppose I have the function which begins
try {
   char buffer[N];
   strcpy(&buffer, &attacker);
} __except(...) { }

This might translate into the assembly code
push ebp
mov ebp, esp
; GS if you want to here

; install the exception handler:
push lbl_Exceptionhandler
push dword ptr [fs:0]
mov dword ptr[fs:0], esp

; setup the locals inside the stack
sub esp, LOCALS
; GS if you want to here

; call strcpy
lea ecx [ebp + offset_to_buffer];
push ecx
lea edx, [ebp + offset_to_attacker]
push edx
call _strcpy
add esp, 8

; uninstall the locals
mov esp, ebp

; uninstall the exception handler
pop dword ptr [fs:0]

; return
pop ebp

; optionally check GS cookies that we might have also inserted at any point in this function.
call _checksecuritycookie
ret

Or in other words, the stack looks like this:
RET PTR
/GS1
SAVED EBP
/GS2
SAVED FS:0
/GS3
LOCAL char buffer[N]

GS1, GS2 and GS3 are locations where stack canaries might choose to write the stack cookie. Note that the cookie will only be checked at the end of the function (This is important in computer security. When you introduce a check you need to think not only whether the check will detect the overflow, but whether it will detect it before it is already too late; and that requires thinking where the check will take place. For stack cookies, the cookie is only inspected on function exits, because stack cookies are generally only there to protect the return address, not to protect local variables).
The problem with normal exception handlers is what happens if the attacker buffer is really huge. Let's suppose it's so huge it destroys the entire stack, writes onto the guard page for the thread and triggers a fault?
Well, the kernel calls back into ntdll and tells it to sort it's process out, and ntdll's first port of call is to see if there are any registered exception handlers. Now how does it find what exception handler to call? Well, it looks at fs:0, which points to the exception handler on the stack, and calls the exception handler pointer. Except that exception handler's on the stack that the attacker just destroyed.
Oops. Now the attacker has control of EIP and you lose.
Safe-SEH solves this problem by noting that the list of exception handlers that you might ever want to call is in fact a finite list entirely determined at compile time. By burning this list into the PE file itself, ntdll has a chance to double check that the exception handler that it should jump to is, in fact, a real exception handler and not the cause of some evil attacker's plot to take over your EIP.
There's a cost to Safe-SEH (hence why it is opt in), but that cost is that it becomes more expensive to catch an exception, since ntdll will now do more work before your exception handler takes over.
Despite this, my advice is that SafeSEH should always be on. Making it easier to lose your customer's credit card details because your app is critically performance dependent on the speed of throwing exceptions suggests a mentality so horrendously broken in the developers mind that they should be immediately put into a cannon and fired into the sun to avoid their awful code from damaging society.

A: The normal way to implement a stack in C is to use a linked list. For example:
struct stack_entry {
    struct stack_entry *previous;
    /* other fields for the actual data */
}

struct stack_entry *stack_top = NULL;

void push(struct stack_entry *entry) {
    entry->previous = stack_top;
    stack_top = entry;
}

struct stack_entry *pop(void) {
    struct stack_entry *entry;

    entry = stack_top;
    if(entry != NULL) stack_top = entry->previous;
    return entry;
}

This is as robust and difficult to exploit as any other normal code.

A: If you're not implementing a stack in C, but are implementing a C compiler (in any language), then..
It would be possible to create a C compiler that detects programming errors and generates safe code. For example, for every read or write the compiler could insert checks to ensure that the read or write is contained within one storage area (e.g. and you're not trying to write 4 bytes at the end of an array of char or something); where a signal is raised (e.g. "SIGSEGV") if one of these checks fail.
Due to the nature of C, these checks would involve scanning things like the heap, and it'd require more code to be insert to track the sizes of things on the stack.
The main reason this hasn't been implemented is that it'd create massive performance problems, and would therefore defeat the purpose of using C to begin with.
However, there are debugging tools (e.g. valgrind) that do this type of checking by running the application inside a virtual machine (where the virtual machine tracks the sizes of storage areas and is able to check reads/writes before they're performed).


text:
Q: Spring boot,SOAP,Spring jpa i have few problems with Spring boot(SOAP - Apache cxf,Spring jpa).
When i run my project, i get following error, but if i change Spring boot version on 1.4.0, its ok(but EntityManager is null):
Where was I wrong?I want to connect spring-jpa with my SOAP web service using Spring boot.
java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration due to org/springframework/boot/context/embedded/ServletRegistrationBean not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:55) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at

my application.properties
# server HTTP port
server.port=9090
# set the CXFServlet URL pattern
cxf.path=/codenotfound/ws
# hello world service address
helloworld.service.address=http://localhost:9090/codenotfound/ws/helloworld
spring.datasource.url=jdbc:mysql://localhost:3306/concretepage
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

I using DAO method
@Transactional
@Repository
public class ArticleDAO implements IArticleDAO {
    @PersistenceContext
    private EntityManager entityManager;
    @Override
    public Article getArticleById(int articleId) {
        return entityManager.find(Article.class, articleId);
    }
    @SuppressWarnings("unchecked")
    @Override
    public List<Article> getAllArticles() {
        String hql = "FROM Article as atcl ORDER BY atcl.articleId";
        return (List<Article>) entityManager.createQuery(hql).getResultList();
    }
    @Override
    public void addArticle(Article article) {
        entityManager.persist(article);
    }
    @Override
    public void updateArticle(Article article) {
        Article artcl = getArticleById(article.getArticleId());
        artcl.setTitle(article.getTitle());
        artcl.setCategory(article.getCategory());
        entityManager.flush();
    }
    @Override
    public void deleteArticle(int articleId) {
        entityManager.remove(getArticleById(articleId));
    }
    @Override
    public boolean articleExists(String title, String location) {
        String hql = "FROM Article as atcl WHERE atcl.title = ? and atcl.category = ?";
        int count = entityManager.createQuery(hql).setParameter(1, title)
                      .setParameter(2, location).getResultList().size();
        return count > 0 ? true : false;
    }
}

pom.xml
  <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.codenotfound</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <url>http://</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <cxf.version>3.1.7</cxf.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Apache CXF-JAXWS-->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <!-- Spring boot Test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-codegen-plugin</artifactId>
                <version>${cxf.version}</version>
                <executions>
                    <execution>
                        <id>generate-sources</id>
                        <phase>generate-sources</phase>
                        <configuration>
                            <sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
                            <wsdlOptions>
                                <wsdlOption>
                                    <wsdl>${project.basedir}/src/main/resources/wsdl/helloworld.wsdl</wsdl>
                                    <wsdlLocation>classpath:wsdl/helloworld.wsdl</wsdlLocation>
                                </wsdlOption>
                            </wsdlOptions>
                        </configuration>
                        <goals>
                            <goal>wsdl2java</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

And I'm trying to call this method here
public class HelloWorldImpl implements HelloWorldPortType {
    @Autowired
    private IArticleDAO articleDAO;
    private static final Logger LOGGER = LoggerFactory
            .getLogger(HelloWorldImpl.class);

    @Override
    public Greeting sayHello(Person request) {
        LOGGER.info(
                "Endpoint received person=[firstName:{},lastName:{}]",
                request.getFirstName(), request.getLastName());
        List<Article> _list = articleDAO.getAllArticles();
        System.out.println("title: " + _list.get(0));
        String greeting = "Hello " + "rasras" + " "
                + request.getLastName() + "!";
        ObjectFactory factory = new ObjectFactory();
        Greeting response = factory.createGreeting();
        response.setGreeting(greeting);

        LOGGER.info("Endpoint sending greeting=[{}]",
                response.getGreeting());
        return response;
    }
}

main class
@SpringBootApplication
public class SpringCxfApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCxfApplication.class, args);
    }
}

Project structure

A: Please use CXF 3.1.11 or later if you are using spring-boot 1.5+. Here is the bug, the fix has already gone in to 3.1.11


text:
Q: problem with cross reference an equation using cleveref I want to refer to an equation through my document, so I thought it is beter to use cleveref package, the problem is when I refer to an equation it refer to the section where the equation is.
I work on my thesis so it would be very helpful to use cleveref instead of the regular \ref command.
here, a small example.
\documentclass[a4paper, 14pt,]{extreport}
\usepackage{color, xcolor}
\usepackage{amsmath}
\usepackage{breqn}
\usepackage{varioref}
\usepackage{hyperref}
\hypersetup{colorlinks=true,
citecolor=red,
linkcolor=blue,
urlcolor=magenta,
breaklinks}
\usepackage{cleveref}
\crefname{equation}{equation}{equations}
\newcommand{\p}{\partial}
\newcommand{\beqa}{\begin{eqnarray}}
\newcommand{\eeqa}{\end{eqnarray}}

\begin{document}
\chapter{Mathematical Modelling}\label{ch:math}

\section{Reynolds equation}\label{sec:Reynolds}

The well known Reynolds equation in dimensional form is given below:
\beqa \label{eq:rey_car}
\frac{\p}{\p x}\left(h^3 \frac{\p p}{\p x}\right) + \frac{\p}{\p y}\left(h^3 \frac{\p p}{\p y}\right) = 6\mu U \frac{\p h}{\p x} +12 \mu \frac{\p h}{\p t}
\eeqa
transform ~\cref{eq:rey_car} to polar coordinate by using the following relations:
$$\theta = x R ~~ , ~~ z = \frac{L}{2} y $$
\beqa\label{eq:rey_polar}
\frac{\p}{\p \theta}\left(h^3 \frac{\p p}{\p \theta}\right) + \left(\frac{D {L}\right)^2 \frac{\p}{\p z} \left(h^3 \frac{\p p}{\p z}\right) = 6 \mu U R \frac{\p h}{\p \theta} + 12 \mu R \frac{\p h}{\p t}
\eeqa
now, to get the dimensionless form of \vref{eq:rey_polar}
\end{document}

this is the output

A: You have discovered one of the many reasons eqnarray should be avoided.

*

*Never use eqnarray (see eqnarray vs align)

*Never use $$ (see Why is \[ ... \] preferable to $$ ... $$?)

*Never have two consecutive displays

*For single equations, use equation
In order to comply with 2 and 3 in your case, use gather.
\documentclass[a4paper, 14pt]{extreport}
\usepackage{color, xcolor}
\usepackage{amsmath}
\usepackage{varioref}
\usepackage{hyperref}
\hypersetup{
  colorlinks=true,
  citecolor=red,
  linkcolor=blue,
  urlcolor=magenta,
  breaklinks
}
\usepackage{cleveref}
\crefname{equation}{equation}{equations}

\newcommand{\p}{\partial}

\begin{document}

\chapter{Mathematical Modelling}\label{ch:math}

\section{Reynolds equation}\label{sec:Reynolds}

The well known Reynolds equation in dimensional form is given below:
\begin{equation}\label{eq:rey_car}
  \frac{\p}{\p x}\left(h^3 \frac{\p p}{\p x}\right) +
  \frac{\p}{\p y}\left(h^3 \frac{\p p}{\p y}\right) =
  6\mu U \frac{\p h}{\p x} +12 \mu \frac{\p h}{\p t}
\end{equation}
transform~\cref{eq:rey_car} to polar coordinate by using the following relations:
\begin{gather}
  \theta = x R, \quad z = \frac{L}{2} y \nonumber \\
  \frac{\p}{\p \theta}\left(h^3 \frac{\p p}{\p \theta}\right) +
  \left(\frac{D}{L}\right)^2 \frac{\p}{\p z} \left(h^3 \frac{\p p}{\p z}\right) =
  6 \mu U R \frac{\p h}{\p \theta} + 12 \mu R \frac{\p h}{\p t}
  \label{eq:rey_polar}
\end{gather}
Now, to get the dimensionless form of \vref{eq:rey_polar}
\end{document}


text:
Q: Troubles with global messages in Magento My knoledges in magento not so deep so I had a trouble with the magento global messages output.
I created my module. On the index page of my module (the route is /vouchers) I had a form. So by POST i send data to Controller (the route is the same (/voucehrs)) where I validate data:
if(!isset($post["to_name"]) || !$post['to_name'])
   {
       Mage::getSingleton('customer/session')->addError($this->__('Please enter  "To Name" information'));
       $errors = 1;
   }

...

  if(!$errors)
     {
        Mage::getSingleton('customer/session')->addSuccess($this->__('Your order is successfully saved and now is in process'));
     }

In the template I use     <?php echo $this->getMessagesBlock()->getGroupedHtml() ?> but nothing happens, though I dumped Session variable where I can see success message.
Where I was wrong?

A: Please check your controller. If you renders the layout, you must include the following code in your action.
$this->_initLayoutMessages('customer/session');

So your action should be like this :
$this->loadLayout();
$this->_initLayoutMessages('customer/session');
$this->renderLayout();

It may help you.

A: Notice
Mage::getSingleton('core/session')->addNotice('Notice message');

Success
Mage::getSingleton('core/session')->addSuccess('Success message');

Error
Mage::getSingleton('core/session')->addError('Error message');

Warning (admin only)
Mage::getSingleton('adminhtml/session')->addWarning('Warning message');

Output errors from a controller
public function sendAction()
    {
        try
        {
            $mail = new Zend_Mail();
            $mail->send();
        }
        catch (Exception $e)
        {
            Mage::getSingleton('core/session')->addError('Error sending mail');
        }
        $this->loadLayout();
        $this->renderLayout();
    }

MOre info for session in mageno how to get and set

A: Can you try core/session instead of customer/session? It may help you.

A: First, we strongly advise you to install/configure Xdebug - this tool will save you lots of time.
As for the issue, try to use
Mage::getSingleton('customer/session')

instead of
Mage::getSingleton('core/session')

If it doesn't work, you may try:
// after post form
$this->getLayout()->getMessagesBlock()->setMessages(Mage::getSingleton('customer/session')->getMessages(true));

// when display
$this->getLayout()->getMessagesBlock()->getGroupedHtml();

Hope it will help. :)

A: I found this stack overflow post extremely helpful.
What worked for me was a combination of Alex Ivanov's and Emipro Technologies Pvt. Ltd's answsers, as below (controller code):
$this->loadLayout();
$this->_initLayoutMessages('core/session');
$this->renderLayout();


text:
Q: Memory Allocation issue when modifying CreateToolbarEx function with new bitmap I'm trying to modify some old code (c++) that uses the CreateToolbarEx function, in an attempt to use a new bitmap and replace our 24x24 pixel toolbar buttons with flashier 36x36 ones.  The function I'm using is as follows:
m_hToolbarWnd = CreateToolbarEx(m_hPagerWnd, ws, ID_TOOLBAR, NUMBERTOOLBARBITMAPS, hInst, IDB_TOOLBAR, tbInitButtons, m_ncButtons, 24, 24, 24, 24, sizeof(TBBUTTON));

I'm able to expand the size of the current toolbar buttons by changing the '24's to '36', but if I change IDB_TOOLBAR to the new toolbar bitmap and run the program I hit a memory access read violation pointing to the CreateToolbarEx function.  Am I missing something on how the bitmap is getting its memory allocation or creating the individual buttons?  The new toolbar is 1584x36 pixels (44 buttons).

A: This is old, but hopefully the solution I found will help someone.  I had overlooked the fact that I was changing from a 16-bit color bitmap to 24-bit, which I was unable to get CreateToolbarEx to handle.  Instead, I had to call CreateWindowEx and create and set the icon ImageList for it.  Working code:
m_hToolbarWnd = CreateWindowEx(0L, TOOLBARCLASSNAME, "", ws, 36, 36, 36, 36, m_hPagerWnd, (HMENU) ID_TOOLBAR, hInst, NULL);
SendMessage(m_hToolbarWnd, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0);
HBITMAP hBmp = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_TOOLBAR));
HIMAGELIST hIcons = ImageList_Create(36, 36, ILC_COLOR24, 0, m_ncButtons);
ImageList_Add(hIcons, hBmp, NULL);
SendMessage(m_hToolbarWnd, TB_SETIMAGELIST, 0, (LPARAM) hIcons);


text:
Q: COPY failed: stat /var/lib/docker/tmp/docker-builder700869788/private: no such file or directory I got an error:

COPY failed: stat /var/lib/docker/tmp/docker-builder700869788/private: no such file or directory .

I wrote in Dockerfile:
FROM "centos"

    RUN mkdir ~/.ssh
    COPY ./private ~/.ssh/id_rsa
    RUN yum install -y https://centos7.iuscommunity.org/ius-release.rpm
    RUN yum install -y wget
    RUN yum update -y

and when I run docker build ./ -t docker/app,I got an error:
Status: Downloaded newer image for centos:latest
 ---> ff426288ea90
Step 2/22 : RUN mkdir ~/.ssh
 ---> Running in 49d3950mwpion
Removing intermediate container 49d73360f899
 ---> 24shentufhckm
Step 3/22 : COPY ./private ~/.ssh/id_rsa
COPY failed: stat /var/lib/docker/tmp/docker-builder700869788/private: no such file or directory  .

Of course, private key is in my PC.Now this Dockerfile is in myname/Desktop/app/Dockerfile .And private ket is in ~/.ssh/id_rsa .Is this error meaning directory wrong?

A: You should put the file into the same directory with Dockerfile.

A: Did you try to run docker build from outside the Dockerfile directory? It worked for me: docker build dir/.


text:
Q: How can i assign a two dimensional array into other temporary two dimensional array.....?? in C Programming Hi I am trying to store the contents of two dimensional array into a temporary array.... How is it possible... I don't want looping over here, as it would add an extra overhead.. Any pointer notation would be good.
struct bucket
{
   int nStrings;
   char strings[MAXSTRINGS][MAXWORDLENGTH];
};

void func()
{
   char **tArray;
   int tLenArray = 0;
   for(i=0; i<TOTBUCKETS-1; i++)
   {
      if(buck[i].nStrings != 0)
      {
         tArray = buck[i].strings;
         tLenArray = buck[i].nStrings;
      }
   }
}

The error here i am getting is:-
[others@centos htdocs]$ gcc lexorder.c
lexorder.c: In function âlexSortingâ:
lexorder.c:40: warning: assignment from incompatible pointer type

Please let me know if this needs some more explanaition...

A: You can use memcpy or wrap it in a struct and use assignment on the structs, but any way you do it, you'll effectively be looping over all the elements. That's fundamental.

A: The compiler issue is that the notation array[...][...] is not the same as char **. The char ** notation is pointer to a pointer.
For example;
char ** pA;
pA = malloc(10);

pA[0] is a pointer
in the case of array[...][...]
array[0] is not a pointer. It is a char.
If you want to do what you are trying then you you need declare strings as char ** and initialize your structure like this.
struct bucket
{
    int nStrings;
    char** strings;
};

struct bucket buck;

buck.strings = (char **)malloc(MAXSTRINGS);

for(i = 0; i < MAXSTRINGS; i++)
    buck.strings[i] = (char*)malloc(MAXWORDLENGTH)

A: You mean cloning the array right?
Unfortunately, I don't think there is a way to clone an array in C without looping through all items in the array and making a copy of them somewhere else.
The main problem is that since they are pointers, any thing you do to simply copy the contents would just copy the addresses and you would have a reference, not a clone.