text:
Q: expression web 4 vs visual studio 2010 for client side and c# I am trying to connect my project from VS2010 to expression 4, but it is not so intuitive.  So I'm asking myself if VS2010 has the same capabilities as expression 4?
What is the best solution for a programmer like me that writes css3, html5 and javascript that needs to work together with c# and asp programmers?

A: Expression and Visual Studio have a very different focus group.  Expression is for designers and has extra tools/capabilities to better handle creating your markup.  Visual Studio is more geared towards hooking that design up with code.
That isn't to say you can't build a beautiful site with VS alone; many do it.  However, if you need good tool support, as opposed to hand coding the look, then go with Expression.
Expression does support the project models handled by Visual Studio and has hooks to source control like TFS, so you can use both side by side just fine.


text:
Q: Mi header es un desastre con position: fixed; Tengo una página web. Toda funciona bien hasta ahora:

Pero se me ha ocurrido hacer que mi header sea fijo en la página, para lo que recurrí a usar position: fixed;.
El header se vuelve un total desastre desordenado:

Lo de la superposición es entendible, porque eso es fácil de arreglar, pero por lo demás, el header se vuelve un auténtico licuado, y no he logrado arreglarlo.
Cosas que he intentado:

*

*Hacer que un div sea fijo y que el header sea contenido por el div para poder poner position: relative al header.

*Reconstruir el CSS.

Programación de mi header:
HTML:

Offered by TechMan Walker in:
<select id="language"><option value="en">English   ▼</option><option value="es">Español  &nbsp▼</option></select>

CSS:

body {
    background-color: #070707;
    margin: 0px;
    color: #cccccd;
    font-family: "Acherus", "Arial";
    word-break: break-word;
    font-size: 1rem;
    width: 100%;
}

header {
    background-color: #333339;
    padding: 1em;
    width: auto;
    height: 2em;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
}

/* Barra superior - División izquierda */ #navbar_left {
    position: absolute;
    width: auto;
    justify-content: flex-start;
    left: 0;
    display: flex;
    align-items: center;
    padding: 0px;
    margin: 0px;
}

/* Barra superior - División derecha */
#navbar_right {
    position: absolute;
    width: auto;
    justify-content: flex-end;
    right: 0;
    display: flex;
    align-items: center;
    padding: 0px;
    margin: 0px;
}

#navbar_left .icon, #navbar_right .icon {
    padding-top: auto;
    padding-bottom: auto;
    margin-top: auto;
    margin-bottom: auto;
}

#logo {
    background-color: #00000000;
    width: 5.6em;
    padding: 0px;
}

#help {
    cursor: help;
}

select {
    background-color: #FFFFFF;
    border-radius: 2px;
    color: #000000;
    linear-gradient:none;
    overflow: hidden;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    padding: 0.7em;
}

¿Alguien sabe cómo puedo lograr que me salga como en la primera imagen y que quede fijo en la página sin moverse?
Gracias y espero que me puedas ayudar. ¡Ten un lindo día!

A: varias cosas, la forma de hacer que un fixed se vea por encima de todos los demás elementos en pantalla es z-index:1000, le pones un valor y vas probando hasta que tengas el header por encima de los demás elementos con un z-index inferior.
Recuerda que cuando le das a un elemento position:fixed, este pierde el flujo de elementos en la pantalla, ósea que los elemento se colocan delante o detrás de el pero nunca a continuación como en el flujo normal de position:auto
También cambie el width:auto a max-width:100%, eso podría ser una razón por la cual tu elementos no se posiciona correctamente en el top de la pagina.
Otra solución es que le des al header las siguientes propiedades
header {
  position:fixed;
  top:0px;
  right:0px;
  left:0px;
  max-width:100%;
  height:70px;   /* Por darle un valor fijo para evitar conflictos con :auto */
  z-index:1000000  /* Exagero el valor de z-index porque no se que z-index tengas puesto en el resto de tu css*/
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Enable PodTolerationRestriction on gcloud k8s cluster I have a namespace in k8s with the setting:
scheduler.alpha.kubernetes.io/defaultTolerations:
      '[{"key": "role_va", "operator": "Exists"}]'
If I am not mistaken all pods that are created in this namespace must get this toleration.
But the pods don't get it.
I read this and understood that I must enable the PodTolerationRestriction controller.
How can I do this on gloud?

A: In order to enable PodTolerationRestriction you might be required to set --enable-admission-plugins flag in kube-apiserver configuration. This is according to the official documentation, as by default this plugin is not included in admission controller plugins list.
However, in GKE there is no possibility to adapt any specific flag for the current API server run-time configuration, because Kubernetes cluster engine core components are not exposed to any user purpose actions (related Stackoverflow thread).
Assuming that, you can consider using GCE and bootstrap cluster with any cluster building solutions, depending on your preference, within a particular GCE VM.


text:
Q: No value was provided for the parameter 'appIdName' when provisioning I've just enrolled in Apple's iOS Developer Program (account type: Individual).
In my Xcode organizer on my iPhone 4 device I click "Add device to provisioning portal" => Xcode asks my credentials => I enter them => I see "No value was provided for the parameter 'appIdName'." dialog window.
What am I missing?

A: I'm getting the same issue in Xcode. I think it's related to the wildcard app ID that Xcode creates for you. There seems to be an issue with that process that then cancels the device addition process that you're trying to complete.
You should still be able to add the device via the iOS Dev Center. Once logged in, go to the Provisioning Portal and you can add the device there.
Not perfect I know, but should allow you to start building apps and testing on your device until the Xcode issue is resolved.

A: You could avoid this problem by making App ID with wild-card id in iOS dev center.
I guess Organizer could not follow the updated policy related to App ID in iOS Dev Center/Provisioning Portal.
App ID with wild-card("*") is seems to be restricted in some function,
for example, Push Notification, Game Center.
and
developer also seems to be required to make sure the security option for the app related to the App ID.

A: Part of the process in Xcode's automated submitting of certificate requests is that it looks for a "Wildcard" app ID. If you're missing this (for some reason, it's created on some accounts automatically and not created automatically on others?), this automated process will likely fail.
To fix it, try the following:
1) "Revoke" any existing certificates you might have from within the developer portal
2) Create a new "App Id"; title it "Wildcard"; and enter only " * " (without any spaces or quotes) as the suffix.
3) Try the automated certificate request from within Xcode again, and it should now work
Cheers!

A: Actually, my initial goal was to be able to test my app on iPhone device. Clicking "Add device to provisioning portal" still results into the subject error, but anyway my iPhone device have been added somehow to the Provisioning Portal and now I can see my app on iPhone (I haven't even tried to add it via iOS Dev Center). My guess is that this procedure takes multiple steps to be completed, and only the last of them still fails now, while the rest of them do succeed.

A: In my case the provisioning profile for that application was invalid, then I did the following steps:

*

*Login on Developers Portal

*Click on Certificates, Identifiers & Profiles section.

*Go to Provisioning Profiles, in the list I realized my app profile
was invalid.

*Click to edit it and selected the corresponding certificates (all)
and devices (all).

*Download the profile and un Run. Issue solved.


text:
Q: Team City build - Workspace is null error I am setting up Maven project from a RTC repository on Team City. When I run the build on the project I am getting the following error:
"Failed to perform checkout on agent: Unable to start build as workspace name is null"
Does anyone has any idea how to fix this error.
More Details for the error:

*

*Updating sources: agent side checkout

*[VCS Root: Trunk] Agent Checkout

*[Agent Checkout] Unable to start build as workspace name is null

*[Updating sources] Failed to perform checkout on agent: Unable to start build as workspace name is null

A: Please check that build configuration has at least one build step (it can be a dummy or simple echo message).
I did face the same issue and could resolve it by creating a dummy step.


text:
Q: Vertical UIScrollView without code behind My goal is to have background image that fills whole screen and above that image there will be vertical scroll view because labels and text inputs will be stacked vertically, somehow i managed to achieve this, but after i added Navigation Controller, layout got messed up.
I simulated the View Controller size to height of 1000 so i can constraint the labels and inputs correctly, but how would i handle the image size and scroll sizes?


text:
Q: sourcing a shell script from a perl script I have a shell script to change my path permanently to another path. My requirement is to source it using a perl script(perl script has some other code as well and finally it has to source the below shell scipt)
test.sh:
!/bin/bash
cd /db/oa/invoke/path

test.pl:
!/usr/bin/perl
system("source /home/test.sh");

but sourcing is not working. I know the command system("sh /home/test.sh --help") for shell script execution from perl script. But I need similar command to source the shell script. Please let know, if I am missing any details. I have already seen questions being asked on same topic, but i didn't see a proper solution for sourcing. can anyone help me on this.
Regards Anand

A: As @tripleee said, you must exec yourself. Here is how I would do it:
if (defined $ENV{TOTO}) {
    print "TOTO is $ENV{TOTO}\n";
} else {
    my $cmd = ". ./source.txt ; exec $^X $0 " . join(' ', @ARGV);
    system ($cmd);
}

my script source.txt contains
export TOTO=titi


text:
Q: How can I get all views that have value in the tag attribute? I have 7 views has android:tag="92832380" in the same layout and I tried to get these views using findViewWithTag but it returns 1 view (first view) only so what is the best way to get all views that has 92832380 value?
Edit
According to the comments discussion below, I found this way to solve the problem but is it a good way, or is there a better way?

A: You can try using this way
fun getViewsByTag(rootView: ViewGroup, tag: String): ArrayList<View>? {
        val views = ArrayList<View>()
        val childCount = rootView.childCount
        for (i in 0 until childCount) {
            val child = rootView.getChildAt(i)
            if (child is ViewGroup) {
                views.addAll(getViewsByTag(child, tag)!!)
            }
            val tagObj = child.tag
            if (tagObj != null && tagObj == tag) {
                views.add(child)
            }
        }
        return views
    }

If you have multiple types of view with same tag you can identify them by is like if (child is EditText)


text:
Q: Can I put Data Access layer as JAR file in the tomcat/shared lib directory? I have created a Data Access layer which is responsible to retrieve data from the database using plain SQL query. My tomcat contains two web projects. Both projects contain same copy of Data Access layer.
Web Project1 (WP1)
     |----DataAccess layer
Web Project2 (WP2)
     |----DataAccess layer
I would like to separate Data Access layer from web project, so I don't need to maintain multiple copies.
WP1 -- WP2
  |             |
DataAccess layer
Is it the best practice to make the Data Access layer as JAR file and put it inside Tomcat shared lib folder?
Thanks,
  MFH

A: I won't say that doing so is dangerous but I definitely won't consider this solution as a "best practice" : sharing a library across all the web application will increase the probability that one of them will run into a classpath conflict.
For instance, suppose that you deploy another web application in which you're using (knowingly or not) a class that is duplicated (several classes with the same exact full qualified name), given that the shared libraries are loaded before the application specific libraries, you could end up using another class than the one expected. In the best scenarios, you'll figure it out quite easily but still that would have made you loose some time. In the worst scenario, your application won't behave as expected.
From my personal experience, I've seen this happening in the past : some applications were referring to a shared lib-1.0.jar and some others were deployed with a application-specific lib-2.0.jar (which had slightly evolved).
Besides, in your case, it won't cause a maintenance havoc : just adapt the deployment procedure from both of your web application to add the concerned library as a dependency (if you're using tools such as Maven or Ant, it's a piece of cake).


text:
Q: Run PHP Results inside WP Shortcode How would I put the below results into the WP Short code?
PHP Results:
    <?php

 function endsWith($haystack, $needle) {
     // search forward starting from end minus needle length characters
     return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
 }

 $lastDate = date('Y-m-d', strtotime('today - 30 days'));
 $todayDate = date('Y-m-d');

 $results = $wpdb->get_results( "SELECT * FROM `ucsite_statistics_pages` WHERE id=1428 AND `date` BETWEEN '$lastDate' AND '$todayDate' ", ARRAY_A );
    for($i=0;$i<count($results);$i++)
    if (endsWith(get_site_url().''.$results[$i]['uri'], 'http://universitycompare.com/universities/the-uni-of-westminster/')) {
        echo $results[$i]['count'];
        echo ',<br />';  } ?>

How do I insert the above 'if results' that are being echoed out into the below shortcode?
<?php
echo do_shortcode('[wp_charts title="linechart" canvaswidth="976px" canvasheight="244px" relativewidth="4" width="976px" height="244px" type="line" align="alignright" datasets=" { data to be here } "]');
?>

A: If I understand correctly, you have a shortcode called wp_charts that accepts a pramaeter datasets, and you want to create a new shortcode that runs a database query and embeds the results of the query as the value of datasets?
If so, there are several ways to do this, but I think the easiest - especially if you didn't write wp_charts yourself - is to create a new shortcode that runs the query and then calls the wp_charts shortcode.
For example:
function my_charts_with_data_shortcode_impl($atts, $content = null) {
    $sql_query = ...
    $results = $wpdb->get_results($sql_query, ARRAY_A );
    $datasets = [];
    foreach ($results as $row) {
        if (endsWith(get_site_url().''.$row['uri'], 'http://universitycompare.com/universities/the-uni-of-westminster/')) {
            $datasets[] = $row['count'];
        }
    }

    return do_shortcode('[wp_charts '.
        'title="linechart" canvaswidth="976px" canvasheight="244px" relativewidth="4" '.
        'width="976px" height="244px" type="line" align="alignright" '.
        'datasets="'. join(",",$datasets) . '"]');
}


text:
Q: How to save the state of button without using onSaveInstanceState I have a layout where I have a button. This button has 2 properties I'm interested in: text and color.
Now I know that if we mention android:configChanges="keyboardHidden|orientation|screenSize" in the manifest for this activity, we are telling that "we will handle it manually."
Now I don't want to add this in the manifest and let Android handle it automatically.
PROBLEM: Here when the user clicks on the button, I am changing the color as well as the text. Now when the screen orientation changes, the button color changes. How should I handle this?
For some reason and requirements, I don't want to use onSaveInstanceState. I have the same problem with a seek bar, also.
Is there a way to do this?


text:
Q: Export To Excel - Change Default "Save as type" to Microsoft Office Excel Workbook(*xls) I am Doing an Export to Excel with my Ruby on Ralis application.I have not used any gem or Plugin (since our requirement was something different, we couldn't use them). We used the inbuilt "format.xls" support that comes with Ruby on Rails.
The problem is that, when we get our Excel, Save as Type appears on the webpage. I want to change this to Microsoft Office Excel Workbook (*xls). How to do it?
Below is my controller action code  and the respective view with which we get the excel.
Get_excel methods in controller
def get_excel
    format.xls do
        headers['Content-Type'] = "application/vnd.ms-excel"
        headers["Content-disposition"] = 'inline;  filename="myexcel.xls"'
        headers['Cache-Control'] = ''
    end
end

VIEW (get_excel.xls.erb)

  <meta http-equiv=Content-Type content="text/html; charset=UTF-8"/>
  <meta name=ProgId content=Excel.Sheet/>
  <meta name=Generator content="Microsoft Excel 11"/>

some code

some code

some code

some code

some code

A: In config/initializers/mime_types.rb
Mime::Type.register "application/vnd.ms-excel", :xls

Then you shouldn't need to set headers directly in the method.
I'm not sure if this will stop you from being prompted, but it's how I serve HTML tables as xls and nobody ever has a problem opening them.
I also don't set a filename, as the method name will name it (get_excel.xls in your case).
I also don't set all the xml and xmlns stuff either. It just works.


text:
Q: Ruby Comparing Time objects considers date. How to avoid that? I have a model with a Time attribute
create_table "opened_intervals", force: :cascade do |t|
    t.time "start"
    t.time "end"

An example of a value would be:
>>  oi.start
=> Sat, 01 Jan 2000 06:26:00 UTC +00:00

(I am living in Germany)
If I use the current time, I get following value:
current_time = Time.now
>>  current_time
=> 2019-02-14 18:36:12 +0100

If I compare the class of both objects, I have
>>  current_time.class
=> Time
>>  oi.start.class
=> ActiveSupport::TimeWithZone

In order to make both instances same class, I change the Time class with the .zone method
>>  Time.zone.now
=> Thu, 14 Feb 2019 17:38:48 UTC +00:00
>>  Time.zone.now.class
=> ActiveSupport::TimeWithZone

Now both instances have same Class.
If I compare them, I get wrong results because of the date:
>>  oi.start
=> Sat, 01 Jan 2000 06:26:00 UTC +00:00
>>  current_time
=> Thu, 14 Feb 2019 17:40:13 UTC +00:00
>>  current_time < oi.end
=> false

I thought about creating a new Time with the hours, minutes and seconds, but then I have the same problem, Ruby always appends a Date.
Of course I could extract the hour, the minutes, the time, create an integer and compare them, but it feels too much.

*

*How can I deal with this issue the Ruby way?

*The Time object is always a time with a date? Is there no other way to achieve a Time just with the time?

*What would be the best approach for this problem?

I solved it this way:
def to_integer(time)
  hours = time.hour < 10 ? "0#{time.hour}" : time.hour
  minutes = time.min < 10 ? "0#{time.min}" : time.min
  seconds = time.sec < 10 ? "0#{time.sec}" : time.sec
  "#{hours}#{minutes}#{seconds}"
end

It feels too much (I could refactor it, but still too much)
to_integer(current_time) < to_integer(oi.end)

A: You can just modulus the days off to get the remaining time value.
t1 = Time.now
t2 = t2 = Time.at(Time.now.to_i - (5*24*3600))  # later time in day but previous date
tod1 = t.to_i % (24*3600)
=> 69734
tod2 = t2.to_i % (24*3600)
=> 69912

we can clearly see that t2 is a later time of day or clock time if you will and the modulus operation is very clear if you know anything about the unix epoch.


text:
Q: Display delivery status from UPS I am using the UPS courier service for the delivery of the packages. In my website I need to display the delivery status of a particular order using the tracking number, I used the following example,
https://github.com/chetan/php-ups-api
I added the access key, username and password in the config file. and I am using tracking.php file fro this library for testing purpose. But I get the following error,
Fatal error: require_once(): Failed opening required 'XML/Unserializer.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/project/php-ups-api-master/UpsAPI/Client.php on line 119

Can anyone please tell me where can I get this file.
I have also tried using
https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
\project\TrackingPACKAGE\TRACKINGWebServices\CodeSamples\Track\PHP\SoapTrackClient.php file
I have added,
 $wsdl = "../../../SCHEMAS-WSDLs/Track.wsdl";
as the parameter.
But get the following error,
SoapFault Object ( [message:protected] => An exception has been raised as a result of client data. [string:Exception:private] => [code:protected] => 0 [file:protected] => /home/project/TrackingPACKAGE/TRACKINGWebServices/CodeSamples/Track/PHP/SoapTrackClient.php [line:protected] => 62 [trace:Exception:private] => Array ( [0] => Array ( [file] => /home/project/TrackingPACKAGE/TRACKINGWebServices/CodeSamples/Track/PHP/SoapTrackClient.php [line] => 62 [function] => __soapCall [class] => SoapClient [type] => -> [args] => Array ( [0] => ProcessTrack [1] => Array ( [0] => ) ) ) ) [previous:Exception:private] => [faultstring] => An exception has been raised as a result of client data. [faultcode] => Client [faultcodens] => http://schemas.xmlsoap.org/soap/envelope/ [detail] => stdClass Object ( [Errors] => stdClass Object ( [ErrorDetail] => stdClass Object ( [Severity] => Authentication [PrimaryErrorCode] => stdClass Object ( [Code] => 250002 [Description] => Invalid Authentication Information. ) ) ) ) [xdebug_message] => ( ! ) SoapFault: An exception has been raised as a result of client data. in /home/project/TrackingPACKAGE/TRACKINGWebServices/CodeSamples/Track/PHP/SoapTrackClient.php on line 62 Call Stack #TimeMemoryFunctionLocation 10.0006132036{main}( )../SoapTrackClient.php:0 20.0079240060SoapClient->__soapCall( )../SoapTrackClient.php:62 )
Please help me.

A: Error message tell that you need install PEAR Serializer package: https://pear.php.net/package/XML_Serializer/


text:
Q: How to get started with ExoPlayer My requirement is very simple. I've a database in www.xyz.example.com. Using web service I pull the detail of a song/songs. I store them in an Arraylist.
The arraylist contains the url of the song. When user press play button, the url is passed to a service and song starts playing. I've successfully implemented android's default MediaPlayer. But I noticed that it takes too long to prepare. Then I found that Exoplayer is there to replace MediaPlayer. Now I notice that ExoPlayer is not as simple as Mediaplayer. It has so many classes, implementation etc. etc..
I added the latest player in my project using gradle
compile 'com.google.android.exoplayer:exoplayer:r2.0.0'

Now what should I do? How to actually intialize the Exoplayer? According to developer guide
// 1. Create a default TrackSelector
Handler mainHandler = new Handler();
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
    new AdaptiveVideoTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector =
    new DefaultTrackSelector(mainHandler, videoTrackSelectionFactory);

I cannot get anything here. What is a BandwidthMeter here? What is TrackSelection here ? What is TrackSelector here ?
Again...
// 2. Create a default LoadControl
LoadControl loadControl = new DefaultLoadControl();

// 3. Create the player
SimpleExoPlayer player =
    ExoPlayerFactory.newSimpleInstance(context, trackSelector, loadControl);

Here these are some another confusions. What is the difference between Exoplayer and SimpleExoPlayer ?
Moreover, I see that most of the projects using ExoPlayer in Github are about playing video over http. How can I achieve my above stated goal? (Please do not advice me to read the demo app. It is not simple.) Can anyone guide me to create a audio player.


text:
Q: WooCommerce - Flat rate shipping based on X quantity steps? We need to run WooCommerce flat rate shipping rate based on every X items in the cart, for example:

*

*1-5 Items: Delivery = £5

*6-10 Items: Delivery = £10

*11-15 Items: Delivery = £15

*and so on…
It's essentially £1 per item, but it's in brackets of £5, so 3 items would be £5, and 7 items would be £10, for example.
I'm hoping this is achievable with the out of the box shipping rates, or alternatively, I'd be relatively comfortable writing a theme function, if required - but the client has a limited budget on this.
I've tried looking for more reference on the available shortcodes that I can use in the advanced shipping options, but can't seem to find a way to achieve the above.

A: For that, you need to use a hooked function in woocommerce_package_rates filter hook, targeting "Flat rate" shipping method.
In shipping settings for flat rate shipping method you will set a cost of 5.
Each 5 items step, the shipping cost will be increased by 5:
• From 1 to 5 Items: Delivery = 5
• From 6 to 10 Items: Delivery = 10
• From 11 to 15 Items: Delivery = 15
• And so on…
Here is the code:
add_filter( 'woocommerce_package_rates', 'different_rates_based_on_quantity_steps', 10, 2 );
function different_rates_based_on_quantity_steps( $rates, $package ){

    $items_count  = WC()->cart->get_cart_contents_count(); // Cart item count
    $items_change = 5; // number of items needed to increase the cost each time
    $rate_operand = ceil( $items_count / $items_change ); // Operand increase each 5 items here

    foreach ( $rates as $rate_key => $rate ){
        // Targetting "Flat rate"
        if( 'flat_rate' === $rate->method_id ) {
            $has_taxes = false;

            // Set the new cost
            $rates[$rate_key]->cost = $rate->cost * $rate_operand;

            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_key]->taxes as $key => $tax){
                if( $tax > 0 ){
                    // New tax calculated cost
                    $taxes[$key] = $tax * $rate_operand;
                    $has_taxes = true;
                }
            }
            // Set new taxes cost
            if( $has_taxes )
                $rates[$rate_key]->taxes = $taxes;
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or active theme). tested and works.

Refresh the shipping caches: (required)

*

*This code is already saved on your active theme's function.php file.

*The cart is empty

*In a shipping zone settings, disable / save any shipping method, then enable back / save.

A: Still can't comment so I need to post this fix to the above awesome answer.
For the rate calc to work properly, the return $rates; line must be outside the cart loop.
The complete function should be:
$step_change = 5; // Steps for item
$item_count = 0;

// Checking in cart items
foreach( WC()->cart->get_cart() as $cart_item ){

// If we find the shipping class
if( $cart_item['data']->get_shipping_class() == $slug_class_shipping ){

$item_count += $cart_item['quantity']; // Cart item count
$rate_operand = ceil( $item_count / $step_change ); // Operand increase each # items here

foreach ( $rates as $rate_key => $rate ){
    // Targetting "Flat rate"
    if( 'flat_rate' === $rate->method_id ) {
        $has_taxes = false;

        // Set the new cost
        $rates[$rate_key]->cost = $rate->cost * $rate_operand;

        // Taxes rate cost (if enabled)
        foreach ($rates[$rate_key]->taxes as $key => $tax){
            if( $tax > 0 ){
                // New tax calculated cost
                $taxes[$key] = $tax * $rate_operand;
                $has_taxes = true;
            }
        }
        // Set new taxes cost
        if( $has_taxes )
            $rates[$rate_key]->taxes = $taxes;
     }
   }
 }
  return $rates;
}

A: To add a specific class you must check each item in the cart, and check with the slug of the class which items correspond, in this way:
First add the woocommerce_package_rates filter
add_filter( 'woocommerce_package_rates', 'different_rates_based_on_quantity_steps', 10, 2 );

Then insert the function
function different_rates_based_on_quantity_steps ( $rates, $package ){

$slug_class_shipping = 'books'; // Slug of the shipping class
$step_change = 5; // Steps for item
$item_count = 0;

// Checking in cart items
foreach( WC()->cart->get_cart() as $cart_item ){

// If we find the shipping class
if( $cart_item['data']->get_shipping_class() == $slug_class_shipping ){

$item_count += $cart_item['quantity']; // Cart item count
$rate_operand = ceil( $item_count / $step_change ); // Operand increase each # items here

foreach ( $rates as $rate_key => $rate ){
    // Targetting "Flat rate"
    if( 'flat_rate' === $rate->method_id ) {
        $has_taxes = false;

        // Set the new cost
        $rates[$rate_key]->cost = $rate->cost * $rate_operand;

        // Taxes rate cost (if enabled)
        foreach ($rates[$rate_key]->taxes as $key => $tax){
            if( $tax > 0 ){
                // New tax calculated cost
                $taxes[$key] = $tax * $rate_operand;
                $has_taxes = true;
            }
        }
        // Set new taxes cost
        if( $has_taxes )
            $rates[$rate_key]->taxes = $taxes;
    }
}    return $rates;
} break; } }


text:
Q: Traefik with self-signed backend I have the traefik setup to proxy the kibana backend with self signed certs. Whenever I access the backend, I am getting "Internal error" in the browser and I see the following error message in kibana logs.

{"type":"log","@timestamp":"2018-02-04T03:56:26Z","tags":["connection","client","error"],"pid":1,"level":"error","message":"139782929405760:error:14094412:SSL
  routines:ssl3_read_bytes:sslv3 alert bad
  certificate:../deps/openssl/openssl/ssl/s3_pkt.c:1493:SSL alert number
  42\n139782929405760:error:140940E5:SSL routines:ssl3_read_bytes:ssl
  handshake
  failure:../deps/openssl/openssl/ssl/s3_pkt.c:1216:\n","error":{"message":"139782929405760:error:14094412:SSL routines:ssl3_read_bytes:sslv3 alert bad
  certificate:../deps/openssl/openssl/ssl/s3_pkt.c:1493:SSL alert number
  42\n139782929405760:error:140940E5:SSL routines:ssl3_read_bytes:ssl
  handshake
  failure:../deps/openssl/openssl/ssl/s3_pkt.c:1216:\n","name":"Error","stack":"Error:
  139782929405760:error:14094412:SSL routines:ssl3_read_bytes:sslv3
  alert bad certificate:../deps/openssl/openssl/ssl/s3_pkt.c:1493:SSL
  alert number 42\n139782929405760:error:140940E5:SSL
  routines:ssl3_read_bytes:ssl handshake
  failure:../deps/openssl/openssl/ssl/s3_pkt.c:1216:\n\n    at Error
  (native)"}}

Here is my docker-compose file:
 ---
 version: '3.0'
 services:
  traefik:
    image: traefik:1.5-alpine
    command: --web --accesslog --docker --docker.watch --docker.domain=localhost --logLevel=ERROR --entryPoints="Name:http Address::80"
    ports:
      - "80:80"
      - "8080"
    labels:
      - "traefik.frontend.rule=Host:monitor.localhost"
      - "traefik.port=8080"
      - "traefik.frontend.entryPoints=http"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /dev/null:/traefik.toml
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch-platinum:6.1.3
    container_name: elasticsearch
    ports:
      - "9200"
    labels:
      - "traefik.frontend.rule=Host:es.localhost"
      - "traefik.frontend.entryPoints=http"
    environment:
      - cluster.name=docker-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms1024m -Xmx1024m"
      - ELASTIC_PASSWORD=changeme
    cap_add:
      - IPC_LOCK
    ulimits:
      memlock:
        soft: -1
        hard: -1
      nofile:
        soft: 65536
        hard: 65536
  kibana:
    image: docker.elastic.co/kibana/kibana:6.1.3
    container_name: kibana
    ports:
      - "5601"
    labels:
      - "traefik.frontend.rule=Host:kb.localhost"
      - "traefik.frontend.entryPoints=http"
      - "traefik.protocol=https"
    links:
      - elasticsearch
    environment:
      - SERVER_SSL_ENABLED="true"
      - SERVER_SSL_CERT=/usr/share/kibana/config/kibana.example.org.crt
      - SERVER_SSL_KEY=/usr/share/kibana/config/kibana.example.org.key
    depends_on:
      - elasticsearch

How can I make traefik to work with self-signed certs? Am I missing anything in the setup?

A: I've been dealing with this sort of issue myself. Traefik does not currently support per-backend configuration of TLS parameters, unless it's for client authentication pass-through. The only customization currently offered for reverse-proxy routing in a back-end is with the global insecureSkipVerify boolean setting (See the short blurb for this in Traefik's Commons documentation).
I haven't verified this, but I believe --insecureSkipVerify=true would be the correct flag to pass in your command stanza for Traefik to enable this functionality.
Please note that this will affect all backend connections, and can open you up to man-in-the-middle attacks. Issue #3038 on Traefik's GitHub repository tracks a design idea that would make this configurable per back-end. Feel free to upvote or issue a PR for this feature.


text:
Q: how can i getCurrent location and display also city name i am new in android create current location and display its city name
i Have No idea About code so give some example to create current location and display also city name thnks in advance

A: public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
{
   LocationClient mLocationClient;
private TextView addressLabel;
private TextView locationLabel;
private Button getLocationBtn;
private Button disconnectBtn;
private Button connectBtn;

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

  locationLabel = (TextView) findViewById(R.id.locationLabel);
  addressLabel = (TextView) findViewById(R.id.addressLabel);
  getLocationBtn = (Button) findViewById(R.id.getLocation);

  getLocationBtn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
        displayCurrentLocation();
     }
  });
  disconnectBtn = (Button) findViewById(R.id.disconnect);
  disconnectBtn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
        mLocationClient.disconnect();
        locationLabel.setText("Got disconnected....");
     }
  });
  connectBtn = (Button) findViewById(R.id.connect);
  connectBtn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
        mLocationClient.connect();
        locationLabel.setText("Got connected....");
     }
  });
  // Create the LocationRequest object
   mLocationClient = new LocationClient(this, this, this);
 }
 @Override
 protected void onStart() {
  super.onStart();
  // Connect the client.
  mLocationClient.connect();
  locationLabel.setText("Got connected....");
}
@Override
protected void onStop() {
  // Disconnect the client.
  mLocationClient.disconnect();
  super.onStop();
  locationLabel.setText("Got disconnected....");
  }
  @Override
  public void onConnected(Bundle dataBundle) {
  // Display the connection status
  Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
  // Display the connection status
  Toast.makeText(this, "Disconnected. Please re-connect.",
  Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
  // Display the error code on failure
  Toast.makeText(this, "Connection Failure : " +
  connectionResult.getErrorCode(),
  Toast.LENGTH_SHORT).show();
}
public void displayCurrentLocation() {
  // Get the current location's latitude & longitude
  Location currentLocation = mLocationClient.getLastLocation();
  String msg = "Current Location: " +
  Double.toString(currentLocation.getLatitude()) + "," +
  Double.toString(currentLocation.getLongitude());

  // Display the current location in the UI
  locationLabel.setText(msg);

  // To display the current address in the UI
  (new GetAddressTask(this)).execute(currentLocation);
 }
/*
 * Following is a subclass of AsyncTask which has been used to get
 * address corresponding to the given latitude & longitude.
 */
 private class GetAddressTask extends AsyncTask<Location, Void, String>{
  Context mContext;
  public GetAddressTask(Context context) {
     super();
     mContext = context;
  }

  /*
   * When the task finishes, onPostExecute() displays the address.
   */
  @Override
  protected void onPostExecute(String address) {
     // Display the current address in the UI
     addressLabel.setText(address);
  }
  @Override
  protected String doInBackground(Location... params) {
     Geocoder geocoder =
     new Geocoder(mContext, Locale.getDefault());
     // Get the current location from the input parameter list
     Location loc = params[0];
     // Create a list to contain the result address
     List<Address> addresses = null;
     try {
        addresses = geocoder.getFromLocation(loc.getLatitude(),
        loc.getLongitude(), 1);
     } catch (IOException e1) {
        Log.e("LocationSampleActivity",
        "IO Exception in getFromLocation()");
        e1.printStackTrace();
        return ("IO Exception trying to get address");
     } catch (IllegalArgumentException e2) {
        // Error message to post in the log
        String errorString = "Illegal arguments " +
        Double.toString(loc.getLatitude()) +
        " , " +
        Double.toString(loc.getLongitude()) +
        " passed to address service";
        Log.e("LocationSampleActivity", errorString);
        e2.printStackTrace();
        return errorString;
     }
     // If the reverse geocode returned an address
     if (addresses != null && addresses.size() > 0) {
        // Get the first address
        Address address = addresses.get(0);
        /*
        * Format the first line of address (if available),
        * city, and country name.
        */
        String addressText = String.format(
        "%s, %s, %s",
        // If there's a street address, add it
        address.getMaxAddressLineIndex() > 0 ?
        address.getAddressLine(0) : "",
        // Locality is usually a city
        address.getLocality(),
        // The country of the address
        address.getCountryName());
        // Return the text
        return addressText;
     } else {
        return "No address found";
     }
  }
}// AsyncTask class
}

Refrence link http://www.tutorialspoint.com/android/android_location_based_services.htm


text:
Q: findall specification pageable is taking time for 10 data java spring boot jpa Hi I have a table HrCrEmp where i have 132 columns and have several relationship with other tables. I am using a pagination
if(sortField == null || sortField.equals("") || sortField.equals("id") ) sortField = "id";
Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).descending() : Sort.by(sortField).ascending();

Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);

Page<HrCrEmp> hrCrEmp = this.hrCrEmpRepository.findAll((Specification<HrCrEmp>) (root, cq, cb) -> {
    //rest of the code;
}

But unfortunately this pagination is taking about 40 to 50 seconds to return 10 values; Can anyone please help what might be the issue and how can i sort out this issue in java spring boot.
I have searched for solutions in the net but haven't found any . This is beyond my knowledge.

A: Normally you would use the findList method. findAll is a full table query, and I don't know which class your hrCrEmpRepository is extends from


text:
Q: Initialization order of static inline member variables in class templates (C++17) I am working on a code where I need a static member variable of some class to be initialized using a static variable of an instance of a class template. I know about the static initialization order fiasco and found several discussions on that issue but none of them really helped me with my problem. I don't even know why that should be a problem in my case.
This is a minimal example that reproduces the error I get from my code:
#include <string>
#include <map>

template<class T>
class Foo {

private:

    static inline std::map<std::string, T> map_ = {};

public:

    static bool insert(const std::string& key, T value) {

        map_[key] = value;
        return true;
    }
};

using MyFoo = Foo<char>;

class Bar {
    static inline bool baz_ = MyFoo::insert("baz", 'A');
};

int main() {
    // This works just fine if the definition of Bar::baz_ in line 24 is removed
    //MyFoo::insert("baz", 'A');
    return 0;
}

Compilation using the C++17 standard finishes with 0 warnings and 0 errors. When the program is executed, however, a segmentation fault occurs when Foo::insert is called. It appears that Foo::map_ is not initialized at that point. But shouldn't the static variables be initialized in the same order as they are defined in the code?
I should also mention that the code without the template works fine. So I am wondering if the compiler instantiates the template in a way that the the actual class is defined after Bar. Could something like that be the problem or does the compiler just happen to do the 'right' thing in that case?

A: Dynamic initialization of static data members of class template specializations (if they are not explicitly specialized) are completely unordered (indeterminately-sequenced) with any other dynamic initialization. It doesn't matter whether the member is inline or not, it doesn't matter whether the other dynamic initialization is also of a static data member of a class template specialization or not, and it also doesn't matter where the points of instantiation and definition of the static data member are located in the translation unit.
Therefore there is no way to guarantee that Foo<char>::map_ is initialized before Bar::baz_.
Instead use the common idiom of using a static member function containing the static member as a local static variable instead:
static auto& map_() {
    static std::map<std::string, T> map = {};
    return map;
}

// replace `map_` with `map_()` everywhere else


text:
Q: Which of two sentences mean the same as the first one? "You don't get everything you want."
Do both the following sentences mean the same as the one above? Are they interchangeable?
1.Not everything you want, do you get.
2.Not everything you want, you get.
What's the difference in meaning between the two sentences?

A: All sentences hold the same meaning, and differ mainly in their execution. The reference sentence, "You don't get everything you want," is best in terms of fluency/native use of the phrase, while (1) and (2) appear to lean towards what one would call a proverb (e.g. fancy advice).
For instance, if we add the contrapositive phrase to (1) or (2), we get this:
"Not everything you want, [do] you get, and not everything you get, [do] you want." In essence, a piece of advice heading listeners to have reasonable expectations about their wants and procuring them.
Use of "do" or not in this case is a bit more... aesthetic? I would argue that inclusion of "do" make be closer to a full sentence, but removing it (like in (2)), creates a more concise and crisp proverb-like sentence structure when compounded with its contrapositive counterpart.
All in all, the reference sentence is best for fluidity and terseness, while use of (2) in tandem with its reverse is best for doling out some advice (perhaps a bit Yoda-like, as HammerN'Songs noted).
Hope this helps, and let me know if further clarification would be useful!


text:
Q: Node.js / Grunt export log to file Is there any way of exporting the console log of your Grunt build to a *.txt file?
I can run grunt in console with the >> thingy to export to file, like so:
grunt >> log.txt

But it does not log to console, only to file.
And I'd like a module/task to do it for me after the build has finished.

A: This is not actually grunt or node.js question. You need to use piping to tee.
grunt | tee log.txt

Or if you're using windows cmd:
grunt > log.txt | type log.txt


text:
Q: Why am I getting "Cannot read property of html undefined"? I am building a simple counter to practice closures in JS, and I can't seem to get past this error. In my mind setting the variable elem to the id of canv should work, but something is obviously not connecting. What am I doing wrong here?
My HTML:

My JS:
function setup(delay) {
  var el = document.getElementById('canv');

  counterFn(el, delay);
}

function counterFn(el, delay) {
  var counter = 0;

  setInterval(getTime, delay);

  function getTime(el) {
    el.innerHTML(counter);
    counter++;
  }
}

setup(500);

This all feels very elementary but I can't seem to figure out what I am doing wrong.
Here's a JS fiddle.
https://jsfiddle.net/8sjaqdrh/2/

A: The thing that caused the error is because el is not defined within the scope of getTime.
In getTime's parent scope counterFn, el is defined because you gave it a value when calling it in counterFn(el, delay) inside setup function, which is el = document.getElementById('canv').
However in the scope of getTime, you did not provide el with a value. So el becomes undefined.
Another problem with the code is the incorrect usage of innerHTML.
Just removing the parameter from function getTime(el){... to function getTime(){... will do.
As for innerHTML, it is not a function. So it can't be called like innerHTML(counter).
The correct way is to directly assign a value to it like innerHTML = counter.

function setup(delay) {
  var el = document.getElementById('canv');

  counterFn(el, delay);
}

function counterFn(el, delay) {
  var counter = 0;

  setInterval(getTime, delay);

  // Corrected code:
  function getTime() {
    el.innerHTML = counter;
    counter++;
  }

  /* Your code
  function getTime(el){
    el.innerHTML(counter);
    counter++;
  }
  */
}

setup(500);

A: One potential issue here is that your trying to get the canvas before it exist in the DOM, you will want to wrap your code in a window.onload event to prevent that from happening.
Next for the code bellow here:
setInterval(getTime, delay);

You define getTime as expecting a parameter but did not pass one, instead you will want do to:
setInterval(function(){ getTime(el); }, wait);

Finally el.innerHTML(counter); should be el.innerHTML = counter;.
Working Fiddle here


text:
Q: SSRS- Fit PDF Export To One Page I am new to SSRS. I have created a report.
My report has four others reports in it. And I have set the page break. Page break works before displaying the new report.
So this way I get all four reports in separate tabs in excel. But now I want my report in PDF too. But after exporting to PDF, I get a blank page after each report.
Can I set the page break only for EXCEL and ignore if I export to PDF. Second my page doesn't fir while printing. In PDF it looks good. It is on single page. But when I try to print it shows half of the page.

A: I cannot check now but look at Globals!RenderFormat (I think it's called that).
If you can set the page break on an expression then you can use this property to determine if you need the break of not.
Something like
=IIF(Globals.RenderFormat.Name = "PDF", False, True)

If this does not work, add a thin rectangle between each report, set the page breaks on that instead by setting the rectangle's page break properties. and then set the hidden property to the expression above. You will have to remove the existing page breaks.

A: It will happen sometimes. Try to change margins in Report Properties.
Body content size should not exceed Report page size.
Body content size + margin size <= report width
For Eg.
Body content size = 6 inch

Margin right = 1 inch

Margin Left 1 inch

Report width=8.5 inch

So, 6+1+1<=8.5 then report will render properly. Otherwise new empty page will come. Check below screen shot of report properties.

Overall PDF report size should match with printer page setup. Then it will print properly.


text:
Q: No converter found for return value of type: class org.json.JSONArray I want to return a JSONArray(org.json.jar) object from spring controller method, this is my java spring controller :
import org.json.JSONArray;
import org.json.JSONException;

@RestController
public class BICOntroller{

@RequestMapping(value="/getStatus", method = RequestMethod.GET)
    public ResponseEntity<JSONArray> getStatus() throws JSONException{
      ResponseEntity<JSONArray> response = null;
      JSONArray arr = new JSONArray();

      JSONObject obj = new JSONObject();
      //process data
      arr.put(obj);

      response = new ResponseEntity<JSONArray>(arr, HttpStatus.OK);
      return response;
  }

}

Angular js call :
            $http({
                url: 'getStatus',
                method: 'GET',
                responseType: 'json'
            }).then(function(response){
                console.log(response);
                return response;
            }, function(error){
                console.log(error);
                return error;
            });

This gives 500 error :
java.lang.IllegalArgumentException: No converter found for return value of type: class org.json.JSONArray

I have included jackson-core-2.7.5.jar and jackson-databind-2.7.5.jar in the class path.
Thanks!

A: Adding the dependencies did not work for me. What did work is converting the JSONArray to String.
FYI I am using Spring Boot Application and was trying to return a JSONArray.

A: Apart from adding dependencies, you may need this.
If you are not using spring boot, update your spring xxx-servlet.xml with message converters for JSON.
<mvc:annotation-driven>
     <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
   </mvc:message-converters>
</mvc:annotation-driven>

if you are using spring boot, adding dependencies in pom.xml alone will suffice.
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>


text:
Q: Check a string for 1 to infinite repetitions of asterisk (*) using JavaScript regex object I am completely crap in regex and I need a little help with a task. How do I check a string for a single character repetition (in my case *) using javasctipt regex object.
Specifically I need to check a string for 1 to n repetitions of * character. If the above case is true return true.

A: This is fairly trivial I am afraid:
/\*+/.test("*");           // true
/\*+/.test("hello world"); // false

A: If you want to know how many & they can be seperated, you can count the number of * in a string (using regex) with
"_*_*_*_*_".match(/\*/g).length; // 4

then compare against n


text:
Q: How to change the value of a variable using input field? I have created a wordpress website. I want to extract each user's data using php through his/her id.
I have created this code;
<?php
$userid = /* help me get the below input field's value */
$user_info = get_userdata($userId);
      echo 'Username: ' . $user_info->user_login . "\n";
      echo 'User roles: ' . implode(', ', $user_info->roles) . "\n";
      echo 'User ID: ' . $user_info->ID . "\n";
    ?>
<input name="getUser" id="getUser" value=''/>

The user will write the id of the user he wants to extract his data. and then the data will echo back.
The code is working fine but i can't set the value of "getUser" input field to "$userId" variable. Also i want that php to re-execute on input field value change.

A: Please try below snippet of code.
HTML :
<input name="getUser" id="getUser" value=''/>

JS (js/my-ajax-script.js)
 jQuery(document).ready(function($){
    $('#getUser').keyup(function(e) {
      var user_id = e.target.value;
      console.log(user_id);
      $.ajax({
            url:my_ajax_object.ajaxurl, #add here your ajax url
            type:'POST',
             data:'action=get_this_user_data&user_id='+user_id ,
             success:function(results)
             {
              jQuery('#user_data').html(results);

             }
        });
    });
});

Ajax (add in functions.php)
function my_enqueue() {

wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

wp_localize_script( 'ajax-script', 'my_ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
   }
   add_action( 'wp_enqueue_scripts', 'my_enqueue' );

add_action( 'wp_ajax_get_this_user_data', 'get_this_user_data' );
add_filter( 'wp_ajax_nopriv_get_this_user_data', 'get_this_user_data');
function get_this_user_data()
{
    $userid = $_POST["user_id"];
    $data = '';
    $user_info = get_userdata($userid);
     if(!empty($user_info))
     {
       $data .= '
';
       $data .= 'Username: ' . $user_info->user_login . '
';
       $data .= 'User roles: ' . implode(', ', $user_info->roles) . '
';
       $data .= 'User ID: ' . $user_info->ID . '
';
       $data .='
';
     }
     else
     {
        $data = "user data not found";
     }

      echo $data;
      die();
}

Hope this helps you!


text:
Q: TypeError: Type str doesn't support the buffer API # find method? Here is my input:
<!DOCTYPE html>
..........

    Jim Cramer
    <s>@</s>jimcramer

    26 Nov

Love this spirited & rigorous <s>$</s>TSLA defense ! RT <s>@</s>InfennonLabs: Why are these idiots selling <s>#</s>tsla are they that blind? <s>@</s>jimcramer

        Favorited 5 times

...........

For instance this "input" is in my input variable.
Here is my code:
  start_link = input.find(' <p class="js-tweet-text tweet-text" ')

if i run it, i'll get the following error:
  start_link = input.find('<p class="js-tweet-text tweet-text" ')
TypeError: Type str doesn't support the buffer API

How can I fix this?
NOTE: type of my input variable is: class 'bytes'

A: You can also make the data coming from your input a str object, like this:
url = "http://www.google.com"
req = request.Request(url)
response = request.urlopen(req)
page = str(response.read()) # make it a str object
print(page[page.find('id='):]) # now you don't need a b in front of your string

A: You can't use bytes.find() to find a str object inside a bytes object(since they're different types, a str can't be inside bytes).
You can, however, look for a bytes object inside it. This should work:
start_link = input.find(b' <p class="js-tweet-text tweet-text" ')

Btw, you should be using an html parser if you're parsing html.


text:
Q: Change Xcode Playground Font for comments/description How can I change the font of "Topline" below to a e.g. smaller font, colored what ever in a Playground Page?
import Foundation
//: # Topline
var greeting = "Hello, playground"

//: [Next](@next)

The above code in a playground page will be rendered as


text:
Q: Как применить стили к коментариям? В текстовом файле как мне применить стили к комментариям? то есть например автоматические рамки и т.д
<?php
$filename = 'templates/comments.txt';
$handle = fopen($filename, "rb");

$contents = fread($handle, filesize($filename));
fclose($handle);
echo $contents;
?>

Как применить css в этот код? он выводит комментарии на сайт из текстового файла. Мне нужно что бы они автоматически появлялись со стилями

A: echo '
'.$contents.'
';


text:
Q: Problem of finding shortest proof - how complex is it? For first order theories, is it correct that there is a brute force algorithm that tells us the shortest proof length for any given theorem ('length' means the sum of the lengths of the formulas that appear as lines in the proof)?
Are there algorithms better than brute force? What is the complexity class for the problem?

A: There are two reasonable ways to measure the length of a proof: by steps or by symbols. For step-length, we can brute-force-search for proofs and be certain we've found the shortest one as long as our axiom system is finite - for symbol-length, we only need that the language is finite and our axiom system is computably axiomatized (e.g. $\mathsf{PA}$ and $\mathsf{ZFC}$).
That said, in either case we have a serious issue as far as complexity is concerned: as long as our axiom system is "sufficiently rich," for every computable function $F$ there is some theorem $\varphi$ which has no proof of length $\le F(length(\varphi))$. (Basically, we're looking at the Busy Beaver function in disguise when we talk about bounding proof searches ahead of time.)
That said, this doesn't rule out $(i)$ efficient proof search in simpler theories or $(ii)$ efficient proof search for particularly simple results. There's a rich literature on this topic, beginning with the already-interesting case of propositional proof search - "automated theorem proving" is a good keyword for this.


text:
Q: How to get the current profile name in an aura cmp? I need to get the Profile name in my Aura component. I am converting my JS button to a Lightning Quick Action, so I need something like this in my component:
"{!$Profile.Name}"

A: The global value providers you are used to using in Visualforce are not available in lightning. The Lightning Aura Components developer guide further expands on this and the supported global value providers.
So, you will have to get that info from the server in Apex using a callout from your quickactions component controller.

A: It's not necessary to make an Apex call for this. You can retrieve the profile of the current user with a force:recordData component and an associated aura:attribute component, like so:
<aura:attribute name="CurrentUser" type="Object"/>
<force:recordData recordId="{!$SObjectType.CurrentUser.Id}"
                  fields="Profile.Name"
                  targetFields="{!v.CurrentUser}"/>

Then you can access that data in your component controller like so:
{!v.CurrentUser.Profile.Name}

And in your component controller like so:
const username = component.get('v.CurrentUser')['Profile'].Name;

A: You can't use $Profile in lightning. For that, you need to write some apex code. Please refer below link for more details
https://andrescanavesi.wordpress.com/2018/09/09/migrate-user-profile-label-and-api-to-lightning-components/


text:
Q: How can I handle custom NULL string with Spark DataFrame I have a data file look like below:
// data.txt
1    2016-01-01
2    \N
3    2016-03-01

I used \N to represent a null value for some reason. (It's not a special character, it's a string consists of 2 chars: \ and N).
I want to create DataFrame like below:
case class Data(
    val id   : Int,
    val date : java.time.LocalDate)

val df = sc.textFile("data.txt")
           .map(_.split("\t"))
           .map(p => Data(
               p(0).toInt,
               _helper(p(1))
           ))
           .toDF()

My question is how can I write the helper method ?
def _helper(s : String) = s match {
    case "\\N" => null,                // type error
    case _     => LocalDate.parse(s, dateFormat)
}

A: This is where an Option type will come in handy.
I changed the custom null value to make the case more explicit but it should work in your case. My data is in a .txt file like so:
Ryan,11
Bob,22
Kevin,23
Asop,-nnn-

Notice the -nnn- is my custom null. I use a slightly different case class:
case class DataSet(name: String, age: Option[Int])

And write a pattern matching function to capture the nuances of the situation:
      def customNull (col: String): Option[Int] = col match {
           case "-nnn-" => None
           case _ => Some(Integer.parseInt(col))
      }

From here it should work as expected when you combine the two:
  val df = sc.textFile("./data.txt")
.map(_.split(","))
.map(p=>DataSet(p(0), customNull(p(1))))
.toDF()

When I do a df.show() I get the following:
+-----+----+
| name| age|
+-----+----+
| Ryan|  11|
|  Bob|  22|
|Kevin|  23|
| Asop|null|
+-----+----+

Treating the ages like a string gets around the problem. It might not be the fastest to parse values like this. Ideally, you could also use an Either but that can also get complex.


text:
Q: Why excel rounded but still shows more than 2 decimal points I have a set of numbers that was rounded of to 2. When I sum a range, i ended on a cell which shows 762,078.31. I copied this cell and paste value and it actually shows 762078.31. I increased decimal and it still shows 762078.3100. But on the 'formula bar' it shows as 762078.309999999.
I would like to show the calculations here but there ~359 rows. It's simple formula used as follows;  =ROUND(Q2*S2,2) and =SUM(Y2:Y359).
Anyone with an idea why this happens, do let me know.
Thanks.

A: Not sure why it's happening, but you can edit the SUM cell to round as well:
 =ROUND(SUM(Y2:Y359),2)

A: It could just be a rounding error in Excel. The article below gives an example where if you subtract 22.26 - 21.29 you get 0.970000000000002.
http://journalofaccountancy.com/issues/2014/mar/excel-calculation-errors.html
There are many examples where you will see Excel's precision slightly off, but as noted in the article, users find them to be insignificant.


text:
Q: Unity 2D, character will not move So i have followed this guide https://learn.unity.com/tutorial/live-session-2d-platformer-character-controller#5c7f8528edbc2a002053b695
And i've basically followed everything step by step.
Here is the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PhysicsObject : MonoBehaviour
{
    public float minGroundNormalY = .65f;
    public float gravityModifier = 1f;
    protected Vector2 targetVelocity;
    protected bool grounded;
    protected Vector2 groundNormal;

    protected Rigidbody2D rb2d;
    protected Vector2 velocity;
    protected ContactFilter2D contactFilter;
    protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
    protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16);

    protected const float minMoveDistance = 0.001f;
    protected const float shellRadius = 0.01f;

    void OnEnable()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Start is called before the first frame update
    void Start()
    {
        contactFilter.useTriggers = false;
        contactFilter.SetLayerMask(Physics2D.GetLayerCollisionMask (gameObject.layer));
        contactFilter.useLayerMask = true;
    }

    // Update is called once per frame
    void Update()
    {
        targetVelocity = Vector2.zero;
        ComputeVelocity();
    }

    protected virtual void ComputeVelocity()
    {
    }

    void FixedUpdate()
    {
        velocity += gravityModifier * Physics2D.gravity * Time.deltaTime;
        velocity.x = targetVelocity.x;

        grounded = false;

        Vector2 deltaPosition = velocity * Time.deltaTime;
        Vector2 moveAlongGround = new Vector2(groundNormal.y, -groundNormal.x);
        Vector2 move = moveAlongGround * deltaPosition.x;
        Movement(move, false);

        move = Vector2.up * deltaPosition.y;
        Movement(move, true);
    }

    void Movement(Vector2 move, bool yMovement)
    {
        float distance = move.magnitude;
        if (distance > minMoveDistance)
        {
           int count =  rb2d.Cast(move, contactFilter, hitBuffer, distance + shellRadius);
            hitBufferList.Clear();
            for (int i = 0; i < count; i++)
            {
                hitBufferList.Add(hitBuffer[i]);
            }

            for (int i = 0; i < hitBufferList.Count; i++)
            {
                Vector2 currentNormal = hitBufferList[i].normal;
                if (currentNormal.y < minGroundNormalY)
                {
                    grounded = true;
                    if (yMovement)
                    {
                        groundNormal = currentNormal;
                        currentNormal.x = 0;
                    }
                }
                float projection = Vector2.Dot(velocity, currentNormal);

                if (projection < 0)
                {
                    velocity = velocity - projection * currentNormal;
                }
                float modifiedDistance = hitBufferList[i].distance - shellRadius;
                distance = modifiedDistance < distance ? modifiedDistance : distance;
            }
        }
        rb2d.position = rb2d.position + move.normalized * distance;
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerPlatformerController : PhysicsObject
{
    public float jumpTakeOffSpeed = 7;
    public float maxSpeed = 7;

    // Start is called before the first frame update
    void Start()
    {
    }

    protected override void ComputeVelocity()
    {
        Vector2 move = Vector2.zero;
        move.x = Input.GetAxis("Horizontal");

        if (Input.GetButtonDown("Jump") && grounded)
        {
            velocity.y = jumpTakeOffSpeed;
        }
        else if (Input.GetButtonUp("Jump"))
        {
            if (velocity.y > 0)
            {
                velocity.y = velocity.y * 0.5f;
            }
        }
        targetVelocity = move * maxSpeed;
    }
}

If you check that link it will probably have some animations added to it, i have not gotten that far yet.
So atm my char just stands completly still and does not move. Below is the picture.

A: When inheriting from Unity objects (MonoBehaviours in general), if you create a new Unity lifecycle function (Start, Awake, Update, etc), it will ignore the inheriting class' implementation.
In this case, PlayerPlatformerController is implementing an empty Start, which means Start won't be called on PhysicsObject.
This means this code will not run:
contactFilter.useTriggers = false;
contactFilter.SetLayerMask(Physics2D.GetLayerCollisionMask (gameObject.layer));
contactFilter.useLayerMask = true;

Which could be a game breaking issue since you are modifying physics related arguments there.


text:
Q: Comma as decimal separator in read_excel for Pandas I have a excel file with 119 sheets that I would like to get the data to plot multiple graphs. The problem is that the numeric values have comma as a decimal separator. And I have read that, differently from read_csv, the read_excel function in Pandas does not have this option.
I intend to load specific columns from some of selected sheets and build a merged graph using a for loop.
One of the alternatives that I saw (but it is kind of an overkill) is to transform each of the sheets into a specific csv file and load them and use the option of comma as decimal separator). Is there any alternative that I can load the data correctly without having to recourse to this alternative?
Thanks!

A: Well unlike read_csv() method read_excel() method doesn't support decimal parameter:
But after loading your dataset you can use:
df = pd.read_excel('yourexcel.xlsx')
#loading dataset

cols=#your list of column that you want to convert
df[cols]=df[cols].replace(',','.',regex=True).astype(float)

OR
Other way is to create a function and use converters parameter in read_excel() method:
def typecast_float(value):
    try:
        return float(value.replace(',', '.'))
    except:
        return value

#Finally:

df=pd.read_excel("sample.xlsx", converters={'column_name': typecast_float})

A: as simple as:
pd.read_excel(file_locale, decimal=',')

A: Just modify the thousands separator:
df = pd.read_excel('yourexcel.xlsx', thousands=',')


text:
Q: UseEffect stop working after refreshing the site I'm working in ReactJS. I have a form that is suppossed to be the configuration of another form. This specif form kind of looks like this:
  const [startingDate, setStartingDate] = useState();
  const [endingDate, setEndingDate] = useState();
  const [startingTime, setStartingTime] = useState();
  const [endingTime, setEndingTime] = useState();
  const [places, setPlaces] = useState();

  const createConfig = () => {
    Axios.post("http://localhost:3005/adminConfig", {
      startingDate,
      endingDate,
      startingTime,
      endingTime,
      places,
      organization: user._id,
    }).then((response) => {
      alert("successful")
    })
  }

After you send that data to the server I'm supposed to retrieve and set it as the configuration of another form (This second form is supposed to be shared and filled by other people) in the next way:
const [config, setConfig] = useState([]);

  useEffect(() => {
    Axios.get(`http://localhost:3005/adminConfig/`).then((response) => {
      setConfig(response.data);
    });
  }, []);

          <input
            type="date"
            placeholder="Date of the meeting
            name="date"
            id="datePickerId"
            min={config[0].startingDate}
            max={config[0].endingDate}
            onChange={(event) => {
              setDate(event.target.value);
            }}
            required
          />

When you access this form and havent set the configuration in React it works good. After accessing it and starting the configuration you can see how it updates; the dates are limited and in theory everything works good, the problem comes when you refresh the site or someone else try to access, it stops working and you have to delete the settings (config[0].startingDate, etc)
console shows:
Cannot read properties of undefined (reading 'startingDate')
Any help is appreciated

A: The useEffect hook is executed after the page is loaded. and at the time of initial page loading, config[0] is not defined.
use optional chaining and default value togther:
<input
    type="date"
    placeholder="Date of the meeting"
    name="date"
    id="datePickerId"
    min={config[0]?.startingDate || 0} // <==
    max={config[0]?.endingDate || 0} // <==
    onChange={(event) => {
        setDate(event.target.value);
    }}
    required
/>

A: If it is possible, you can use fallback value:
min={ config?.length > 0 ? config[0].startingDate : '1980-01-17'}

The reason why you've got an error as some people do not have admin config and it is okay:
Axios.get(`http://localhost:3005/adminConfig/`).then((response) =>
{
  setConfig(response.data);
});

A: Try making the axios request async too so that it doesn't return an empty array.

A: You can use optional chaining to achieve the required behavior, The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
<input
        type="date"
        placeholder="Date of the meeting
        name="date"
        id="datePickerId"
        min={config[0]?.startingDate} //change this
        max={config[0]?.endingDate} //change this
        onChange={(event) => {
          setDate(event.target.value);
        }}
        required
      />


text:
Q: Ruby 2.0.0 fails to install because of openssl I can't install ruby from source, on configuration (./configure) it states
Ignore OpenSSL broken by Apple.
Please use another openssl. (e.g. using `configure --with-openssl-dir=/path/to/openssl')
Failed to configure openssl. It will not be installed.

Even if I use the told parameter. --with-opt-dir=/usr/local doesn't help either. Notice, I installed the latest openssl (1.0.1e) from source too (it's located at /usr/local/ssh).
So later I can't use gem install, it just states:
ERROR:  Loading command: install (LoadError)
    cannot load such file -- openssl
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

How can I tell the ruby installation to take my installed openssl?

A: Rather than doing all the building from sources (and having to hunt down any necessary patches) why not try using rvm to build (and manage) your rubies, and homebrew to allow you to build and install the necessary dependencies.
I have used these to get a ruby 2.0.0 build completed earlier today, although I haven't had a chance to check if it's fully functional yet.

A: Had a similar issue on Tiger (yes, I'm using Ruby 2.0 on a Power Mac G4) – Ruby builds there just fine, but gem install rails fails with "RuntimeError: Unsupported digest algorithm (SHA512).".
Assuming you meant /usr/local/ssl and not /usr/local/ssh for the directory containing OpenSSL 1.0.1e, you should run ./configure as such:
./configure --prefix=/opt/ruby20 --with-openssl-dir=/usr/local/ssl
The configure script will say that --with-openssl-dir is an invalid option.  It's lying.  Add /opt/ruby20/bin (or whatever you set as your prefix) to your PATH and enjoy Ruby 2.0 :)

A: You need to change the code page of the current terminal window running this code:
chcp 1252


text:
Q: Casting to custom type in SELECT query I am new to PostgreSQL and absolutely lost here. (Guess even the title is absolutely wrong...)
I have e.g. this:
postgres=# SELECT round(10000::decimal/100, 4);
  round
----------
 100.0000
(1 row)

Is there an easy way to get the same result using a custom type:
postgres=# SELECT 10000::my_type;
----------
 100.0000
(1 row)

A: I think it depends on the type.
For example, the following works for me on Postgres 9.3
# CREATE TYPE foo AS (num INT);
CREATE TYPE

# SELECT 300::foo;
ERROR:  cannot cast type integer to foo
LINE 1: SELECT 300::foo

# SELECT (ROW(300)::foo).num;
 num
-----
 300
(1 row)

A: Formally you can create any type using this simplified syntax:
CREATE TYPE my_numeric (
    INPUT = my_numeric_in,
    OUTPUT = my_numeric_out,
    <optional parameters>
    )

where my_numeric_in and my_numeric_out are support functions. The problem is that

Generally these functions have to be coded in C or another low-level language.

This means that it is a kind of extending Postgres and you have to compile the server or an extension with the code of the functions, so it is definitely not an easy way. In practice this kind of input conversions might be done using triggers, however the described conversion looks strange and may be considered bad practice.
You may be tempted to define your type as domain and create appropriate cast but this will not work:

A cast to or from a domain type currently has no effect. Casting to or from a domain uses the casts associated with its underlying type.

The easiest way to achieve a similar effect is to store the value as numeric and use a conversion function, e.g.:
create or replace function my_numeric(numeric)
returns numeric language sql immutable as $$
    select round($1/100, 4)::numeric
$$;

select my_numeric(10000);

 my_numeric
------------
   100.0000
(1 row)


text:
Q: How to make crossdomain authorization? There are 2 domains on one server. If user is logged on one domain he has to be logged on the another domain too.
How to make cross-domain authorization in php on one server?
I solved it for sub-domains, but can't solve for different second-level domains.

A: The main problem is that the cookie isn't send by the browser if you're on another domain.
You can't make the browser to write a cookie for another domain, too.
What can be done is send a unique token to the other domain, and when validated, write a cookie on the second domain. That can be done when authenticated, using an iframe or a double-redirect (iframe cookies are blocked by some browsers, like safari). The unique token will have to be validated by the second domain, and then invalidated (removed) so it can't be used again by another user (man in the middle attack).

A: You must research for CAS and implement it depending on what framework you are using. For example, in my Zend application I would use Zend_OpenId and Zend_Oauth .


text:
Q: How can I change timezone and go back previous timezone My project libary version is
mybatis 3.1
postgresql 9.2
I want to change connection timezone before select query. and back to the timezone.
first, I try it. set timezone in mapper xml.
set timezone = 'Asia/Seoul' ;
select now();
set timezone = 'UTC';

I think If an error occurs when select query, Timezone is not set to UTC.
If timezone is not set to UTC, Query on the different request will be utc time.
second, I try it. sqlsession injected by spring DI.
sqlsession.selectOne(namespace.setTimezone, 'Asia/Seoul');
sqlsession.selectOne(namespace.selectNow);
sqlsession.selectOne(namespace.setTimezone, 'UTC');

I think. three sqlsession this may not be the same connection.
How can I change timezone and go back previous timezone?
If I process transactions, three sqlsession happens is the same connection?

A: Use a transaction.
It mybatis is worth its salt, it will support database transactions, and it has to use the same connection for all statements within one transaction.
I don't know if mybatis can do this, but in PostgreSQL you can use SET LOCAL to change a parameter only for the duration of a transaction. It will be reset automatically at the end of the transaction.


text:
Q: Function is not defined when importing external raw file in React I'm doing a Coursera course from Meta and I'm getting an error importing an api file.
We need to import this raw file from GitHub that contains three functions: seededRandom, fetchAPI, submitAPI.
Next, we need to use fetchAPI that receives a date as parameter and submitAPI that returns a boolean value. The problem is when i'm trying to use these functions React throws an error because functions are not defined.
I tried to use them from "window" global variable, but it still doesn't work.
Thanks you for your help!
I tried to use them from "window" global variable, but it still doesn't work.


text:
Q: Evans PDE Notation Chapter 1
*

*Page 2 in the Introduction chapter defines a linear PDE as

$$ \sum_{|\alpha| \leq k} a_{\alpha}(x)D^\alpha u = f(x)$$
Now, in Appendix A, Evans defines for a "multi-index" $\alpha = (\alpha_1...\alpha_n)$, where each component is a non-negative integer, $$ D^\alpha u = \frac{\partial^{|\alpha|} u}{\partial^{\alpha_1}x_1...\partial^{\alpha_n}x_n}.$$ Now, the fact that it is $ |\alpha| \leq k $ in the summation makes me think that $ \alpha $ is such a multi-index. However, in that case, the notation $ a_{\alpha}(x) $ does not make sense - shouldn't it be $ a_{|\alpha|}(x) $ instead? What does he mean to sum over here?


text:
Q: MySQLSyntaxErrorException: You have an error in your SQL syntax I am not seeing anymore where i am doing my mistake. Working with Spring 3 and Hibernate and Mysql so far worked perfectly and was ok, but on this one it just doesn't work.
This is my class:
@Entity
@Table(name = "order")
@XmlRootElement(name = "order")
public class Order implements java.io.Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "idOrder", length = 11)
    private int id;

    @Column(name = "latitude", nullable = true, length = 45)
    private String latitude;

    @Column(name = "longitude", nullable = true, length = 45)
    private String longitude;

    @Column(name = "orderDate", length = 30)
    @DateTimeFormat
    private Date orderDate;

    @Column(name = "city", nullable = true, length = 45)
    private String city;

    @Column(name = "country", nullable = true, length = 45)
    private String country;

    @Column(name = "street", nullable = true, length = 45)
    private String street;

    @Column(name = "streetNo", nullable = true, length = 45)
    private String streetNo;

    @Column(name = "created", length = 30)
    @DateTimeFormat
    private Date created;

    @JoinColumn(name = "idTaxi")
    @JoinTable(name= "taxi")
    @Column(name = "idTaxi", length = 11)
    private Integer idTaxi;

    @Column(name = "orderstatus", nullable = false, length = 45)
    private String orderstatus;

    @Column(name = "clientname", nullable = true, length = 45)
    private String clientName;

    //public getters and setters

}

In db, my table name is "order". I have checked all fields for typo.
In persistence xml config file:
[...]
 <property name="annotatedClasses">
     <list>
           <value>test.bean.Taxi</value>
           <value>test.bean.Order</value>
     </list>
</property>
<property name="hibernateProperties">
    <props>
        <prop key="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </prop>
        <prop key="hibernate.hbm2ddl.auto">create</prop>
        <prop key="lazy">true</prop>
        <prop key="hibernate.show_sql">true</prop>
        <!-- Show and print nice SQL on stdout -->
        <prop key="hibernate.format_sql">true</prop>
        <prop key="hibernate.archive.autodetection">class</prop>
    </props>
</property>
</bean>
[...]

In DAO class:
public List<Order> showAllOpenOrders() {

    List<Order> history = new ArrayList<Order>();
    history = getHibernateTemplate().find("FROM Order o where o.orderstatus ='open'");

    return history;
}

My Error:
SEVERE: Servlet.service() for servlet [] in context with path [/] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [select order0_.idOrder as idOrder1_, order0_.city as city1_, order0_.clientname as clientname1_, order0_.country as country1_, order0_.created as created1_, order0_.idTaxi as idTaxi1_, order0_.latitude as latitude1_, order0_.longitude as longitude1_, order0_.orderDate as orderDate1_, order0_.orderstatus as orderst10_1_, order0_.street as street1_, order0_.streetNo as streetNo1_ from order order0_ where order0_.orderstatus='open']; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order order0_ where order0_.orderstatus='open'' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3256)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1313)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1448)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:921)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:904)
at test.rest.persistence.OrderDAOImpl.showAllOpenOrders(OrderDAOImpl.java:154)
at test.rest.services.OrderServiceImpl.showAllOpenOrders(OrderServiceImpl.java:109)
at test.rest.controller.OrderController.showAllOrders(OrderController.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

I have successfully mapped another class(Taxi), but this one..just doesn't work.I don't get why... Do you see something i don't?
So my db table is lowecase "order" and in my Class Order i am mapping that table.
But if I try to access all the records from database with status set on "open" like this:
public List<Order> showAllOpenOrders() {
    ;
    List<Order> history = new ArrayList<Order>();
    history = getHibernateTemplate().find("FROM Order o where o.orderstatus ='" + TaxiStatus.OPEN + "'");

    return history;
}

I receive an error that there is an SQL Exception.
Thank you for your time.

A: order - is reserved keyword in MySQL, and must be backquoted if it used not as part of order by
rewrite you query as:
history = getHibernateTemplate().find("FROM `Order` o where o.orderstatus ='" + TaxiStatus.OPEN + "'");


text:
Q: Show different navigation for different users role I'm building an app where I have to show different navigation for users role. However, this is what I've came up with
Navigation example :

       @if (Auth::check() && Auth::user()->role == 'author')

nameslug) }}"> {{ Auth::user()->name }}

       @endif

       @if (Auth::check() && Auth::user()->role == 'admin')
         @if (!empty($page) && $page == 'admin')

 Admin

         @else

 Admin

         @endif
       @endif

       @if (Auth::check())

 Logout

       @else
          @if (!empty($page) && $page == 'login')

 Login

          @else

 Login

          @endif
       @endif

I've tested it and it works just fine, but I'm just wondering if this will affect the app performance, making it slow ? If so is there a better way to do this ? That's all and thanks!

A: This should not impact your application speed. A few if/else blocks won't change much. The roles for this user will be loaded on every page, but this is probably a very light query and Laravel is smart enough to only execute this query once per request.
So conclusion: this looks fine. :)


text:
Q: Sub-match syntax highlighting in Vim First, I'll show the specific problem I'm having, but I think the problem can be generalized.
I'm working with a language that has explicit parenthesis syntax (like Lisp), but has keywords that are only reserved against the left paren. Example:
(key key)

the former is a reserved word, but the latter is a reference to the variable named "key"
Unfortunately, I find highlighting the left paren annoying, so I end up using
syn keyword classification key

instead of
syn keyword classification (key

but the former triggers on the variable uses as well.
I'd take a hack to get around my problem, but I'd be more interested in a general method to highlight just a subset of a given match.

A: Using syn keyword alone for this situation doesn't work right because you want your highlighting to be more aware of the surrounding syntax.  A combination of syn region, syn match, and syn keyword works well.
hi link lispFuncs Function
hi link lispFunc Identifier
hi link sExpr Statement

syn keyword lispFuncs key foo bar contained containedin=lispFunc
syn match lispFunc "(\@<=\w\+" contained containedin=sExpr contains=lispFuncs
syn region sExpr matchgroup=Special start="(" end=")" contains=sExpr,lispFuncs

The above will only highlight key, foo, and bar using the Function highlight group, only if they're also matched by lispFunc.
If there are any words other than key, foo, and bar which come after a (, they will be highlighted using the Identifier highlight group.  This allows you to distinguish between standard function names and user-created ones.
The ( and ) will be highlighted using the Special highlight group, and anything inside the () past the first word will be highlighted using the Statement highlight group.

A: There does appear to be some capability for layered highlighting, as seen here: Highlighting matches in Vim over an inverted pattern
which gives ex commands
:match myBaseHighlight /foo/
:2match myGroup /./

I haven't been able to get anything like that to work in my syntax files, though. I tried something like:
syn match Keyword "(key"
syn match Normal "("

The highlighting goes to Normal or Keyword over the whole bit depending on what gets picked up first (altered by arrangement in the file)
Vim soundly rejected using "2match" as a keyword after "syn".


text:
Q: Google Apps Script server error when trying to add an editor to a Google Document I have some code that looks like this
  var folder = DriveApp.getFolderById(/* destination folder id */);
  var doc = DriveApp.getFileById(/* document file id */);

  var id = doc.makeCopy(folder).setName(/* name of copy */).getId();
  var new_doc = DocumentApp.openById(id);
  new_doc.addEditor(/* some email address */);

Running this causes the script to stop at the last line and throw this error:

We're sorry, a server error occurred. Please wait a bit and try again.

If I comment out the line, then the script runs fine.
Also if new_doc is a File instead of a Document, then the last line works fine too. It's only when new_doc is a Document type that it gives me an error. Apparently, it doesn't work for Document types either. Although the error I get is different from when it's a File:

Cannot use this operation on a Team Drive item.

Very weird, because this was working a while ago.
All resources used in this script (the script, the destination folder, the file that is copied, the copy, etc.) are in a Team Drive.
I am puzzled as to how or why this error is happening and I am looking for help in getting around this issue.

A: Add the editor through the DriveApp as opposed to the DocumentApp.
It appears to be a bug with DocumentApp, SpreadsheetApp and FormApp when working with Team Drive files.
var folder = DriveApp.getFolderById(/* destination folder id */);
var doc = DriveApp.getFileById(/* document file id */);

var id = doc.makeCopy(folder).setName(/* name of copy */).getId();
var new_doc = DriveApp.getFileById(id); //updated this from DocumentApp to DriveApp.
new_doc.addEditor(/* some email address */);


text:
Q: Java/Android - Getting socket output stream breaks execution with no exception launched I'm debugging the thread which manages a socket and I noticed that when I call getOutputStream() the debug breaks with no exception thrown. I've even added breakpoints to the very Socket.getOutputStream() but there is no way to get what's wrong.
The Java server correctly accepts the connection and waits for input (by checking inputStream.available()).
Both Socket and ServerSocket come from SSLSocketFactory and SSLServerSocketFactory.
I'm using Android Studio.
What am I doing wrong?
edit: I've even tried to change structure from Thread to AsyncTask but the result is the same. This is frustrating.

A: Debugging network connections is a bit tricky as time-outs may occur.
I am also unsure if breakpoints on non-app-code (like Socket.getOutputStream()) will really work. The SDK code in AndroidStudio may be different to the one used by your devices which mean that breakpoints (which are set to a specific line) may end up in a totally different method (if they work at all).
Therefore I would suggest to change your code and add log statements and if necessary sleep commands to slow-down the important parts.
For SSL traffic I strongly suggest to look also at the transferred data. There are apps capturing the traffic on-device that run without root permissions. Later you can then debug the traffic on the PC using Wireshark and see if the problem was caused by a communication problem between your client and the server.


text:
Q: manifest unknown: The named manifest is not known to the registry when pulling from remote repository on artifactory I have configured a remote docker repository on my new artifactory server which points to a virtual docker repo on a legacy artifactory server. I have tested the credentials to access the legacy server and they are working fine from the UI. On the UI for my new artifactory server I can even see the folder structure and all the artifacts from my legacy server. All the artifacts say "this item is not cached". I believe this is expected as it is meant as a representation of my upstream server and nothing has yet been pulled and cached locally.
I have then added this remote repository to a virtual docker repository on the new artifactory server.
The issue is that I am unable to pull items from my legacy server via the newly created remote or virtual repos.
I get the below error
Error response from daemon: manifest for obc-test-remote.myartifactoryserver.cloud/base-image:1.1.30 not found: manifest unknown: The named manifest is not known to the registry

I get the same when I target via the virtual (which has the remote added to it)
Error response from daemon: manifest for obc-test-virtual.myartifactoryserver.cloud/base-image:1.1.30 not found: manifest unknown: The named manifest is not known to the registry

the docker login is succeeded and I am able to pull other docker images with the same syntax from other virtual repos on the same server.
I unticked the option "Block pulling of image manifest v2 schema 1" in the remote repo configuration also

A: Seems an issue with the URL configured in the new Artifactory's remote repository. Can you check if this URL includes "api/docker" if not, make sure to have the URL as "http://myold-artifactory.com/artifactory/api/docker/docker-repo-name"


text:
Q: Lifecycle state management with Room live queries I have a view with three states:
sealed class MainState(val movieList: List<Movie>) {
    class Loading(movies: List<Movie> = emptyList()) : MainState(movies)
    class Success(movies: List<Movie>) : MainState(movies)
    class Error(val throwable: Throwable, movies: List<Movie> = emptyList()) : MainState(movies)
}

These states are wrapped in a MutableLiveData and managed by a ViewModel:
class MovieListViewModel(private val movieRepo: MovieRepository) : ViewModel() {
    val stateLiveData = MutableLiveData<MainState>()
    .
    .
}

I want to integrate the query liveData to my state liveDate so that when query liveData is updated to movieList, state liveData updates to Success(movieList). How can I acheive that?
Here's how my live query looks like:
@Dao
interface MovieDAO {
@Query("SELECT * FROM Movie")
   fun getAllMovies(): LiveData<List<Movie>>
}

A: If you have installed RxJava2 support for Room, I will consider following:
val stateLiveData = MutableLiveData<MainState>()

dao().getAllMovies()
     .subscribeOn(Schedulers.io())
     .observeOn(AndroidSchedulers.mainThread())
     .doOnSubscribe(() -> stateLiveData.value = Loading(emptyList()))
     .subscribeBy(
         onNext = { stateLiveData.value = Success(it) }
         onError { stateLiveData(it, emptyList()) }
      )

of course you need to change the return type of the Room query to Flowable<MainState> or Observable<MainState>.

A: It could be done with the use of MediatorLiveData.

LiveData subclass which may observe other LiveData objects and react
  on OnChanged events from them.

The solution looks like this:
    val stateLiveData = MediatorLiveData<MainState>()

    init {
        stateLiveData.addSource(movieRepo.getAllMovies()) {
            stateLiveData.value = Success(it)
        }
    }

For more info please check this great post