text:
Q: Adjust div width according to button rows width I have some buttons inside a div which, being many, form new rows down, so I've made a vertical scroll inside that div to have access to all those buttons.
The problem is that the vertical scroll is not next to the buttons, and that is what I need, but it is difficult because the width of a row of buttons will always vary according to the width of the screen.
In the snipet, if you change of your screen width, you can see that great variable space between the buttons and the scroll, I have put colors to the main divs for better distinction:

body{
 overflow-y: hidden;
}

#sentlist{
 height: 55px;
 overflow-y: auto;
}

#sli{
 width:auto;
 background-color: #EEAAEE;
}

.otradiv{
 height:50px;
 background-color:orange;
}

button{
  width:50px;
  height:23px;
}
<!DOCTYPE html>

<meta charset='utf-8'>
<title>Hi</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" href="test2.css">

            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>
            <button></button>

So, whatever the width of the screen, is there any way to eliminate the space between the buttons and the scroll?
edit:
Cause snipets here can't be resized, here's a codepen:

A: You can use flex
 #sli .flex-container {
    display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    justify-content: space-around;
    -webkit-justify-content: space-around;
    -moz-justify-content: space-around;
    flex-flow: row wrap;
    -webkit-flex-flow: row wrap;
    -moz-flex-flow: row wrap;
}

.flex-container {
display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    justify-content: space-around;
    -webkit-justify-content: space-around;
    -moz-justify-content: space-around;
    flex-flow: row wrap;
    -webkit-flex-flow: row wrap;
    -moz-flex-flow: row wrap;
}

.flex-container .item {
    width: 50px;
    height: 23px;
    background: red;
    margin: 0px 1.1% 8px;
}
.flex-dummy {
    height: 0 !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    margin-top: 0 !important;
    margin-bottom: 0 !important;
}
.flex-container .item>button {
    width: 100%;
    height: 100%;
}
.otradiv {
    height: 50px;
    background-color: orange;
}
#sentlist {
    height: 55px;
    overflow-y: auto;
}
#sli {
    width: auto;
    background-color: #EEAAEE;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

<button></button>

A: There is unwanted padding on div#sentlist which is creating the space between div#sli and the scroll bar. You need to remove the padding from div#sentlist.
  #sentlist{
    height: 55px;
    overflow-y: auto;
    padding: 0; //remove bootstrap padding
  }

Also, it is typically best practice to use classes rather than the id in your css file.


text:
Q: Camera preview in GLSurface view is too slow I am developing a camera application ,I have used camera API ,and GLSurface view to add live filters .I have used GPU Image library.The problem is camera preview is too lagging .I have tested on many devices ,devices with jellybean (API 15) will works perfect but preview of devices with lollipop and Marshmallow is too slow.Can anyone help ?
https://github.com/CyberAgent/android-gpuimage

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular.js Model Traversal Is there a function that goes like $.each(scope.model)? A function that traverses all the models within a scope?
I can't seem to find an answer anywhere and thought maybe I should give SO a try.
Thanks!
-Jan

EDIT:
So I've been playing around the code and found a workaround on this.
Fiddle here.
function ResetScope(scope){
    $(scope).each(function () {
        if(!(this instanceof Function)){
            for (var key in this) {
                if(key.indexOf("$") !== -1 || key.indexOf("this") !== -1)
                    continue;
                else
                    if(key instanceof Function){
                        continue;
                    }else if(this[key].indexOf("function") !== -1){
                        continue;
                    }else{
                        alert(this[key]);
                        this[key] = "";
                        console.log(this);
                    }
            }
        }
    });
    return scope;
}

The only thing that is not so awesome is that when you have a variable with a "function" in its name, it might also be filtered out. Well, at least for now, this snippet works. For those who have their answers, feel free to post your answer. Might be helpful to others.

A: For reference, Brian's Batarang tool has this code in appInspect.js:
var thisScope = angular.element(this).scope();
var models = {};
for (prop in thisScope) {
    if (thisScope.hasOwnProperty(prop) && prop !== 'this' && prop[0] !== '$') {
        models[prop] = thisScope[prop];
    }
}
var str = JSON.stringify(models);


text:
Q: how to assign class names for tagless ember components user-table.js
export default Ember.Component.extend({
    tagName: ''
});

user-table.hbs

    {{yield}}

usage
{{#users-table class="table table-bordered"}}
    {{#table-head}}
        {{#table-row}}
            {{table-head-cell}}
            {{table-head-cell}}
        {{/table-row}}
    {{/table-head}}
    {{#table-body}}
        {{#each users as |user|}}
            {{#table-row}}
                {{table-body-cell cellValue=user.name}}
                {{table-body-cell cellValue=user.age}}
            {{/table-row}}
        {{/each}}
    {{/table-body}}
    {{#table-foot}}
        {{#table-row}}
            {{table-head-cell}}
            {{table-head-cell}}
        {{/table-row}}
    {{/table-foot}}
{{/users-table}}

since i mentioned tagName for the component as empty (tagName:''), how to pass class names for that root element. is there any alternative

A: Tagless components, as the name says, don't have a tag, so you can't stick classes on them. They also don't have event handling, as there's no element to register the handlers on.
The suggestions in the comments are on a good track, use tagName="table" and have only a {{yield}} in the component template:
// user-table.js
export default Ember.Component.extend({
  tagName: 'table'
});

// user-table.hbs
{{yield}}

That seems to make better use of Ember functionality than alternatives.

A: You can pass classNames to tagless components like so (Ember Twiddle):
// user-table.js
export default Ember.Component.extend({
  tagName: ''
});

// user-table.hbs

  {{yield}}

// usage
{{#users-table class="table table-bordered"}}...{{/users-table}}

The nice thing about tagless components is that it is clear from the template what the top-level element of the component is, you don't have to look up the javascript file.


text:
Q: PHP Pagination with SQL

I have done this pagination using PHP and SQL. id 11 and 12 is missing in the page 2 module. I cant find out where i am doing the mistake. Please find the source code below
<?php
$per_page = 5;
$rec_count = $row['id'];
$total_pages = ceil($rec_count / $per_page);

if (isset($_GET['page'])) {
    $show_page = $_GET['page']; //current page
    if ($show_page > 0 && $show_page <= $total_pages) {
        $start = ($show_page - 1) * $per_page;
        $end = $start + $per_page;
    } else {
        $start = 0;
        $end = $per_page;
    }
} else {
    $start = 0;
    $end = $per_page;
}

$page = intval($_GET['page']);
$tpages=$total_pages;
if ($page <= 0)
    $page = 1;

$sql = "SELECT COUNT(Id) AS id FROM [Register].[dbo].[RegisData] WHERE DeleteStatus = 1";
$result = sqlsrv_query($conn,$sql);
$row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC);
$rec_count = $row['id'];
$total_pages = ceil($rec_count / $per_page);

$sql1 = "SELECT [Id],[FirstName],[LastName],[ProfilePic],[Gender]
                ,[Email],[MobileNo],[Company],[Designation],[Country],[State],[Address],[City]
                ,[Pincode],[Hobbies],[DietaryHabits],[DeleteStatus]
        FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY RegId) as row
        FROM [Register].[dbo].[RegisData])
        a WHERE row between $start and $end
        AND DeleteStatus = 1
        ORDER BY RegId";

$result = sqlsrv_query($conn,$sql1);
$z = 1;
for ($x=1; $x<=$total_pages; $x++) {
    echo $x;
}
?>

Please help me where i have done the mistake.


text:
Q: In android, why service's oncreate() method invokes twice when the activity starts and destroys In main activity's oncreate(), the code is
Intent intent = new Intent(this, SampleService.class);
startService(intent);

In service's oncreate(), the code is
Toast.makeText(this, "oncreate", Toast.Length_Short).show();

When I start the activity, it shows "oncreate", but when I remove the activity from the recent application list, it also shows "oncreate", why?


text:
Q: Сделать сложную выборку элементов в jquery Есть вот такой фрагмент верстки:

Some link
<input class="selected/unselected">

Хотел спросить как можно выбрать див класс 1 если у него внутри будет инпут селектед (т.е если внутри дива находится инпут селектед, то див должен становиться тоже селектед), и убирать класс если инпут станет анселектед. Инпуты меняют свой класс если кликать на другую кнопку на сайте.
A: $('div.1').each(function(){
    if($.contains(this, $('input.selected', this)[0]))
        $(this).addClass('selected');
});
$('div.1 input').live('focusin focusout', function(){
    $(this).toggleClass('selected unselected').closest('div.1').toggleClass('selected unselected');
});

A: Если код будет такой:

    Some link
    <input class="selectable unselected">

То на JQuery будет примерно такой обработчик:
$('div.1>span>input.selectable').live('focus blur', function(event) {
$(event.target).toggleClass('selected unselected');

var $parent = $(event.target)
    .parent()
    .parent();

if($parent.hasClass('1'))
{
    $parent.toggleClass('selected unselected');
}

});

глянуть можно тут
A: А почему нельзя ставить класс сразу на div, а на input вообще не ставить? Сейчас вы хотите, вместо решения одной проблемы, создать новую.
A: $('div.1 input').each(function(){
    $(this).closest('div.1').addClass( $(this).hasClass('selected')?'selected':'' );
    $(this).closest('div.1').removeClass( $(this).hasClass('selected')?'':'selected' );
});


text:
Q: R - Error: argument 1 is not a vector when bootstrapping I'm attempting to bootstrap my data to get 2000 measurements based on the linear regression and Theil regression (mblm function w/ repeated=FALSE).
My bootstrap R code works perfectly for the normal regression (from what I can tell), given below:
> fitfunc <- function(formula, data, index) {
+ d<- data[index,]
+ f<- lm(formula,data=d)
+ return(coef(f))
+ }

boot(dataframe, fitfunc, R=2000, formula=`Index A`~`Measurement B`)

But I get an error when attempting the Theil estimator bootstrap:
> fitfuncTheil <- function(formula,data,index) {
+ d<- data[index,]
+ f<- mblm(formula, data=d, repeated=FALSE)
+ return(coef(f))
+ }
> boot(dataframe, fitfuncTheil, R=2000, formula=`Index A`~`Measurement B`)

Error in order(x) : argument 1 is not a vector
    In addition: Warning message:
    In is.na(x) :

The error message seems basic but I cannot figure out why this would work in one case but not the other.

A: Once I removed the space from the column names (referenced in the formula field), the issue was resolved.


text:
Q: MYSQL trigger Query syntax error MYSQL:
DELIMITER $$
CREATE TRIGGER `Activation_code` BEFORE UPDATE ON `user_users` FOR EACH ROW BEGIN
    (CASE
     WHEN (OLD.activation_code_time < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 15 MINUTE) AND OLD.activation_code <> NEW.activation_code)
           THEN SET NEW.activation_code = (SELECT(ROUND((RAND() * (999999-100000))+100000))), NEW.activation_code_time = (SELECT(UNIX_TIMESTAMP()))
           ELSE SET NEW.activation_code = OLD.activation_code, NEW.activation_code_time = OLD.activation_code_time
    END);
    (CASE
      WHEN (OLD.forgotten_password_time < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 15 MINUTE) AND OLD.txt_key <> NEW.txt_key)
           THEN SET NEW.forgotten_password_time = (SELECT(UNIX_TIMESTAMP()))
           ELSE SET NEW.forgotten_password_time = OLD.forgotten_password_time
    END);
END
$$
DELIMITER ;

Error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CASE
     WHEN (OLD.activation_code_time < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTE' at line 2

Can anyone please tell me How can I resolve this error? why this function is not working. can I solve this by using one case and multiple when a statement with else statement?

A: Use if instead of case.
DELIMITER   $$
CREATE  TRIGGER `ACTIVATION_CODE` BEFORE UPDATE ON `user_users`
FOR EACH ROW
BEGIN

    IF OLD.ACTIVATION_CODE_TIME < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 15  MINUTE)) AND OLD.ACTIVATION_CODE !=  NEW.ACTIVATION_CODE THEN
        SET NEW.ACTIVATION_CODE  = (ROUND((RAND()   *   (999999-100000))+100000));
        SET NEW.ACTIVATION_CODE_TIME = UNIX_TIMESTAMP();
    ELSE
        SET NEW.ACTIVATION_CODE = OLD.ACTIVATION_CODE;
        SET NEW.ACTIVATION_CODE_TIME = OLD.ACTIVATION_CODE_TIME;
    END IF;

    IF OLD.forgotten_password_time < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 15 MINUTE)) AND OLD.txt_key != NEW.txt_key THEN
        SET NEW.forgotten_password_time = UNIX_TIMESTAMP();
    ELSE
        SET NEW.forgotten_password_time = OLD.forgotten_password_time;
    END IF;

END$$
DELIMITER ;

A: You can't apply multiple SET values for fields under CASE block.
Instead call SET first on a field to set values based on a CASE.
Following change may help you.
DELIMITER $$

CREATE TRIGGER `Activation_code` BEFORE UPDATE ON `user_users`
FOR EACH ROW
BEGIN
    set NEW.activation_code = (
        CASE WHEN
                OLD.activation_code_time < UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 15 MINUTE) )
                AND OLD.activation_code <> NEW.activation_code
            THEN ROUND( ( RAND() * (999999-100000) ) + 100000 )
            ELSE OLD.activation_code
        END
        );
    set NEW.activation_code_time = (
        CASE WHEN
                OLD.activation_code_time < UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 15 MINUTE) )
                AND OLD.activation_code <> NEW.activation_code
            THEN UNIX_TIMESTAMP()
            ELSE OLD.activation_code_time
        END
        );
    set NEW.forgotten_password_time = (
        CASE WHEN
                OLD.forgotten_password_time < UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 15 MINUTE) )
                AND OLD.txt_key <> NEW.txt_key
            THEN UNIX_TIMESTAMP()
            ELSE OLD.forgotten_password_time
        END
        );
END;
$$

DELIMITER ;


text:
Q: Trying to use hover on a element below an absolute positioned element So I'm trying to use a hover effect on two elements. One of the elements has a absolute position, this element needs to have the background recolored once hovered. This seems to work, however I cannot get the back image to scale accordingly. I think it has to do with the absolute positioning of the first div. But I cannot find a way to fix this. I have been trying to fix it using pointer-event but I cannot get that to do the trick.

This is the code I have got right now

A: You can't get hover effects on two stacked elements at once. However, if you want to be able to hover the element which is behind  another element, you can use pointer-events: none; on the element in the foreground, allowing mouse actions to "go through it" and therefore affect the element in the back:

A: You can add pointers-event: none; to img and your pointer will ignore the image but that's only in case you don't have any plan to add some mouse actions on image later

A: You're correct that you're not getting the hover event on the image because the absolutely positioned
 is covering it. But since the  element immediately follows the
 element in your HTML hierarchy, you can use the Adjacent Sibling Combinator to target it.

A: I have found out that moving the hover effect to .master instead of the seperate elements seem to work.

        test

A: There is no problem  between hover and absolut position.
Your problem is that img tag is place on top on .hover cause of the absolute position.
So your hover div is behind your image and the mouse over is intercepted by image tag.
Hope it's help

A: You need to set the :hover to an absolute element with class .hover:
.hover:hover + img {
    transform: scale(1.2);
}

Also, set z-index for the same class without a :hover.
In addition, I've added transition for transform and background.

.master {
    width: 1200px;
    overflow: hidden;
    position: relative;
    display: inline-flex;
}

.hover {
    position: absolute;
    height: 100%;
    width: 100%;
    z-index: 9999;
    transition: background .5s;
}

img {
    width: 100%;
    transition: transform .5s;
}

.hover:hover + img {
    transform: scale(1.2);
}

.hover:hover {
    background: rgba(255, 0, 0, 0.5);
}


text:
Q: Duplicate Content Management I have bunch of duplicate content errors to fix. Same content have different links. Or some have only one duplicate content error. Whats the easy way to fix. Its hurting SEO really badly.
I have tried to use 301 redirect which already active but I also know that using rel="canonical" link can fix but need clear explanation on how to use and where to use, is it in source?

A: Do you have actual duplicate content in the content tree or you just have multiple URL alias for the same content page?
If you have duplicate content in the tree, delete the duplicates.
If you have multiple URL alias for the same page, then set the alias redirection behavior to be "redirect to main URL". This way, search engine will know those aliases are 301 redirect to main URL.

A: Using canonical links is the best option in your case. Canonical links help Google to understand what URL is main for your content. Follow this official Google instruction to understand better.

A: In some cases it makes sense to have duplicates in the content tree.  BUT you need to take caution as to how to deal with them.  As Rui stated, make sure the setting is set to "redirect to the main URL".
Also, implement a canonical link web part on the master page. There is one on the Kentico Marketplace which is really robust and works well.


text:
Q: Drupal Theming - Different themes for each webform I am including a webform block in a page using module invoke.
The block is included as a node, and says "Submitted by  admin  on Wed, 2010-01-20 14:06" on top of the form. The devel template information is as follows:
Template called:
    node.tpl.php
File used:
    sites/all/themes/david01/node.tpl.php
Candidate template files:
    node-webform.tpl.php < node.tpl.php
I know how to theme the webform (webform-form-###.tpl.php), but how do I theme this node in particular (node-webform-####.tpl.php is not a candidate!)

A: Try to define node-[nid].tpl.php - a template for a single node.
Also look through this post.


text:
Q: Laravel Eloquent Many to Many [Edit] I have Many-Many tables of users and tasks and user_task. That users are able to be assigned multiple tasks.
**User model:**
public function tasks() {
  return $this->belongsToMany(Task::class, 'user_task', 'user_uuid', 'task_uuid');
}

**Task Model:**
public function users() {
  return $this->belongsToMany(User::class, 'user_task', 'task_uuid', 'user_uuid');
}

**Controller:**
public function store(Request $request) {
  $user = auth()->user();
  $tasks_uuid = $request->tasks;
  $user->tasks()->sync($tasks_uuid);
  return response()->json(['message' => 'Submit'], 200);
}

But after a successful store, I expect user_uuid but it stores id of user instead.

A: Laravel convention presumes that the primary key name is 'id' if you did not follow that, you should pass the primary key name in your relation ...
belongsToMany relation definition:

BelongsToMany belongsToMany(string $related, string|null $table =
null, string|null $foreignPivotKey = null, string|null
$relatedPivotKey = null, string|null $parentKey = null, string|null
$relatedKey = null, string|null $relation = null)

for your case your relation should be:
**User model:**
public function tasks() {
  return $this->belongsToMany(Task::class, 'user_task', 'user_uuid', 'task_uuid','user_uuid','task_uuid');
}

**Task Model:**
public function users() {
  return $this->belongsToMany(User::class, 'user_task', 'task_uuid', 'user_uuid','task_uuid','user_uuid');
}


text:
Q: Simulator background is dark / broken I am following the Apple tutorial on Swift and for some reason my simulator background is black causing parts of the app to not show up correctly. This is what my simulator looks like

This is what it is supposed to look like (cropped because my screen won't fit)

I tried restarting simulator and Xcode but it won't go away. How to fix this?

A: It's probably because you change your view background view to Default

It does looks the same in Interface Builder (Still White) but will be black in Simulator
try to change it back to White


text:
Q: CUDAFunctionload error I am trying to get CUDAFunctionLoad to work with Mathematica 9.0.
I installed the latest clang and the Nvidia Tools 6.0.
but I keep getting the error message:

CUDAFunctionLoad::cmperr: "-- Message text not found --
                             "clang: error: unsupported option -dumpspecs" "

I note that others have the same problem.  i asked NVIDIA and Wolfram Reaserch for help
and they have not come up with any solution so far, although they suspect the problem is that clang in latest version is not compatible with Mathematica 9.0.
Any help, insights or leads would be very much appreciated.

A: Try using the following, so you update CudaLink in the process:
     Needs["CUDALink`"]
     CUDAResourcesInstall[Update -> True]
     CUDAQ[] (* This might take long *)
     CUDAInformation[]


text:
Q: How can I link to a specific glibc version? When I compile something on my Ubuntu Lucid 10.04 PC it gets linked against glibc. Lucid uses 2.11 of glibc. When I run this binary on another PC with an older glibc, the command fails saying there's no glibc 2.11...
As far as I know glibc uses symbol versioning. Can I force gcc to link against a specific symbol version?
In my concrete use I try to compile a gcc cross toolchain for ARM.

A: You are correct in that glibc uses symbol versioning.  If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.
One option is to statically link your binary.  This is probably the easiest option.
You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.
According to the http://www.trevorpounds.com blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver pseudo-op that is used for defining versioned symbols in the first place.  The following example is excerpted from the blog post.
The following example makes use of glibc's realpath, but makes sure it is linked against an older 2.2.5 version.
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
{
    const char* unresolved = "/lib64";
    char resolved[PATH_MAX+1];

    if(!realpath(unresolved, resolved))
        { return 1; }

    printf("%s\n", resolved);

    return 0;
}

A: This repo:
https://github.com/wheybags/glibc_version_header
provides a header file that takes care of the details described in the accepted answer.
Basically:

*

*Download the header of the corresponding GCC you want to link against

*Add  -include /path/to/header.h to your compiler flags

*You may also need to add -D_REENTRANT if you're linking pthread

I also add the linker flags:
-static-libgcc -static-libstdc++ -pthread
But those are dependent on your app's requirements.

A: An alternative is to just discard the version info and let the linker default to whatever version it has.
To do this, you may want to check out PatchELF1:
$ nm --dynamic --undefined-only --with-symbol-versions MyLib.so \
  | grep GLIBC | sed -e 's#.\+@##' | sort --unique
GLIBC_2.17
GLIBC_2.29
$ nm --dynamic --undefined-only --with-symbol-versions MyLib.so | grep GLIBC_2.29
                 U exp@GLIBC_2.29
                 U log@GLIBC_2.29
                 U log2@GLIBC_2.29
                 U pow@GLIBC_2.29
$ patchelf --clear-symbol-version exp   \
           --clear-symbol-version log   \
           --clear-symbol-version log2  \
           --clear-symbol-version pow   MyLib.so

This is extremely useful if you don't have the source at hand (or have a hard time understanding the code2).
1 Although patchelf is available on many distributions, they are very likely to be outdated.
The --clear-symbol-version flag was added in version 0.12, which, unfortunately, does not fully remove version requirements.
You will need to compile manually from this merge request before it gets merged.
2 FYI, I was cross-compiling LuaJIT.

A: Setup 1: compile your own glibc without dedicated GCC and use it
Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.
This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.
But it is not reliable as it uses host C runtime objects such as crt1.o, crti.o, and crtn.o provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.
For a more reliable setup, see Setup 2 below.
Build glibc and install locally:
export glibc_install="$(pwd)/glibc/build/install"

git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`

Setup 1: verify the build
test_glibc.c
#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>

atomic_int acnt;
int cnt;

int f(void* thr_data) {
    for(int n = 0; n < 1000; ++n) {
        ++cnt;
        ++acnt;
    }
    return 0;
}

int main(int argc, char **argv) {
    /* Basic library version check. */
    printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());

    /* Exercise thrd_create from -pthread,
     * which is not present in glibc 2.27 in Ubuntu 18.04.
     * https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
    thrd_t thr[10];
    for(int n = 0; n < 10; ++n)
        thrd_create(&thr[n], f, NULL);
    for(int n = 0; n < 10; ++n)
        thrd_join(thr[n], NULL);
    printf("The atomic counter is %u\n", acnt);
    printf("The non-atomic counter is %u\n", cnt);
}

Compile and run with test_glibc.sh:
#!/usr/bin/env bash
set -eux
gcc \
  -L "${glibc_install}/lib" \
  -I "${glibc_install}/include" \
  -Wl,--rpath="${glibc_install}/lib" \
  -Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
  -std=c11 \
  -o test_glibc.out \
  -v \
  test_glibc.c \
  -pthread \
;
ldd ./test_glibc.out
./test_glibc.out

The program outputs the expected:
gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674

Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot made it fail with:
cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install

so I removed it.
ldd output confirms that the ldd and libraries that we've just built are actually being used as expected:
+ ldd test_glibc.out
        linux-vdso.so.1 (0x00007ffe4bfd3000)
        libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
        libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
        /home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)

The gcc compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:
COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o

Setup 1: modify glibc
Now let's modify glibc with:
diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
    License along with the GNU C Library; if not, see
    <http://www.gnu.org/licenses/>.  */

+#include <stdio.h>
+
 #include "thrd_priv.h"

 int
 thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
 {
+  puts("hacked");
   _Static_assert (sizeof (thr) == sizeof (pthread_t),
                   "sizeof (thr) != sizeof (pthread_t)");

Then recompile and re-install glibc, and recompile and re-run our program:
cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh

and we see hacked printed a few times as expected.
This further confirms that we actually used the glibc that we compiled and not the host one.
Tested on Ubuntu 18.04.
Setup 2: crosstool-NG pristine setup
This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o, crti.o, and crtn.o.
In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.
The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.
crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.
Yes the GCC build system is so bad that we need a separate project for that.
This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.
Get crosstool-NG and configure it:
git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig

The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:
uname -a

which shows me:
4.15.0-34-generic

so in menuconfig I do:

*

*Operating System

*

*Version of linux
so I select:
4.14.71

which is the first equal or older version. It has to be older since the kernel is backwards compatible.
Now you can build with:
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

and now wait for about thirty minutes to two hours for compilation.
Setup 2: optional configurations
The .config that we generated with ./ct-ng x86_64-unknown-linux-gnu has:
CT_GLIBC_V_2_27=y

To change that, in menuconfig do:

*

*C-library

*Version of glibc
save the .config, and continue with the build.
Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:

*

*Paths and misc options

*

*Try features marked as EXPERIMENTAL: set to true

*C-library

*

*Source of glibc

*

*Custom location: say yes

*Custom location

*

*Custom source location: point to a directory containing your glibc source

where glibc was cloned as:
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28

Setup 2: test it out
Once you have built he toolchain that you want, test it out with:
#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
  x86_64-unknown-linux-gnu-gcc \
  -Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
  -Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
  -v \
  -o test_glibc.out \
  test_glibc.c \
  -pthread \
;
ldd test_glibc.out
./test_glibc.out

Everything seems to work as in Setup 1, except that now the correct runtime objects were used:
COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o

Setup 2: failed efficient glibc recompilation attempt
It does not seem possible with crosstool-NG, as explained below.
If you just re-build;
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.
If we do:
./ct-ng list-steps

it gives a nice overview of the build steps:
Available build steps, in order:
  - companion_tools_for_build
  - companion_libs_for_build
  - binutils_for_build
  - companion_tools_for_host
  - companion_libs_for_host
  - binutils_for_host
  - cc_core_pass_1
  - kernel_headers
  - libc_start_files
  - cc_core_pass_2
  - libc
  - cc_for_build
  - cc_for_host
  - libc_post_cc
  - companion_libs_for_target
  - binutils_for_target
  - debug
  - test_suite
  - finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.

therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files comes before cc_core_pass_2, which is likely the most expensive step together with cc_core_pass_1.
In order to build just one step, you must first set the "Save intermediate steps" in .config option for the intial build:

*

*Paths and misc options

*

*Debug crosstool-NG

*

*Save intermediate steps
and then you can try:
env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`

but unfortunately, the + required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536

Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).

and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.
Furthermore, starting from the libc step didn't seem to copy over the source again from Custom source location, further making this method unusable.
Bonus: stdlibc++
A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?

A: Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

A: In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:
Just build on the system with the oldest GLIBC you still want to support.
This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:

*

*Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.

*Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.
With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.


text:
Q: Is there a better way to use handler in UIAlertController (Swift)? I'm trying to use an AlertController to allow the user to return to the main menu, if a certain calculated value is exceeded. I know that using a simple segue will lead to memory problems.  Is there a way to use the popToRootViewController method in this situation instead of simply using a segue? The compiler yells at me (no doubt for good reasons), but gives me no useful suggestions. I know the problem stems from the handler for the Abort Fit action.  Can someone point me in the right direction?
override func viewDidLoad() {
    super.viewDidLoad()

    if deltaK > 2.25 {

    var helpAlert = UIAlertController(title: "Stop!", message: "Due  to high toricity, the fit should be aborted.", preferredStyle: .Alert)

     helpAlert.addAction(UIAlertAction(title: "Abort Fit", style: UIAlertActionStyle.Default, handler: { action in self.navigationController.popToRootViewControllerAnimated(true)) })

     helpAlert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(helpAlert, animated: true, completion: nil)
    }

A: You will want to add [weak self] to the start of each handler block if you are referencing self in the closure.

A: I overlooked the unwrapping issue.  Adding [weak self] to the closure triggered the compiler to signal the error.  This code works as intended. nhgrif pointed out a problem with using an Alert with viewDidLoad.  Should I be looking for another way to do this?
override func viewDidLoad() {
    super.viewDidLoad()

    if deltaK > 2.25 {

        var helpAlert = UIAlertController(title: "Stop!", message: "Due to the high corneal toricity, a toric GP lens may provide better fit, vision, and comfort. Consider using the Empirical GP lens designer from the Main Menu, or use toric GP fitting set.", preferredStyle: .Alert)

        helpAlert.addAction(UIAlertAction(title: "Abort Fit", style: UIAlertActionStyle.Default, handler: { [weak self] action in self!.navigationController?.popToRootViewControllerAnimated(true) }))

        helpAlert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(helpAlert, animated: true, completion: nil)
    }


text:
Q: React Native - how to key number pad ONLY (without punctuations) Is there a way to key a numeric keypad without punctuations?
<TextInput keyboardType='numeric' ..... />

if I use secureTextEntry={true}, it gets the right keyboard I want, but the values are replaced with *.
so, this is what im getting:

This is what I want:

A: keyboardType={"number-pad"} Works on Android.
Note: I am using FormInput from react-native-elements.

A: React native not provided keyboardType which remove punctuation from keyboard. You need to use regular expression with replace method to remove punctuation from text and set keyboardType = 'numeric'.
Regular Expression

/[- #*;,.<>{}[]\/]/gi

Example code
 onTextChanged(value) {
    // code to remove non-numeric characters from text
    this.setState({ number: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
  }

Please check snack link
https://snack.expo.io/@vishal7008/numeric-keyboard

A: Did you try number-pad? both number-pad and numeric work for me on iOS.

A: I had the same problem.
I could solve doing something like this:
keyboardType={Device.isAndroid ? "numeric" : "number-pad"}

and then in a method call from onChangeText doing this:
const cleanNumber = number.replace(/[^0-9]/g, "");

this.setState({
  cleanNumber
});

and it the value prop of TextInput
value={this.state.cleanNumber}

A: Android doesn't support keyboardType without  punctuations A visual guide to the React Native TextInput keyboardType prop values

A: For Android in my case I prevent set any special char with Miguel Cardenas example.
Here what I did:
const inputRef = useRef(null);
const setRefValue = v => {
      const clean = v.replace(/[^0-9]/g, '');
      inputRef.current.value = clean;
      inputRef.current.setNativeProps({ text: clean });
    }
  };

<TextInput
   ref={inputRef}
   keyboardType={numeric}
   onChangeText={setRefValue}
/>

Every time type in TextInput the constant setRefValue will clean special characters.

A: (Platform.OS === 'ios') ? 'done' : 'next' — good spike


text:
Q: Avoiding character encoding in Apache Abdera I'm working to write a simple article editor which will be used with a CMS system which offers an Atom API to add/edit articles. To communicate with the CMS, I am using the Apache Abdera library. But I'm running into a problem with character encoding. The data sent to the CMS will be encoded like this:
<entry>
  <content xmlns:vdf="http://www.vizrt.com/types" type="xml">
    <vdf:payload>
      <vdf:field name="body">
        <vdf:value><div xmlns="http://www.w3.org/1999/xhtml"><p>Text comes here</p></div></vdf:value>
      </vdf:field>
    </vdf:payload>
  </content>
</entry>

But the CMS system requires this:
<entry>
  <content xmlns:vdf="http://www.vizrt.com/types" type="xml">
    <vdf:payload>
      <vdf:field name="body">
        <vdf:value>

Text comes here

</vdf:value>
      </vdf:field>
    </vdf:payload>
  </content>
</entry>

In other words, no character escaping. Does anyone know how this can be achieved using Apache Abdera?

A: I'm not entirely familiar with abdera's internals and therefore can't explain exactly what is happening here, but I think the essence is that you can not use Strings or plain text as values if you don't want abdera to escape stuff. Instead, you must use an Element with abdera-type XHtml.
Something like this worked for me:
String body = "
Text comes here
"

//put the text into an XHtml-Element (more specificly an instance of Div)
//I "misuse" a Content object here, because Content offers type=XHtml. Maybe there are better ways.
Element el = abdera.getFactory().newContent(Content.Type.XHTML).setValue(body).getValueElement();

//now create your empty <vdf:value/> node.
QName valueQName = new QName("http://your-vdf-namespace", "value", "vdf");
ExtensibleElement bodyValue = new ExtensibleElementWrapper(abdera.getFactory(),valueQName);

//now attach the Div to that empty node. Not sure what's happening here internally, but this worked for me :)
bodyValue.addExtension(el);

Now, bodyValue can be used as value to your field and Abdera should render everything properly.


text:
Q: Problem with assigning attributes to variations in WooCommerce REST API I am triying to update a product in WooCommerce with variants and attributes but when I launch the request the variant is created but it is not related to the attribute.
Here is the request:
require __DIR__ . "/vendor/autoload.php";

use Automattic\WooCommerce\Client;

$woocommerce = new Client(
'https://wpsiteurl.com',
'consumer_key',
'consumer_secret',
    [
        "version" => "wc/v3",
    ]
);

$data = [
    'regular_price' => '9.00',
    'attributes' => [
        [
            "name" => "test_attribute",
            "option" => "test_term"
        ]
    ]
];

$woocommerce->post("products/"."00000"."/variations",$data);

A: Please assign the attributes which are already created to the parent product(Variable).And I see that the attributes body needs id & options,you can find them in attributes section. Like below
{"attributes": [
{
"id": 4,
"options": "white"
}
]
}


text:
Q: Opening an iframe source in a new tab if it tries to redirect the user It's a known fact that a lot of websites use javascript codes to prevent from browsing them using iframes. I would like then my iframe to behave like this: if the site doesn't have such a code and isn't trying to redirect the user, its content should be shown in the iframe. But if it's trying to redirect, it should be opened in a new tab (just like links with target="_blank"). Is it possible to use onUnload or any other techniques to do such a thing?
Thanks in advance,
Michael.

A: This will be extremely tough and complex and kludgy to achieve, if it's possible at all. It would require to predict the target site's behaviour before navigating to the link.  On second thought, this may in fact be possible using the onbeforeunload event but I expect a lot of trouble with pop-up blockers and the like.
I am assuming you have external links, and would like to show some "return to original site" bar in order to not lose visitors.
What I would do as a simple workaround is open the site in a new target="_blank" window in both cases, and have your "return to site" link close the window using window.close().


text:
Q: React - Random background color to each element for loop I'm doing the "Color Guessing Game" using Reactjs and I'm having some problems with giving random background color to each square. So when I do my for loop to show 6 squares, and pass color props, it gives the same color to all squares and not random color to each square...
Thank you in advance!
This is my App Component:
import React, { Component } from 'react';
import './App.css';

import SquaresContainer from './containers/SquaresContainer/SquaresContainer';

class App extends Component {

  constructor() {
    super();
    this.state = {
      correctColor: undefined,
      rgbDisplay: '',
      colorSquares: undefined
    }
  }

  generateRandomColor() {
    let r = Math.round((Math.random() * 255)); //red 0 to 255
    let g = Math.round((Math.random() * 255)); //green 0 to 255
    let b = Math.round((Math.random() * 255)); //blue 0 to 255
    return 'rgb(' + r + ', ' + g + ', ' + b + ')';
  };

  componentDidMount() {
    let correctColor = this.generateRandomColor();
    let colorSquares = this.generateRandomColor();

    this.setState({
      correctColor: correctColor,
      rgbDisplay: correctColor,
      colorSquares: colorSquares
    })
  };

  render() {

    return (

        {/* HEADER */}

THE GREAT

              {this.state.rgbDisplay}

            GUESSING GAME

            by Ana Fig

            REACT

        {/* / HEADER */}

        {/* MENU BUTTONS */}

            <button id="newColorButton">NEW COLORS</button>

            <button className="easyMode">EASY</button>
            <button className="hardMode selected">HARD</button>

        {/* / MENU BUTTONS */}

        {/* SQUARES COMPONENT */}
        <SquaresContainer color={this.generateRandomColor()} />
        {/* / SQUARES COMPONENT */}

    );
  }
}

export default App;

This is my SquaresContainer Component:
import React, { Component } from 'react';

import './SquaresContainer.css';

import Square from '../../components/Square/Square';

class SquaresContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
      squares: 6
    }
  }
  createSquares = () => {
    let squares = [];
    for (let i = 0; i < this.state.squares; i++) {
      squares.push(<Square color={this.props.color} key={i} />);
    }
    console.log(this.props.color)
    return squares;
  }

  render() {

    return (

        {this.createSquares()}

    );
  }
};

export default SquaresContainer;

This is Square Component:
import React from 'react';

import './Square.css';

const Square = (props) => {

  return (

  );
};

export default Square;

This is a print from what's happening:

A: You are creating 6 squares with the same color:

createSquares = () => {
    let squares = [];
    for (let i = 0; i < this.state.squares; i++) {
        squares.push(<Square color={this.props.color} key={i} />);
    }
    console.log(this.props.color)
    return squares;
  }

Where color passed by props through here:

<SquaresContainer color={this.generateRandomColor()} />


text:
Q: Will relationship be removed by setting the foreign key to 0? In Entity Framework, will the following code remove a relationship by setting the foreign key to 0?
entity.relationEntityID = 0;

A: It will search related entity with id equals 0, and return an error if will not find any, to remove relation you should make field nullable and set it to null.


text:
Q: Não foi possível localizar o arquivo 'c:\ ... \bin\roslyn\csc.exe' Segue imagem:

Fui atualizar Microsoft.CodeDom.Providers.DotNetCompilerPlatform com a versão mais recente e estável. Então atualizei 1.0.5 para 1.0.6.

Ele não estava mais assim. Agora fica dando esse problema.


text:
Q: Why do some people need low-contrast themes? Everyone is familiar with the high-contrast themes that are created for people with poor eye-sight. Because of the high contrast it is easier to see what is on the screen.
However, I heard there are also low-contrast themes. Could someone give some examples, but most importantly, could someone explain why there are low-contrast themes and who are helped by it?

A: In an attempt to answer your question, low-contrast themes have the advantage of being simpler and cleaner. Even though its harder to identify what's on the screen, some people find that low contrast themes are less shocking than high contrast ones.
I find low contrast themes useful when using the computer in a dark room, for example, because I don't have light reflecting on the screen. I hope it answers at least part of the question.

A: I have had to install a (Windows) PC for somebody who needed low contrast themes in a previous job.  This woman could only see "light" and no colours, and had low vision in general.  (I think she said she had no cone cells or something like that, but it's been 2 years).  She used a low contrast theme in Windows that used 2 shades of blue.
She described looking at a screen with high contrast (e.g. black on white or white on black text) as "looking straight into a spotlight and trying to see/read something that's written on it".
At least one other almost blind person told me it was the same or similar for him (but his eyesight is so bad now that he does everything with a braille reader & TTS anyway—he also uses the console most of the time).
BTW: I think it's possible to use compiz filters to show "low contrast" & "high contrast" versions of a normal display, but I don't know how well that works in practice?


text:
Q: Why passing df column not work when user function contain boolean conditions? When I pass pd Series (e.g. df column) to user function without Boolean conditions then it works, otherwise fall with

error: The truth value of a Series is ambiguous. Use a.empty,
  a.bool(), a.item(), a.any() or a.all()

Sorry, new to Python, so can't get why in one case it processes element-wise but in case of Boolean - like array.
df = pd.DataFrame({'A' : ['football', 'football',
'tennis','tennis','tennis'],
                   'B' : ['MESSI', 'ROONEY', 'FEDERER','NADAL', 'FEDERER'],
                   'C' : [5,4,6,5,6],
                   'D' : np.random.randn(5),
                   'E' : [1,2,4,3,5],
                   'F' : [1,0,1,0,1]
                  })
def diffs(E, F):
    vals = E - F
    return vals

This work:
df.loc[:, 'asd'] =  pd.Series(diffs(df.loc[:,'E'],df.loc[:,'F']),
index=df.index)

And this code fall:
def peak_rate(E, F):
    if E > 0:
        vals = 1
    else:
        vals = 0
    return vals

df.loc[:, 'asd'] =  pd.Series(peak_rate(df.loc[:,'E'],df.loc[:,'F']),
index=df.index)

A: It's because, in the first case, it's just subtraction and two arrays or series can be added/subtracted/multiplied and output will still be a series. You can't do that for greater than or less than equations. Here's an alternate solution:
def peak_rate(E, F):
    if E > F:
        return 1
    else:
        return 0

df.loc[:, 'asd'] =  pd.Series([peak_rate(df["E"][i],df["F"][i]) for i in range(len(df))], index=df.index)

Or you don't even need the function peak_rate. You can write it like below (I'm guessing you meant E > F instead of E > 0 in peak_rate. In case it was E > 0, just replace df["F"][i] with 0)
df.loc[:, 'asd'] =  pd.Series([int(df["E"][i]>df["F"][i]) for i in range(len(df))], index=df.index)

A: the line:
if E > 0:

E (a.k.a df.loc[:,'E']) is a pd.Series and checks whether it's greater then 0
you can't check a whole series if it's greater then 0
what you can do is to use:
if E.all() > 0:

maybe you got confused with 'E' and E


text:
Q: Is there a specific drawing order in PCL? I am trying to write a PCL document, which has several drawing objects (lines, rectangles, texts...)
I found that if I draw the rectangles before anything else, they appear in the right position and size. However, if I draw them among the rest of objects, they are drawn smaller and in the wrong place.
The PCL seems to be OK (although this is yet to be proven), but it has made me think that perhaps graphic objects must be drawn in a particular order (I am using HPGL/2, by the way).
Does someone know if this is so? I have not been able to find anything in the PCL Manual nor in the internet (which leads me to believe that there is not such drawing order).

A: Perhaps you have written position or scale commands that unintentionally affect your rectangles.


text:
Q: Why did this model still need calling 'build()' firstly when I have defined parameters? I have defined a image, img_shape , its shape is (28,28,1) before this model,
def make_discriminator(img_shape):
    return keras.Sequential([
        keras.layers.Dropout(0.3),
        keras.layers.Conv2D(32, 5, strides = 2,
                            padding='same',
                            input_shape = img_shape,
                            use_bias = False),
        keras.layers.BatchNormalization(),
        keras.layers.LeakyReLU(),
        keras.layers.Conv2D(64, 5, strides = 2,
                            padding = 'same',
                            use_bias = False),
        keras.layers.BatchNormalization(),
        keras.layers.LeakyReLU(),
        keras.layers.Flatten(),
        keras.layers.Dense(1)
    ], "Discriminator")

Then I tried to directly use it as input and print the structure of this model,
D = make_discriminator(img_shape = img_shape)
print(D.summary())

However, it shows

This model has not yet been built. Build the model first by calling
build() or by calling the model on a batch of data.

But when I tried to add build() before summary,
D = make_discriminator(img_shape = img_shape)

it shows

build() got an unexpected keyword argument 'img_shape'

I dont know how to solve this problem...and the process of creating image is below,
import keras
import tensorflow as tf
import tensorflow_datasets as tfds

fmist = tfds.load('fashion_mnist')
def process(data):
    img = tf.cast(data['image'], tf.float32)
    lab = data['label']
    img = (img / 255.0 - 0.5) * 2.0
    return img

BATCH_SIZE = 256
train = fmist['train'].shuffle(10000).batch(BATCH_SIZE).\
    map(process).prefetch(tf.data.experimental.AUTOTUNE)
img_shape = tf.data.experimental.get_structure(train).shape[1:]
print("image shape:", img_shape)

A: Try discriminator.build(input_shape=(1, 28, 28, 1)):
def make_discriminator(img_shape):
    return tf.keras.Sequential([
        tf.keras.layers.Dropout(0.3),
        tf.keras.layers.Conv2D(32, 5, strides = 2,
                            padding='same',
                            input_shape = img_shape,
                            use_bias = False),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.LeakyReLU(),
        tf.keras.layers.Conv2D(64, 5, strides = 2,
                            padding = 'same',
                            use_bias = False),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.LeakyReLU(),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(1)
    ], "Discriminator")

discriminator = make_discriminator((28, 28, 1))
discriminator.build(input_shape=(1, 28, 28, 1))
print(discriminator.summary())

Or set the input_shape in the first layer of your model. Then, the remaining output shapes will be inferred and you do not have to call model.build():
def make_discriminator(img_shape):
    return tf.keras.Sequential([
        tf.keras.layers.Dropout(0.3, input_shape = img_shape),
        tf.keras.layers.Conv2D(32, 5, strides = 2,
                            padding='same',
                            use_bias = False),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.LeakyReLU(),
        tf.keras.layers.Conv2D(64, 5, strides = 2,
                            padding = 'same',
                            use_bias = False),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.LeakyReLU(),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(1)
    ], "Discriminator")

discriminator = make_discriminator((28, 28, 1))
print(discriminator.summary())


text:
Q: Interoperability of OSGI and JPA in a JEE environment We are in the process of deciding whether to use OSGI or not. It is a manifold decision however I have the specific question regarding the interoperability between OSGI and JPA. I read that there are several  problems with the combination of both. A detailed description of the issues is described in the presentation of Mike Keith or here.

Persistence was another challenging issue. JPA with OSGI required us
  doubling all classes that were to be used across bundles. This forced
  us to use interfaces for all entities, as their classes would be
  different. The main problem here was for the developers to write the
  correct code and to maintain the configuration files. Methods like
  hashCode and equals usually need to be rewritten which might be
  non-trivial if inheritance is used for entities that exist in multiple
  bundles.

Also I found one unanswered post on SO which described it like this:

I just wanted to give an idea why you do not get any answers to this
  question. Several years ago, I implemented the JPA chapter of OSGi EE
  spec. I really wanted to support JPA within OSGi. The thing is, they
  are not compatible. There are issues with every technology within OSGi
  that use weaving, bytecode manipulation, interceptors or other tricks.
  You must decide, either these technologies or OSGi otherwise you will
  spend your precious time on issues like this. There used to be many
  developers, who wanted to support JPA, but they disappeared, too. I
  guess, they moved forward, too.

We use JEE 7 on JBOSS with EJBs, JPA (Hibernate), CDI and an Oracle database. We are not able to switch the database, the JPA provider or the persistence technology (JPA).

A: Not sure how well this works on JBOSS but JPA works quite well when using Aries JPA as the adapter to the OSGi specifics. The best way to use it is in Apache Karaf as it is all prepared already. So you just need to install some features.
See this for an example of using Aries JPA with declarative services and blueprint.
The examples show solutions to the problems mentioned in the slides above.

*

*upward dependencies: Entity classes are auto detected but all Entities for a persistence unit must be in one bundle. I do notknow of any duplication needed.

*weaving: Uses hibernate proxy based weaving. Also supports compile time and load time weaving. Aries JPA takes care of weaving on bundle loading. So it happens before the application can access the classes.

*jdbc: Uses pax-jdbc-config to automatically create XA ready, pooled DataSources without classloader tricks

*JPA specification: This is solved by the OSGi JPA spec which defines how to find and sue PersistenceProviders. All current providers support this.

I saw the hint about buddy classloader .. do not use it. It will make your code non portable and more difficult to understand.
So I would say all problems with JPA in OSGi are already solved. Still JPA is much more complicated than it seems. So even though JPA works well in OSGi there are very good reasons to use a simpler persistence technology.


text:
Q: DAO. JDBC. Where to place Connection object? Where must be placed Connection object in DAO design pattern?
Do I need to create separate class (e.g. DaoManager) with 2 methods: open() and close()? And in business logic do like:
DaoManager.open();
PersonDao personDao = DaoFactory.getPersonDao();
Person person = personDao.getById(personId);
.... //more DAO operations
DaoManager.close()

A: The connection should be a local variable of the PersonDao.getById() method (and of the other DAO methods). It should get the connection from a DataSource, use it, and close it in a finally block.
If you told a bit more about your environment (Spring, EJB container?), I could give more explanations.

A: In a large application you would typically hold the connections in a connection pool so that they can be reused for several purposes. One does this because opening a new DB connection can be somewhat expensive.
The DAO gets a reference to the pool and takes out a connection when it is needed. After the operation it would give it back to the pool.
There are several open source implementations for connection pools available, you may want to reuse one of these.


text:
Q: Como capturar sons no Android Studio? Tudo bem??
Gostaria de saber se tem alguma função no Android Studio para capturar os sons do ambiente pelo microfone do celular. Estou tentando implementar uma função de comando de voz sem ser necessário clicar em algum botão.


text:
Q: SUMIFS formula doesn't work This is a simplified example of my problem:
SUMIFs formula
I have two columns: category and hours. I want to find the sum of hours for A and C. The answer should be 5.1, but it shows 0. If I use SUMIF formula just for A or C, then it works, but if I use it for both A and C, it shows 0. What am I doing wrong?

A: For SUMIFS to work all of the criteria should be met, therefore you're saying SUM if Column A is equal to A and C and none of the columns meets it. You can try:
SUM(SUMIFS(B2:B7,A2:A7,{D2,D3})) or SUMIFS(B2:B7,A2:A7,D2)+SUMIFS(B2:B7,A2:A7,D3)


text:
Q: How to get the name of the running script without the extension I am interested in getting the name of the running script without the .pl
This: my ($script) = $0 =~ /(.*)\.pl/; seems to work. I was wondering if there is another more standard way for this

A: Use fileparse from File::Basename. This is a core module so it's always available to your distribution.
use File::Basename;
my ( $name, $path, $suffix ) = fileparse( $0, qr{\.[^.]*$} );
print "NAME=$name\n";
print "PATH=$path\n";
print "SFFX=$suffix\n";

The regular expression to find the suffix looks for a dot, followed by anything that isn't a dot, zero or more times, anchored to the end of the string.
If the running script was/mypath/myfile.pl this returns:
NAME=myfile
PATH=/mypath/
SFFX=.pl

A: the scriptname is in
print $0;

like you wrote..
if you want to have only the name without .pl
-i- would do this:
my $script = $0;
$script =~ s/\.pl//;

i dont think that here is any performance issue to choose this or that one ;)
see perlvar

A: the last example is if you run the program without the path. But from crontab
    /path/to/dir/script.pl
my $script = $0;
$script =~ s/\.pl//;

will give you
 /path/to/dir/script


text:
Q: How to make R not consider NA values when using table function in R? So let's say I have two factor variables:
a  <- factor(c(1,2,3,NA))
b  <- factor(c(3,4,5))

Them have different length, and I cannot use the table() function. Is there any argument in table function that I can use to not consider the NA value in variable a? I tried useNA = "no" and turns out it is for entirely different purpose.


text:
Q: How to get a bar with colors on top of a plot? I have an R plot with lines. Each sections belong to a category defined by p. I tried coloring the plot with rectangles, but the results is messy. Instead of getting rectangles amid the plot then, I would like to get a thin bar on top. Is it possible to do this in R without messing the other features of the plot?
v <- c(7,12,28,3,41)
x <- c(1,2,3,4,5)
y <- c(1,2,5,6,7)
p <- c(1,2,1,1,2)
data <- data.frame(v,x,y,p)

par(mar=c(5,5,2,5))
with(data, plot(v, type="l",col="black",ylab="scale_1"))
par(new=T)
with(data, plot(y, type="l", axes=F, xlab=NA, ylab=NA,col="blue"))
par(new=T)
axis(side=4)
mtext(side=4,line=3, 'scale_2' )
rect(data$x-0.5,min(data$y),data$x+0.5,max(data$y),col=adjustcolor(data$p,alpha=0.5))

A: You would just need to set the y-coordinate for the bottom of the plot:
rect(data$x-0.5,
     max(data$y) - 1,  # New bottom coordinate
     data$x+0.5,
     max(data$y),
     col=adjustcolor(data$p,alpha=0.5))

Output:

Or if you want the rectangles fully separated from the lines:
rect(data$x-0.5,
     max(data$y),
     data$x+0.5,
     max(data$y) + 1,
     col=adjustcolor(data$p,alpha=0.5))


text:
Q: STI in Rails: How do I change from a superclass to a subclass without accessing the "type" attribute directly? So, I have the following:
class Product < ActiveRecord::Base
  # Has a bunch of common stuff about assembly hierarchy, etc
end

class SpecializedProduct < Product
  # Has some special stuff that a "Product" can not do!
end

There's a manufacturing and assembly process in which data is captured about Products. At the time of capture the eventual product type is not known. after the Product record has been created in the database (perhaps days later) it may be necessary to turn that product into a specialized product and fill in the additional information. Not all products will become specialized, however.
I've been trying to use the following:
object_to_change = Product.find(params[:id])
object_to_change.becomes SpecializedProduct
object_to_change.save

Then, when I do a SpecializedProduct.all the resulting set does not include object_to_change. Instead object_to_change is still listed in the database as Product
UPDATE "products" SET "type" = ?, "updated_at" = ? WHERE "products"."type" IN ('SpecializedProduct') AND "products"."id" = 30  [["type", "Product"], ["updated_at", Fri, 17 May 2013 10:28:06 UTC +00:00]]

So, after the call to .becomes SpecializedProduct the .save method is now using the right type, but it's not able to update the record because the WHERE clause of the update is too specific.
Do I really need to access the type attribute of the model directly? I'd really rather not.

A: Looking at the source of becomes and becomes!, it doesn't mutate the original object. You need to assign it to a new variable:
some_product = Product.find(params[:id])
specialized_product = some_product.becomes SpecializedProduct
specialized_product.save

Not sure how this will handle the primary key of the record, though, so you may need to do some additional finagling to make sure your relations don't get mangled.

A: You just need the bang version of the becomes method with (!) and save.
The difference between the two methods: becomes creates a new instance of the new class with all the same attribute values of the original object.  becomes! also updates the type column.
object_to_change = Product.find(params[:id])
object_to_change.becomes! SpecializedProduct
object_to_change.save

A: I think no! Check the sorces of becomes and becomes! methods!
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb#L199
Looks like you need to use becomes! because it is wrapper around becomes that also changes the instance's sti column value.
UPD: https://github.com/rails/rails/blob/4-0-stable/activerecord/test/cases/persistence_test.rb#L279
This is a test case for your code.
UPD2:
I think you can try to create another class sort of DefaultProject which is subclass of Project and then you can change each from DefaultProject to SpecializedProduct  and vice versa

A: I have a similar issue where I want to change from one subclass to another.  Unfortunately Rails doesn't do this gracefully because it wants to limit the save with a "where type='NewSubclass'". ie:
UPDATE parents SET type='NewSubclass' WHERE type IN 'NewSubclass' AND id=1234

Digging into rails, it appears that the method in ActiveRecord's lib/active_record/inheritance.rb named "finder_needs_type_condition?" is called and the caller isn't smart enough to realize you are changing the type field so it obviously isn't already that value.
I "resolved" this in a round about way.  I used the ActiveRecord core as a basis for how to load an instance of whichever class I want with attributes and save it without having to go through the full ActiveRecord find stack.
old_instance = Parent.find(id) #returns OldSubclass instance
tmp = Parent.allocate.init_with('attributes' => old_instance.attributes)
tmp.type = 'NewSubclass'
tmp.save
Parent.find(id) #returns NewSubclass instance

It's real ugly and I hate it.  Hopefully someone will think about fixing this in ActiveRecord.  I believe it would be useful for objects to change subclasses in STI over time.  I have a single table with 5 subclasses because it cleans up the model quite a bit.
This is the only ugliness I had to live with.  Be sure to write proper tests so that when ActiveRecord breaks this "workaround" you can detect it.


text:
Q: Editing certain space in a line using Regular Expression Hello I have the txt file list:
asjd
gsgs
azda

I want to edit the 2nd spot on the line so it is such:
a-jd
g-gs
a-da

I have tried playing around with the \S reg expression but I am struggling. This is out of my knowledge. Thanks in advance.

A: Try the following find and replace, in regex mode:
Find:    ^(.).(.*)$
Replace: $1-$2

Demo


text:
Q: DescribeSObjectResult missing fields when executed in managed package Problem Description
Not being able to use both custom and managed fields in a managed package when fields share the same API name (with different namespaces). When using the DescribeSObjectResult.fields.getMap() method, it only returns the local custom field (and not both the local custom field and the managed field).
Expected Result
Map of with both the local custom field (e.g. Description__c) and managed field (e.g. namespace__Description__c) returned by the DescribeSObjectResult.fields.getMap() method.
Current Result
Only local custom fields are returned (e.g. Description__c).
Using Salesforce API version 29.0
How to reproduce

*

*Create a custom object / custom field (e.g. namespace__Object__c.namespace__Description__c) and upload the managed package.

*Install the managed package in a different organization (e.g. a developer edition organization)

*In the custom object namespace__Object__c add a new custom field named Description__c (therefore it doesn't have a namespace)

*Run the following code from the managed package

(You can/should embed it in a VF page / custom Apex controller for easy access):
Schema.DescribeSObjectResult dsr = Schema.getGlobalDescribe().get('zqu__Quote__c').getDescribe();
Map objectFields = dsr.fields.getMap();
for (String fieldName : objectFields.keySet()) {
    Schema.DescribeFieldResult dfr = objectFields.get(fieldName).getDescribe();
    System.debug(dfr.getName() + ' >> ' + dfr.getLabel());
}

When running in the managed package, this code will only return the customer local Description__c custom field.
However, when running this code from the Developer Console in the local namespace, this code will return both Description__c and zqu__Description__c fields.

A: The way I read this line in the docs, that is expected behavior:

For example, if the code block that generates the map is in namespace
  N1, and a field is also in N1, the key in the map is represented as
  MyField_c. However, if the code block is in namespace N1, and the
  field is in namespace N2, the key is N2_MyField__c.

So if you are running the code within your namespace, the key is created without the namespace prefix. Since a field created directly in the target Org won't have a namespace either, when the map is generated it will only have one reference to that api name in the map. The only way I can see to avoid that is to add a prefix to the API name for your fields in addition to the namespace, so any custom fields in your package will still be identifiable. Defeats the objective of a namespace, but based on the docs, not sure what else you can do?


text:
Q: Weird Camera Iris Shutter Animation I'm seeing a weird animation of the camera iris when I present a UIImagePickerController in a UIPopoverController with the following code:
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[popover setContentViewController:imagePicker animated:YES];

I should also mention that the UIPopoverController is already presented with another content view controller at this point and thus the call to setContentViewController is changing the popover's content to the image picker.
This is what is looks like when the image picker is shown:

What is going on here?

A: After months of stewing over this, I came up with the solution!
The unsightly black bar below the shutter animation has to do with the fact that the UIPopoverController has a UINavigationController as it's content view controller before  setting the UIImagePickerController as the content view controller. The height of the black bar is the same height as the navigation bar of the UINavigationController.
Anyways, the solution was to set the popover content size to [imagePicker contentSizeForViewInPopover] before I set the UIPopoverController's content view controller to the UIImagePickerController.
Here's some code:
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[popover setPopoverContentSize:[imagePicker contentSizeForViewInPopover] animated:YES]
[popover setContentViewController:imagePicker animated:YES];

The key is this call right here:
[popover setPopoverContentSize:[imagePicker contentSizeForViewInPopover] animated:YES]


text:
Q: mysqli insert script no errors but not working i updated my code still not inserting , and i still need help :(
$reference=$_POST['reference'];
$description=$_POST['description'];
$marque=$_POST['marque'];
$quantite=$_POST['quantite'];
$type=$_POST['type'];
$id_s_equip=88;
$insert="insert into piece (design_piece, type, marque, qte, id_s_equip,description) VALUES ( ?,?,?,?,?,?)";
$stmt = mysqli_prepare($c, $insert);
mysqli_stmt_bind_param($stmt,'ssisis',$reference,$marque,$quantite,$type,
$id_s_equip,$description);
mysqli_stmt_execute($stmt);
print(mysqli_stmt_affected_rows($stmt));


text:
Q: R regular expression for data I have data such as Data<-("10/11/2021").
The only thing I want is to get the digits before 1st slash, digits before 2nd slash and digits after 3rd slash. Please help me do this with regex.

A: You could do this with several gsub functions.
gsub("/.*$","",Data)
#[1] "10"

gsub(".*/(.*)/.*","\\1",Data)
#[1] "11"

gsub('.*/', '', "10/11/2021")
#[1] "2021"

Or you can use strsplit.
strsplit(Data, "/")
#[[1]]
#[1] "10"   "11"   "2021"


text:
Q: How can I keep the order of an ordered hashtable after remote session? I invoke a scriptblock of a ServerObject in a remote session. In the scriptblock I create a hashtable and save it in the ServerObject. At the end of the scriptblock the order is correct, after the session the items are in the wrong order.
$Serv = New-Object -TypeName PSObject
$Serv | Add-Member -MemberType NoteProperty -Name Cn -Value Computername
$Serv | Add-Member -MemberType NoteProperty -Name Inf -Value ""

function getInf (){

  $Inf = [ordered]@{
    SiteConfig = "a";
    BrokerController = "b";
    AdminRoles = "c";
  }
  $Serv.Inf = $Inf
}

getInf

$ServResult = Invoke-Command -Cn $Serv.Cn -Credential $Cred -ScriptBlock {
  param($Serv)
  Invoke-Command  -ScriptBlock ([ScriptBlock]::Create($Serv.getInf))
  $Serv
}-ArgumentList $Serv
Remove-PSSession -ComputerName $Serv.Cn
$ServResult.Inf

A: Try this:
$Inf.GetEnumerator() | sort -Property name


text:
Q: Environment variables not work for IntelliJ IDEA HTTP client In IntelliJ IDEA, I want to define environment variables for HTTP client, here is the document, but IDEA cannot find my environment when I run a request.
what's wrong?
environment config picture
request config picture
IDEA version:
IntelliJ IDEA 2020.1.1 (Ultimate Edition)
Build #IU-201.7223.91, built on April 30, 2020

A: right click on http-client.env.json and "Override File Type" select JSON.
This helps me.

A: Make sure you don't have the env.json files located in the .idea folder: https://youtrack.jetbrains.com/issue/IDEA-239351


text:
Q: MYSQL - How to avoid primary id wastages? How to avoid skipping primary ids when inserting records through multiple load statements?
I inserted a file containing 150 records through LOAD statement into a table.
The last primary id in the table after insertion is 150.
Now, when I insert another file with 100 records through the load statement, the primary id assigned to the first record is 251 instead of 151.
How do I avoid these primary id wastage?
More information:
e.g:
mysql> desc test_data;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)     | NO   | UNI | NULL    |                |
| image      | varchar(255)     | NO   |     | NULL    |                |
| created_at | datetime         | NO   |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

My Load statement -
 LOAD DATA LOCAL INFILE '~/test_2.dat'
       INTO TABLE test_data
       FIELDS TERMINATED BY '|'
       LINES TERMINATED BY '\n'
       set created_at=CURRENT_TIMESTAMP;

Sample data in the file test_2.dat:
|Peter|peter.jpg
|sam|sam.jpg
|radnor|radnor.jpg
|bruce|bruce.jpg

This is the table structure after the load of that file.
mysql> show create table test_data;

| test_data | CREATE TABLE `test_data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 |

Now, the max(id) in this table is 4. But why is the AUTO_INCREMENT value now set to to "8"? Should it not be set to "5"?

A: You can mark the AUTO_INCREMENT to true on the primary id to skip them during load.
Some more info can help answer better.


text:
Q: Alternate form of Modus tollens applicable? The definition states that
not(q)
p--> q
----------
not(p)

Is the following form is also true?
(q)
not(p-)--> not(q)
----------
(p)

A: Yes, because "q"  is equivalent to "not(not q)", and "p" is equivalent to "not(not p)".


text:
Q: How to get workspace (document) path on Linux and Windows using commandline? I have a script which is copy the file source to user workspace when run the script. here i need to get current user workspace from commandline. Can you help me how to get it on both Windows and Linux
Thanks in advance - sri

A: What exactly do you mean by Workspace? If you mean the user's home directory, you can get this via the environment variable $HOME on Linux, and I think the equivalent on Windows would be %HOMESHARE% (not totally sure about the last one, because I am on a Domain computer with roaming profiles right now, and I'm not sure if there is any special setup on it.


text:
Q: Send and receive UDP packets to server on different network android I have looked all over for a solution to this problem, I have not come up with a solution that works.
Currently, I send and receive packets on my android device emulator using my loopback/localHost address. This proccess works successfuly, however when I try running the same code using my computer's public address the server never receives the packets.
private String hostName = "99.248.222.229";
//private String hostName = "10.0.2.2";
private InetAddress hostAddress;
@Override
protected void onCreate(Bundle savedInstanceState)
{

    CreateAddress addressGetter = new CreateAddress();
    try {
        hostAddress = addressGetter.execute(hostName).get();
    } catch(Exception e){
        e.printStackTrace();
    }

Button btnLock = (Button) findViewById(R.id.btnLock);
    btnLock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendReceiveTask = new runUdpClient();
            byte[] udpMsg = {(byte)housenumber, (byte)doornumber, LK_MSG, UNLOCK};
            System.out.println(hostAddress);
            sendPacket = new DatagramPacket(udpMsg, udpMsg.length, hostAddress, portnumber);
            DatagramPacket receivePacket = null;
            try {
                receivePacket = sendReceiveTask.execute(sendPacket).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            currentDoorState = (receivePacket.getData()[3]==UNLOCK);
            updateDoorStatus(currentDoorState);
            int doorNum = doornumber;
            eventArrayList.add(0, (getCurrentTimeStamp() + eventString.replace("doornum", Integer.toString(doorNum)))+ ((currentDoorState) ? "unlocked." : "locked."));
            adapter.notifyDataSetChanged();

        }
    });
}

private  class runUdpClient extends AsyncTask<DatagramPacket, Void, DatagramPacket>{

    @Override
    protected DatagramPacket doInBackground(DatagramPacket ...params){

        DatagramSocket ds = null;
        //SEND
        try {
            ds = new DatagramSocket();
            DatagramPacket dp;
            //dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), hostAddress, portnumber);
            dp = params[0];
            ds.send(dp);
        } catch (SocketException e) {
            e.printStackTrace();
        }catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //RECEIVE
        DatagramPacket incomingPacket = new DatagramPacket(new byte[100], 100);
        try {
            ds.setSoTimeout(1000);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        try {
            ds.receive(incomingPacket);
        } catch (IOException e){
            e.printStackTrace();
        }finally{
            if(ds != null) ds.close();
        }
        System.out.println("Packet recieved from server" + Arrays.toString(incomingPacket.getData()));
        return incomingPacket;
    }

}


text:
Q: iTunes Connect demo account in existing live database for app submittal? I'm submitting my first app through iTunes Connect. It is a social networking community so I have to provide a demo account for the submission. My app already has a live database of users as there is currently an active web version.
I'm new to this and confused as to how I should handle this. Should I be creating a demo account that will not show up in any other live user's search results? Are the testers going to be attempting to interact with other live users? I am assuming I will need to show the various functions of the app, like messaging and events. In that case should I be creating a few "demo" users for the testers to interact with?
Alternatively, should I be linking them to the development version and development database? If that's the case, then the build that I send them would only be a development build then?
I am confused on how this is supposed to work and can't seem to find any information to help?

A: In my experience, you'll need to give them the production version that will go into the store.  So not the development build.
When we submit an app for approval, it seems to get installed and activated on a couple of devices, but nothing much ever happens.  They barely use it, as far as we can tell.  We can tell that it's installed and run.  We have previously been rejected when the network connectivity wasn't working right, so we know that they do look at the app after it's installed.
I'd suggest you make them an account that looks relatively anonymous (or even "Test Account" which you real users are hardly likely to try to interact with).  You could create another account and say "If you want to send a message, send it to account xxxx".  We've never had them interact with our app enough to utilise the suggestions we've made.
If you have an active / inactive flag, you could think about making these accounts inactive once the app is approved, then re-activating it when you next want to submit your app.


text:
Q: Using @Transactional on actors class definition with Akka 2.X.X? I used to use Spring transaction annotation over my beans.
However, actors from Akka are reluctant.
Here's my code snippet in Scala:
@Service
@Transactional
@Scope("prototype")
class MyActor extends Actor with ActorLogging {

   def receive = {
     //......  throwing a NotInTransaction (no matter what the calling lib is)
   }
}

However, @Transactional works for all my other non-actor beans.
I added Java as tag since it is likely a similar issue with Akka for Java, I guess.
Did I miss something?
I'm pointing out I follow beforehand this technique (that I adapted in Scala) to make my actors creation aware of Spring:
http://www.typesafe.com/activator/template/akka-java-spring
UPDATE WITH AN EXAMPLE -----------
@Service("eventsListenerActor")
@Scope("prototype")
class EventsListenerActor @Autowired()(val eventRepository: EventRepository) extends Actor {

  def receive = {
    case RetrieveNewEvents =>
      val newEvents = eventRepository.findNewEvents(EventBatchSizeProperty)
  }

}

@Repository
class MyEventRepository extends EventRepository {

   @Transactional       //transactional annotation here
   def findNewEvents(batchSize: Int): List[Event] = {
    //................    code warning that transaction context is not present here !
  }
}

Any call to the findNewEvents outside an actor well builds the transaction context.
As I asked in comments below, may it be related to the actor and its way of threading?

A: Transaction tracking in application containers is based upon ThreadLocal variables, therefore it does not work with Actors. The clash is no coincidence, since having an actor take part in a larger transaction runs counter to the intention: actors shall share nothing and only communicate using messages. Two actors cannot ever be internally consistent without violating this rule.
The benefits of following this rule are plentiful: proper encapsulation, location transparency, painless distribution across CPUs or nodes, sane failure handling model.


text:
Q: keyval being picky about empty options I am trying to automate the generation of beamer handouts, with the help of \pgfpagesuselayout. I want them with 2 slides on 1 page, my colleagues with 4 in landscape orientation. So we generate both versions, by compiling the file with different jobnames and a conditional in our class that changes behaviour when the jobname contains -HANDOUT or -HANDOUT4. Note that \pgfpagesuselayout uses portrait by default, and does not have a portrait option, only landscape.
I initialise to 2 on 1 by default :
\str_const:Nn \g__chato_beamer_slides_per_page {2~on~1}
\str_const:Nn \g__chato_beamer_orientation {}

When the right circumstances arise, I change that to
\str_gset:Nn \g__chato_beamer_slides_per_page {4~on~1}
\str_gset:Nn \g__chato_beamer_orientation {landscape}

In the end, I say
\pgfpagesuselayout{\str_use:N\g__chato_beamer_slides_per_page}[a4paper,\str_use:N\g__chato_beamer_orientation,border~shrink=5mm]

In 4 on 1 mode, this works well. In 2 on 1 mode, I get
! Package keyval Error:  undefined.

It seems not happy with an empty option. So I tried integrating the a4paper part into the variable. But then, in 4 on 1 mode, I get
! Package keyval Error: a4paper,landscape undefined.

I know I could work around that, by having a conditional to make separate calls to \pgfpageuselayout, or by reverting to my first solution but setting
\str_const:Nn \g__chato_beamer_orientation {a4paper}

(I get no complains about the repeated a4paper option)
However, does anyone understand why keyval seems so picky ? What is going wrong, specifically, with my a4paper,landscape option ? Is this a bug ?

A: keyval is so picky, because it tests for emptiness by using
  \KV@@sp@def\@tempa{#1}%
  \ifx\@tempa\@empty\else

and in case of your \str_use:N \g__chato_beamer_orientation this isn't \@empty. Then it uses the contents of the key in \csname (which will try to build a key with an empty name, since your \g__chato_beamer_orientation is empty) and tests whether the result is \relax, if that's the case (it is, the empty key name isn't defined) you get an undefined key error via \PackageError which fully expands \@tempa and hence also your \str_use:N, and you see the empty message.
To store multiple keys and values inside of your macros (or none, in fact, everything different from a single key without a value) you need to expand your strings before keyval does its parsing. That can be done with \use:e for instance (expl3's \exp_args:N... is not really applicable for you because of the optional argument). So the following should work (but obviously I couldn't test it, you show no compilable example):
\use:e
  {
    \exp_not:n { \pgfpagesuselayout }
      { \g__chato_beamer_slides_per_page }
      [ a4paper, \g__chato_beamer_orientation, border~shrink=5mm ]
  }

Note that for strings you can omit \str_use:N if you want to.


text:
Q: Ubuntu Linux Mono Errors I'm getting alot of errors. I'm getting these errors while trying to compile my program using the DMCS compiler. Any help is appreciated!
The command:
 dmcs -recurse:'*/*.cs' -r:mysql.data.dll -r:Newtonsoft.Json.dll

These are errors:
Unhandled Exception: System.ArgumentException: Path is invalid
Parameter name: path
  at System.IO.Directory.ValidateDirectoryListing (System.String path, System.String searchPattern, System.Boolean& stop) [0x00000] in <filename unknown>:0
  at System.IO.Directory.GetFileSystemEntries (System.String path, System.String searchPattern, FileAttributes mask, FileAttributes attrs) [0x00000] in <filename unknown>:0
  at System.IO.Directory.GetFiles (System.String path, System.String searchPattern) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.ProcessSourceFiles (System.String spec, Boolean recurse) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.CSCParseOption (System.String option, System.String[]& args) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.ParseArguments (System.String[] args, Boolean require_files, System.Func`3 unknown_option_parser) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.Create (System.String[] args, Boolean require_files, System.Func`3 unknown_option_parser, Mono.CSharp.ReportPrinter printer) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentException: Path is invalid
Parameter name: path
  at System.IO.Directory.ValidateDirectoryListing (System.String path, System.String searchPattern, System.Boolean& stop) [0x00000] in <filename unknown>:0
  at System.IO.Directory.GetFileSystemEntries (System.String path, System.String searchPattern, FileAttributes mask, FileAttributes attrs) [0x00000] in <filename unknown>:0
  at System.IO.Directory.GetFiles (System.String path, System.String searchPattern) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.ProcessSourceFiles (System.String spec, Boolean recurse) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.CSCParseOption (System.String option, System.String[]& args) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.ParseArguments (System.String[] args, Boolean require_files, System.Func`3 unknown_option_parser) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.Create (System.String[] args, Boolean require_files, System.Func`3 unknown_option_parser, Mono.CSharp.ReportPrinter printer) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0

A: Maybe your compiler don't understand the -recurse. Try to get that expanded by the invoking shell:
  dmcs **/*.cs -r:mysql.data.dll -r:Newtonsoft.Json.dll

might work with a recent bash (version 4) or a zsh; otherwise try
  dmcs $(find -type f -name '*.cs') \
     -r:mysql.data.dll -r:Newtonsoft.Json.dll


text:
Q: POST transmission of file fails with UWP Trouble
I'd like to send the value and file POST from the UWP application (C #) to the API created in PHP, but it seems that the file can not be sent.

*

*param1 is StringValue.

*param2 is UploadFile.

Excerpt of sample.php
if($_FILES['param2'])

UWP (Failed. $_FILES['param2'] false)
private async Task PostSample()
{
    const string POST_URL = "http://xxx.xxx.xxx.xxx/api/sample.php";

    var multi = new HttpMultipartFormDataContent();

    var param1 = new HttpStringContent("foo");
    multi.Add(param1, "param1");

    byte[] values = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
    var param2 = new HttpStreamContent(new MemoryStream(values).AsInputStream());
    param2.Headers.ContentDisposition = new Windows.Web.Http.Headers.HttpContentDispositionHeaderValue("form-data")
    {
        Name = "param2",
        FileName = "piyo.dat"
    };
    multi.Add(param2);

    var client = new HttpClient();
    var res = await client.PostAsync(new Uri(POST_URL), multi);

    var diag = new MessageDialog(res.ToString());
    await diag.ShowAsync();
}

What I tried
External Tool
In the Advanced REST Client by GoogleChrome, it succeeded
Windows Forms (Successed)
It succeeded on Windows Forms.
private async Task PostSample()
{
    const string POST_URL = "http://xxx.xxx.xxx.xxx/api/sample.php";

    var multi = new MultipartFormDataContent();

    var param1 = new StringContent("foo");
    multi.Add(param1, "param1");

    byte[] values = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
    var param2 = new StreamContent(new MemoryStream(values));
    param2.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
    {
        Name = "param2",
        FileName = "piyo.dat"
    };
    multi.Add(param2);

    var client = new HttpClient();
    var res = await client.PostAsync(POST_URL, multi);
    MessageBox.Show(res.ToString());
}

Guess
Is my UWP code incorrect or can not be sent on UWP?
Thank you.