text:
Q: Run shell command from JavaScript in node-webkit? Is there any way to run shell command from JavaScript in node-webkit?
There is a lot of similar questions, but it didn't help me.
I'm trying to build simple desktop app for listing installed tools.
I've created node module 'tools-v' which is installed globally and works when I run it in command line.
This module run several commands: npm -v, node -v, git -v etc.
I'm on Windows 7.
//var sys = require('sys');
var exec = require('child_process').exec;
//var toolsv = (process.platform === "win32" ? "tools-v.cmd" : "tools-v");
$(document).ready(function() {
    //myCmd = "C:\\Users\\win7\\AppData\\Roaming\\npm\\tools-v.cmd";
    //myCmd = toolsv;
    myCmd = 'tools-v';
    //gui.Shell.openItem('firefox',function(error, stdout, stderr) { });
    //opening Firefox works.
    exec(myCmd,  function (error, stdout, stderr) {
        //detached: true;
        console.log('stdout: ' + stdout);
        $('#output').append('stdout: ' + stdout)
        if (error !== null) {
          console.log('exec error: ' + error);
        }
    });
});

I'm always getting error:
""exec error: Error: spawn ENOENT""
I tried spawn instead of exec. I also tried several other commands, beside node module.
Thanks.

A: Actually, this code works. I just didn't built full app, I tested it trough sublime build for node-webkit. Preforming full build with grunt solved every spawn issues.


text:
Q: pandas isin append unhashable type: 'list' error I ran out of idea on how to add new items to filter list in pandas.
Example:
OldProducts = ProductInfo[ProductInfo['MerchantID'].isin(['A store', 'B store'])]

OldProductsId = list(OldProducts.PID.unique())

OldProductsId2 = ['VayjE7nrDl', 'BYbcAAuV0r', 'hu2y8rYIbN', 'YXELEovcwK']

OldProductsId.append(OldProductsId2)

DetailProductInfo = DetailProductInfo [~DetailProductInfo ['PID'].isin(OldProductsId)]

The error is like this:
TypeError: unhashable type: 'list'

A: You've appended OIdProductsId2 to OldProductsId, so now OldProductsId is a list of (presumably) strings plus a list object. So to correct your code change this line:
OldProductsId.append(OldProductsId2)

To:
OldProductsId.extend(OldProductsId2)

And the error should disappear.

A: The append method will add the item you pass as another item in the list. If that item happens to be another list then the final element in your list will be the OldProductsId2 list. Use extend instead.
Change OldProductsId.append(OldProductsId2) to OldProductsId.extend(OldProductsId2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Help understanding past perfect with continuous I am learning the past perfect/continuous and I have just read that we generally use it when we are saying in our tenses a form of time/date who highlight the importance of the past.
In this case, I was wondering if we could say this:

Last day, when I had been yelled at you, the cake was burning in the oven.

The "Last day" is a mark of the past form, so we need to use the past perfect, in addition of the continuous. Is it true ?

A: Past perfect tense shows an action that happened in the past, but was still going on at that moment in time. Continuous indicates that something is going on right now. You should either stick with present continuous, or past perfect, not one or the other.

A: "Yesterday, after I had been yelled at by you, the cake was burning" is a very awkward and odd sentence, but it is grammatical. The past perfect indicates that something started and ended before some other occurrence in the past. (The other occurrence may be explicitly mentioned or just implied.) The past progressive indicates that something had started but not ended before some other occurrence in the past. A situation where both tenses are appropriate in the same sentence is conceivable but certainly very rare.
Please give an example from your text so that we can help you understand it.


text:
Q: Error in running react-native run-ios on Command Line I was working on my React Native project. When I tried to run the ios using this command react-native run-ios I'm getting this error (See below).
error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening *.xcworkspace

** BUILD FAILED **

The following build commands failed:
    CompileC /****/ios/build/SykesPHMobile/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/DoubleConversion.build/Objects-normal/x86_64/fixed-dtoa.o /****/ios/Pods/DoubleConversion/double-conversion/fixed-dtoa.cc normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
    CompileC /****/ios/build/SykesPHMobile/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/DoubleConversion.build/Objects-normal/x86_64/strtod.o /****/ios/Pods/DoubleConversion/double-conversion/strtod.cc normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
    CompileC /****/ios/build/SykesPHMobile/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/DoubleConversion.build/Objects-normal/x86_64/double-conversion.o /****/ios/Pods/DoubleConversion/double-conversion/double-conversion.cc normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
    CompileC /****/ios/build/SykesPHMobile/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/DoubleConversion.build/Objects-normal/x86_64/fast-dtoa.o /****/ios/Pods/DoubleConversion/double-conversion/fast-dtoa.cc normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
(4 failures)

However when I run and build the ios project in Xcode directly there's no error I encountered it run successfully the project in simulator. Here's the details of my react native cli
System:
    OS: macOS 10.15.2
    CPU: (4) x64 Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
    Memory: 165.61 MB / 8.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 10.15.1 - /usr/local/bin/node
    npm: 6.13.1 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1
  IDEs:
    Android Studio: 2.3 AI-162.4069837
    Xcode: 11.2/11B52 - /usr/bin/xcodebuild
  npmPackages:
    react: 16.9.0 => 16.9.0
    react-native: 0.61.5 => 0.61.5
  npmGlobalPackages:
    create-react-native-app: 1.0.0
    react-native-cli: 2.0.1

I already tried the following solution below.

*

*Delete the Pod folder inside ios and reinstall again.

*Remove the build folder then run react-native run-ios

*Clean my local cache in Cocoapods and perform the steps one again. Same error that I encountered.

Any ideas how to solve this error.

A: *

*delete ios/build

*watchman watch-del-all

*rm -rf /tmp/haste-map-react-native-packager-* rm

*-rf /tmp/metro-bundler-cache-*

A: Removing spaces in my project name resolved this issues. I will mark as answered the question above.


text: Q: Crop part of screen share WebRTC I am developing a screen share web application where I should be able to crop area of screen to share with other users. I got this url (https://www.webrtc-experiment.com/RTCMultiConnection/cropped-screen-sharing.html#21705984193804362) working but frames per second with this example are very low. Is there any solution to make it work well ?


text:
Q: Compare products in Virtuemart I am doing compare page in virtuemart. I want to modify joomla\components\com_virtuemart\views\category\tmpl\default.php file in this way:
<?php

include ("/includes/compare.php");

$con=mysqli_connect("localhost","root","","auto2");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM auto_virtuemart_products");
?>

Value1

<?php
while($row = mysqli_fetch_array($result)) {
?>

<?php echo $row['product_sku']; ?>

<form action="compare.php" method="get">
<input type="checkbox" name="send1[]" value="<?php echo $row?>" />

<?php
}
mysqli_close($con);
?>

And then I add compare.php to includes folder:
 <?php
   $con=mysqli_connect("localhost","root","","auto2");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  if ( isset($_GET['send1']) ) {
        $compare1 = $_GET['send1'];

 if (isset($_GET['Submit'])) {
   for ($i=0; $i<sizeof($compare1);$i++) {

   $result = mysqli_query($con,"SELECT * FROM auto_virtuemart_products WHERE '$compare1[$i]' LIKE product_sku");

   while($row = mysqli_fetch_array($result))
  {
  echo $row['product_sku'] . " " . $row['product_weight'];
  echo "
";
  }

   }
    }
    else {
    echo ("error");
    }
    }
   ?>

Everything is functional, but when I click on button Submit the next error is occured:
An error has occurred.
The requested page cannot be found.
404 Article not found
I expect that problem is, that joomla will not show another page if it is not defined as article.
Please do not solve security issues, I know about them and I will solve them later. Now I have it launched just on localhost.
Please could you advice me, how can I solve this problem?
Thank you very much

A: Why you are using external page and submit like normal forms.
Joomla & VM are  MVC  so use that features. Also do not use mysql functions like this, use Joomla DB object.
I think you can work like this way,
The compare product is VM related option so create a view inside your VM component(Assume VM2.x) Just create related controller and model for your new view.
the view have facility to add new layout so your compare form should be layout.
and your form have something like below.
on your form action
index.php?option=com_virtuemart&controller=yourcontroller&task=yourtask

the task is the function inside your controller.
this can  be include like below method (insted of using form action).
<input type="hidden" value="com_virtuemart" name="option">
<input type="hidden" value="yourcontroller.yourtask" name="task">.

Also in your model you can use DB object like below.
$db = JFactory::getDBO();
$sql= "your sql query";
$db->setQuery($sql);
$db->query();//This may changed based on Joomla versions.

Hope its helps.. try to follow Joomla and VM standard.


text:
Q: variables that can store vulgar fractions in c, or another approach to a code that solve systems of equations I am a first year computer engineering student trying to make a calculator that solves systems of equations with multiple unknown variables using Gaussian-Jordan elimination
my algorithm is to put the equations in 2 dimensional array (matrix) and make the computer apply elementary operation rows by
1- reorganizing the equations so the ones that starts with zeros be in the bottom
2- making all diagonal elements = 1 by dividing every row on the value of its diagonal element element11 element22 and so on
3- eliminating the elements up and down the diagonal to make an echelon form
the answers should be the last column.
here is my code
     #include<stdio.h>
     int input;
     int rows;
      int columns;
     float matrix[100][100];
      int true =1;

  void interchange(curr,alter){
  float row_X[columns];
  float row_Y[columns];
  int k;
   for(k=0;k<columns;k++){
    row_X[k]=matrix[curr][k];
  }
 for(k=0;k<columns;k++){
    row_Y[k]=matrix[alter][k];
 }
 for(k=0;k<columns;k++){
    matrix[curr][k]=row_Y[k];
 }
 for(k=0;k<columns;k++){
    matrix[alter][k]=row_X[k];
}
}

void order(){
int e;
int count;
count = 1;
for(e=0;e<rows;e++){
if(matrix[e][e]==0){
    while(true==1){
        if(matrix[e+count][e]!=0){
                interchange(e,e+count);

        }
        count+=1;
        if(e+count==rows){
            break;
        }

    }
   }
   }
  }

void diagonals_to_ones(){
int g,h;
for(g=0;g<rows;g++){
        for(h=0;h<columns;h++){
            matrix[g][h]/=matrix[g][g];
        }
 }

 }

void zeros(){
int inverse;
int diag;
int i,j;
for(diag=0;diag<rows;diag++){
        order();
        diagonals_to_ones();
        for(i=0;i<rows;i++){
            if(i!=diag){
                inverse=-1*matrix[i][diag];
                for(j=0;j<columns;j++){
                    matrix[i][j]+=matrix[diag][j]*inverse;
                }
            }
        }

   }
   }

 void main(){
printf("Welcome to the awesome system of equations calculator,\n no need for
 tedious elementary row operations any more,\n we do it for you, it's
  computer era");
 printf("\n\n\nEnter the number of equations you want to solve (number of
 variables) :");
 scanf("%d",&input);

 rows=input;
 columns=input+1;

printf("\n\nNow enter the cofactor of the variables\nfollowed by the free
   nonvariable numbers for each equation\nin the same order");

 int a,b;
 for(a=0;a<rows;a++){
    printf("\n\n\n\nNow equation number %d",a+1);
    for(b=0;b<columns-1;b++){
        printf("\n\nEnter The Cofactor of Variable %d :",b+1);
        scanf("%f",&matrix[a][b]);
    }
    printf("\nEnter The free non Variable number :");
    scanf("%f",&matrix[a][b]);

  }

 printf("\n\n\nYour System of Equations is :\n\n");

 int c,d;
 for( c=0;c<rows;c++){
    for( d=0;d<columns;d++){
        printf("%.2f   ",matrix[c][d]);
    }
    printf("\n");
  }

zeros();

for( c=0;c<rows;c++){
     for( d=0;d<columns;d++){
        printf("%.2f   ",matrix[c][d]);
    }
    printf("\n");
 }

  }

here is another version with a matrix ready for testing the answer should be 1,-1,2
#include<stdio.h>
int input;
int rows=3;
int columns=4;
float matrix[3][4]={
{1,-2,3,9},
{-1,3,1,-2},
{2,-5,5,17}
};
int true =1;

void interchange(curr,alter){
float row_X[columns];
float row_Y[columns];
int k;
for(k=0;k<columns;k++){
    row_X[k]=matrix[curr][k];
}
for(k=0;k<columns;k++){
    row_Y[k]=matrix[alter][k];
}
for(k=0;k<columns;k++){
    matrix[curr][k]=row_Y[k];
 }
 for(k=0;k<columns;k++){
    matrix[alter][k]=row_X[k];
 }
 }

 void order(){
  int e;
  int count;
   count = 1;
   for(e=0;e<rows;e++){
  if(matrix[e][e]==0){
    while(true==1){
        if(matrix[e+count][e]!=0){
                interchange(e,e+count);

        }
        count+=1;
        if(e+count==rows){
            break;
        }

    }
  }
 }
 }

void diagonals_to_ones(){
int g,h;
for(g=0;g<rows;g++){
        for(h=0;h<columns;h++){
            matrix[g][h]/=matrix[g][g];
        }
 }

 }

void zeros(){
int inverse;
int diag;
int i,j;
for(diag=0;diag<rows;diag++){
        order();
        diagonals_to_ones();
        for(i=0;i<rows;i++){
            if(i!=diag){
                inverse=-1*matrix[i][diag];
                for(j=0;j<columns;j++){
                    matrix[i][j]+=matrix[diag][j]*inverse;
                }
            }
        }

     }
    }

 void main(){

printf("\n\n\nYour System of Equations is :\n\n");

int c,d;
for( c=0;c<rows;c++){
    for( d=0;d<columns;d++){
        printf("%.2f   ",matrix[c][d]);
    }
    printf("\n");
}

zeros();

printf("\n\nthe answer is\n");

for( c=0;c<rows;c++){
    for( d=0;d<columns;d++){
        printf("%.2f   ",matrix[c][d]);
    }
    printf("\n");
 }

printf("\n\nthe answer should have been\n");

float ansmatrix[3][4]={
{
1,0,0,1
},
{
0,1,0,-1
},
{
0,0,1,2
}

};
for( c=0;c<rows;c++){
    for( d=0;d<columns;d++){
        printf("%.2f   ",ansmatrix[c][d]);
    }
    printf("\n");
 }

 }


text:
Q: Installing Java6 on MacOs Catalina10.15 with brew cask I'm trying to install java6 on my Mac with
brew cask install java6
and I'm getting the following error message:
==> Downloading https://updates.cdn-apple.com/2019/cert/041-88384-20191011-3d8da658-d
######################################################################## 100.0%
==> Verifying SHA-256 checksum for Cask 'java6'.
==> Installing Cask java6
==> Running installer for java6; your password may be necessary.
==> Package installers may write to any location; options such as --appdir are ignore
installer: Cannot install on volume / because it is disabled.
installer: Es ist bereits eine neuere Version dieses Pakets installiert.
==> Purging files for version 1.6.0_65-b14-468 of Cask java6
Error: Failure while executing; `/usr/bin/sudo -E -- /usr/bin/env LOGNAME=benutzer USER=benutzer USERNAME=benutzer /usr/sbin/installer -pkg /usr/local/Caskroom/java6/1.6.0_65-b14-468/JavaForOSX.pkg -target /` exited with 1. Here's the output:
installer: Cannot install on volume / because it is disabled.
installer: Es ist bereits eine neuere Version dieses Pakets installiert.

Apparently it doesn't work because I cannot have different versions of java on the same volume, any idea on how to solve this?
Thanks!


text:
Q: how to move product title above image on category page in WooCommerce? I would like to move the product title above the product image on the shop category page.
Which hook can do that in functions.php?
I tried this one:
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );

but didn't work


text:
Q: mysqltuner report for performance optimization Very new to MySQL optimization techniques.
Please find the below report of mysqltuner.pl and suggest what variables in my.cnf should I change for performance optimization.
One more question -
I'm not able to find few variables like query_cache_size, thread_cache_size in my my.cnf. Can I explicitly add them to  my.cnf ?
Report :
-------- General Statistics --------------------------------------------------
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.5.8
[OK] Operating on 64-bit architecture

-------- Storage Engine Statistics -------------------------------------------
[--] Status: +Archive -BDB -Federated +InnoDB -ISAM -NDBCluster
[--] Data in MyISAM tables: 10K (Tables: 10)
[--] Data in InnoDB tables: 176M (Tables: 60)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 17)
[!!] Total fragmented tables: 61

-------- Performance Metrics -------------------------------------------------
[--] Up for: 21h 15m 41s (237K q [3.099 qps], 42 conn, TX: 29M, RX: 52M)
[--] Reads / Writes: 68% / 32%
[--] Total buffers: 184.0M global + 1.6M per thread (151 max threads)
[OK] Maximum possible memory usage: 419.9M (20% of installed RAM)
[OK] Slow queries: 0% (0/237K)
[OK] Highest usage of available connections: 3% (5/151)
[OK] Key buffer size / total MyISAM indexes: 16.0M/2.3M
[OK] Key buffer hit rate: 100.0% (610K cached / 7 reads)
[!!] Query cache is disabled
[!!] Sorts requiring temporary tables: 38% (5 temp sorts / 13 sorts)
[OK] Temporary tables created on disk: 0% (6 on disk / 67K total)
[!!] Thread cache is disabled
[OK] Table cache hit rate: 83% (36 open / 43 opened)
[OK] Open file limit used: 0% (18/65K)
[OK] Table locks acquired immediately: 100% (257K immediate / 257K locks)
[!!] InnoDB data size / buffer pool: 176.3M/128.0M

-------- Recommendations -----------------------------------------------------
General recommendations:
    Run OPTIMIZE TABLE to defragment tables for better performance
    MySQL started within last 24 hours - recommendations may be inaccurate
    Enable the slow query log to troubleshoot bad queries
    Set thread_cache_size to 4 as a starting value
Variables to adjust:
    query_cache_size (>= 8M)
    sort_buffer_size (> 512K)
    read_rnd_buffer_size (> 512K)
    thread_cache_size (start at 4)
    innodb_buffer_pool_size (>= 176M)

A: Yes. You can add variables to my.cnf
And, depending on the version of MySQL, change them dynamically - in the mysql console.


text:
Q: Updating EXIF info in image files I need to update EXIF info in a lot of .png files (tens of thousands of hires pictures) and I wonder if there is some (not too complicated and documented) way that I can do that without opening (decompressing the whole image) and then re-save it (compressing it again)?

A: Unfortunately the .Net GDI+ image format support is very patchy.
Consider ImageMagick. There is a .Net wrapper for it.

*

*http://www.imagemagick.org/script/index.php
Also consider ExifTool:

*

*http://owl.phy.queensu.ca/~phil/exiftool/


text:
Q: Elasticsearch custom function score i am trying to do a search with custom functions to modify document score.
I have a mapping with specialities stored inside a hospital and every speciality has a priority with it:
Something like:
hospital:{
  name: 'Fortis',
  specialities: [
   {
   name: 'Cardiology',
   priority: 10
  },
   {
   name: 'Oncology',
   priority: 15
  }
]
}

Now i have a function score :
functions: [{
     filter: {terms: {'specialities.name' => params[:search_text]}},
     script_score: {script: "_score * doc['specialities.priority'].value"}
                        },

I have a filter query to match the search text to any speciality.
Like if i search Oncology, it will match and then I have specified a script_score to take priority of that speciality and add it to final score of document.
But, it is taking the priority of the first speciality it encounters that is 10 and a score of 1 for the filter matched and the end score is 11 not 21 (priority of oncology + 1 for filter match)

A: I solved it using nested mapping in elasticsearch.
Lucene internally has no concept of storing object mappings by default, so if I am looking to store priority for every speciality I should have a mapping like this:
hospital: {
  properties: {
    specialities: {
      type: nested,
      properties: {
        name: {
          type: 'string'
        }priority: {
          type: 'long'
        }
      }
    }
  }
}

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/2.0/nested.html
After that, I was able to define function score with nested query and my query looks like this:
  "query": {
    "filtered": {
      "query": {
        "bool": {
          "must": [
            {
              "nested": {
                "path": "specialities",
                "query": {
                  "function_score": {
                    "score_mode": "sum",
                    "boost_mode": "sum",
                    "filter": {
                      "terms": {
                        "specialities.name.raw": ["Oncology"]
                      }
                    },
                    "functions": [
                      {
                        "field_value_factor": {
                          "field": "specialities.priority"
                        }
                      }
                    ]
                  }
                }
              }
            }
          ]
        }
      }
    }
  }


text:
Q: Iframe приложение Вконтакте. Пробую создать программу Вконтакте ... JS еще плохо знаю ... Все вроде делаю по официальной документации, но так ничего и не получается ...

Вот код:
<script src="http://vk.com/js/api/xd_connection.js?2" type="text/javascript"></script>
<script type="text/javascript">

VK.init(function() {
    VK.callMethod("setTitle", 'DemoApp');
    VK.api('users.get',{uids: '15547040'},function(data) {
      if (data.error) {
      alert('error!'+data.error);
      }
      if (data.response) {
        alert('good!'+data.response);
      }
    });
});

function pravadostupa () {
    VK.callMethod("showSettingsBox", 8707);
}

function friendaddf () {
    VK.callMethod("showInviteBox");
}

</script>

Колл Методы работают отлично, но API не работает! Что я делаю не так? Хочу научиться)
A: Если Ваше приложение не опубликовано и оно имеет статус "Отключено", то необходимо добавлять флаг test_mode равный 1, пример:
VK.api('isAppUser',{test_mode: test_mode},function(data) {
   if (data.error)
      alert(data.error.error_msg);
   else if (data.response) {
      alert(data.response);
   }
});


text:
Q: Communicate with foreground service android First question here, but I've been around for a while.
What do I have:
I'm building an Android app which plays audio streams and online playlists. Everything is working fine now, but I'm having issues in communicating with my service.
The music is playing in a Service, started with startForeground, so it doesn't gets killed.
I need to communicate from my activity with the service, for getting the track name, image, and a couple of things more.
Whats my issue:
I think I need to start my service with bindService (instead of my current startService) so the activity can talk to it.
However, when I do that, my service gets killed after closing the Activity.
How can I get both? Binding and foreground service?
Thanks!

A: No. bindService will not start a service . It will just bind to the Service with a service connection, so that you will have the instance of the service to access/control it.
As per your requirement I hope you will have the instance of MediaPlayer in service . You can also start the service from Activity and then bind it. If the service is already running onStartCommand() will be called, and you can check if MediaPlayer instance is not null then simply return START_STICKY.
Change you Activity like this..
public class MainActivity extends ActionBarActivity {

    CustomService customService = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // start the service, even if already running no problem.
        startService(new Intent(this, CustomService.class));
        // bind to the service.
        bindService(new Intent(this,
          CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            customService = ((CustomService.LocalBinder) iBinder).getInstance();
            // now you have the instance of service.
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            customService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customService != null) {
            // Detach the service connection.
            unbindService(mConnection);
        }
    }
}

I have similar application with MediaPlayer service. let me know if this approach doesn't help you.

A: Quoting Android documentation:

A bound service is destroyed once all clients unbind, unless the service was also started

And about the difference between started and bound just take a look to https://developer.android.com/guide/components/services.html
So, you have to create the Service using startService and then bindService, like @Libin does in his/her example. Then, the service will run until you use stopService or stopSelf or until Android decides that it needs resources and kills you.


text:
Q: End win32 process vbscript I've got the following code to end a process, but I still receive an error code 2 (Access Denied).
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'MSSEARCH.exe'")
For each objProcess in colProcessList
  wscript.echo objProcess.processid
  intrc = objProcess.Terminate()
  if intrc = 0 then wscript.echo "succesfully killed process" else wscript.echo "Could not kill process. Error code: " & intrc End if

A: It's quite legitimate to get "access denied" for ending a program.  If it's a service (which I'm guessing mssearch.exe is), then it is probably running as the "SYSTEM" user, which has higher privileges than even the Administrator account.
You can't log on as the SYSTEM account, but you could probably write a service to manage other services...

A: As a non-privileged user, you can only end processes you own. In a multiuser environment this can bite you in the ankle, because WMI would return equally named processes from other users as well, unless you write a more specific WQL query.
If your process is a service, and your script runs under a privileged account, you may still need to take "the regular route" to stop it, for example using WScript.Shell to call net stop or sc.exe, or, more elegantly, using the Win32_Service class:
Set Services = objWMIService.ExecQuery _
               ("SELECT * FROM Win32_Service WHERE Name = '" & ServiceName & "'")

For Each Service In Services
  Service.StopService()
  WSCript.Sleep 2000 ' wait for the service to terminate '
Next

A: If you look on this page: http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx you would see that error code 2 is access denied instead of file not found


text:
Q: TypeScript: Catch variable signature of a function passed as argument in higher order function I would like for a higher order function to be able to catch the signature parameters of the passed function which can have different signature.
I don't know if it's feasible but this was my approach to it :
type FuncA = (a: string, b: number) => void
type FuncB = (a: string) => void

type Func = FuncA | FuncB

const a: FuncA = (a: string, b: number) => {
  console.log('FuncA')
}

const b: FuncB = (a: string) => {
  console.log('FuncB')
}

// My higher order function
const c = (func: Func) => {
  // do something here...
  return (...args: Parameters<typeof func>) => {
    func(...args) // Expected 2 arguments, but got 0 or more. ts(2556). An argument for 'a' was not provided.
  }
}

My higher order function c couldn't pass the parameters of func
It seems like TypeScript cannot discriminate the different possible signature of type Func.
Does anyone know a pattern to write this kind of code?
Thank you !

A: If you're ok with the decorated function being any function, you could do:
const c = <T extends (...a: any) => any>(func: T) => {
  // do something here...
  return (...args: Parameters<typeof func>): ReturnType<T> => {
    return func(...args);
  }
}

Calling it would look like
c<typeof a>(a)('a', 2)

A: This is a tough one because for a function to extend another function doesn't mean quite what you think.
We want the function created by c to require that arguments correspond to the function that it was given.  So we use a generic to describe the function.
const c = <F extends Func>(func: F) => {
  return (...args: Parameters<F>) => {
    func(...args); // still has error
  }
}

At this point we still have that error, but when we call c, we get a function which has the right arguments based on whether we gave it a or b.
const cA = c(a); // type: (a: string, b: number) => void
cA("", 0);

const cB = c(b); // type: (a: string) => void
cB("");

As for the error, it has to do with what it means for a function to extend another function.  Try changing F extends Func to F extends FuncA and F extends FuncB to see what happens.  With F extends FuncB we get an error on c(a), but with F extends FuncA we don't get an error on c(b).  Huh?
If you think about it in terms of a callback it makes sense.  It's ok to pass a function that requires less arguments than expected, but not ok to pass one that requires more.  But we are the ones implementing the callback so this creates a problem for us.  If we extend type Func with a function that has no arguments, the empty array from Parameters<F> isn't sufficient to call either type.
We have to make our generic depend on the arguments instead.
type AP = Parameters<FuncA> // type: [a: string, b: number]
type BP = Parameters<FuncB> // type: [a: string]

type Args = AP | BP;

const c = <A extends Args>(func: (...args: A) => void) => {
  return (...args: A) => {
    func(...args) // no error
  }
}

Typescript Playground Link


text:
Q: How to add space between menu elements (in wordpress)? I am working in wordpress and I have this menu with 4 menu items.
The problem is that they are touching each other and there is 0
space between which makes it ugly in my opinion.
Now this problem only
occurs in wordpress. So I have to find a solution how to put some space between.
Maybe you guys know a solution without having to install something on WP.
(the codes in the body is exactly as in my wordpress to demonstrate how it looks like. You can enter it and that will put some space between, but unfortunately that doesn't work in wordpress.)

M
MethodsB
BackgroundR
ResultsP
Publications

A: Just set a fixed margin on .cornermenu.
Something like margin: 2px
JSFiddle link
 .cornermenu {
    ...
    margin: 2px;
    ...
  }


text:
Q: Gmail api & Admin SDK used to transfer emails between gmail accounts in the same organization Using the Google Admin SDK & gmail API is there a way to automate user email transfers from one account to another user the way Google data migration tool?
I'm looking for any existing scripts or methods that can be implemented in an automated system. (Solutions can contain python,javascript,php)

A: Try using Admin SDK Groups Migration Service in App Script.
A code snippet is provided for you to try:
function migrateMessages() {
  var groupId = 'exampleGroup@example.com';
  var messagesToMigrate = getRecentMessagesContent();
  for (var i = 0; i < messagesToMigrate.length; i++) {
    var messageContent = messagesToMigrate[i];
    var contentBlob = Utilities.newBlob(messageContent, 'message/rfc822');
    AdminGroupsMigration.Archive.insert(groupId, contentBlob);
  }
}

/**
 * Gets a list of recent messages' content from the user's Gmail account.
 * By default, fetches 3 messages from the latest 3 threads.
 *
 * @return {Array} the messages' content.
 */
function getRecentMessagesContent() {
  var NUM_THREADS = 3;
  var NUM_MESSAGES = 3;
  var threads = GmailApp.getInboxThreads(0, NUM_THREADS);
  var messages = GmailApp.getMessagesForThreads(threads);
  var messagesContent = [];
  for (var i = 0; i < messages.length; i++) {
    for (var j = 0; j < NUM_MESSAGES; j++) {
      var message = messages[i][j];
      if (message) {
        messagesContent.push(message.getRawContent());
      }
    }
  }
  return messagesContent;
}


text:
Q: Maps and Flatmaps in Scala I am new to scala. I need a lot of help with using maps and flatmaps with tuples.
I have functions as follows-
    def extract(url: String): String = {//some code}
    def splitstring(content: String): Array[String]={//some code}
    def SentenceDetect(paragraph: Array[String]): Array[String] = {//some code}
    def getMd5(literal: String): String = {//some code}

I have a incoming list of urls. and I want it to go through above series of functions using map and flatmaps.
    var extracted_content=url_list.map(url => (url,extract(url)))

    val trimmed_content=extracted_content.map(t => (t._1,splitstring(t._2)))

    val sentences=trimmed_content.map(t => (t._1,SentenceDetect(t._2)))

    val hashed_values=sentences.flatMap(t => (t._1,getMd5(t._2)))

The issue is I am getting at error at flatMap as type mismatch--
Error:(68, 46) type mismatch;
  found   : (String, String)
  required: scala.collection.GenTraversableOnce[?]
val hashed_values=sentences.flatMap(t => (t._1,getMd5(t._2.toString)))

How to get it done.

A: I think this is what you're after.
val hashed_values = sentences.map(t => (t._1, t._2.map(getMd5)))

This should result in type List[(String,Array[String])]. This assumes that you actually want the Md5 calculation of each element in the t._2 array.
Recall that the signature of flatMap() is flatMap(f: (A) ⇒ GenTraversableOnce[B]), in other words, it takes a function that takes an element and returns a collection of transitioned elements. A tuple, (String,String), is not GenTraversableOnce thus the error you're getting.

A: You are getting this error because getMd5(...) accepts a string, however sentences is of type List[(String, Array[String])] (assuming url_list is List[String]), so t._2 is of type Array[String].
Anyway, some notes regarding your code:

*

*variable names in scala are "lower camel" (https://docs.scala-lang.org/style/naming-conventions.html), not lower-with-underscore

*extracted_content should probably be a val

*since all your variables are maps, and since you want to transform the map's value, you better use .mapValues instead of .map


text:
Q: Berry-Esseen theorem and test functions We use the Berry-Esseen theorem to prove the closeness of the two distributions.
In the proof of the theorem people have used the notion of test functions (functions which are smooth and fourth derivative is bounded). I want to know the idea behind the use of test functions. How we can think about that because these two notions i.e., close distributions and test functions are very different.
Thank you.

A: Consider the representation of of the Euclidean distance
$$
  \|x-y\| = \max_{\|u\| \le 1} \langle{u,x-y\rangle}
$$
Note that $f_u(x) = \langle{u,x\rangle}$ is a linear function. If you define the norm of it as $\|f_u\| = \|u\|$, then the above can be written as
$$
  \| x - y\| = \max_{f \; \text{linear},\; \|f\|\le 1} [f(x) - f(y)]
$$
Now, for two measures (or distributions) $\mu$ and $\nu$ you can use the same idea to define a distance
$$
d(\nu,\mu) = \sup_{f\; \text{linear},\; \|f\| \le 1} [f(\nu) - f(\mu)]
$$
where $\|f\|$ is a suitable norm. Now a general linear function(al) of measures has the form
$$
f_\phi(\mu) = \int \phi(x) d\mu(x)
$$
for some test function $\phi$. Thus, you get
$$
d(\mu,\nu) = \sup_{\phi \,\in\, \mathcal{C},\; \|\phi\|_{\mathcal{C}}\,\le\, 1}
\Big|\int \phi d\mu - \int \phi d\nu\Big|
$$
where $\mathcal{C}$ is some class of test functions and $\|\cdot\|_{\mathcal{C}}$ is some sort of norm on it.
This gives you a general way to define distances between objects if you can define linear fucntionals on them.


text:
Q: Matlab: Fit curve to data points I have to fit experimental data (x, y) with the function g(x)=(A*B*x)/(1+B*x))+K*x+L*x^n.
This is my code:
x=[0;2;4;6;8;10;15;20;25;30;35;40;45;50;55;60;65;70;75;80;85;90];
y=[0.01;0.32;0.76;1.15;1.51;1.83;2.45;3.03;3.6;4.18;4.75;5.30;5.85;6.53;7.25;8.26;9.25;10.46;11.45;13.37;15.75;18.68];
g=fittype('((A*B*x)/(1+B*x))+K*x+L*x^n', 'independent',{'x'}, 'coefficients',{'A','B','K','L','n'});
f=fit(x,y,g,'StartPoint', [53.07, 0.003612, 0.139, 0.0002939, 2.454], 'Lower', [0 0 0.1 0 0 ],'MaxIter',100000);
plot(f)
hold on
scatter(x,y)

The problem is that it throws a figure with a curve which doesn't fit with experimental data.
Can anyone explain to me why ? How do I get a curve which fits with data ?

A: When I fit your posted data and equation with no parameter bounds, a plot of fitted equation vs. raw data gives no visual indication of the problem which you reported. Perhaps the problem is somehow related to the parameter bounds, and if so when you fit without bounds you will have similar results to those I obtained. One of the parameter bounds may be causing the observed difficulty. For comparison, here are the parameter values and fit statistics I obtained when fitting without bounds:
A = -4.6348799797589422E+00
B = -8.5030471461837072E-03
K = -2.3151367681587254E-01
L =  5.1192051372512604E-01
n =  8.5896339221116724E-01

Degrees of freedom (error): 13
Degrees of freedom (regression): 4
Chi-squared: 0.129575842219
R-squared: 0.999684934083
R-squared adjusted: 0.999587990724
Model F-statistic: 10312.051735
Model F-statistic p-value: 1.11022302463e-16
Model log-likelihood: 18.863852459
AIC: -1.540428051
BIC: -1.2931025627
Root Mean Squared Error (RMSE): 0.0848449049798

A = -4.6348799797589422E+00
std err: 2.21395E+00
t-stat: -3.11497E+00
p-stat: 8.20677E-03
95% confidence intervals: [-7.84937E+00, -1.42039E+00]

B = -8.5030471461837072E-03
std err: 1.21952E-07
t-stat: -2.43489E+01
p-stat: 3.13238E-12
95% confidence intervals: [-9.25748E-03, -7.74861E-03]

K = -2.3151367681587254E-01
std err: 4.48642E-01
t-stat: -3.45642E-01
p-stat: 7.35141E-01
95% confidence intervals: [-1.67855E+00, 1.21552E+00]

L = 5.1192051372512604E-01
std err: 3.36712E-01
t-stat: 8.82213E-01
p-stat: 3.93682E-01
95% confidence intervals: [-7.41674E-01, 1.76551E+00]

n = 8.5896339221116724E-01
std err: 7.71803E-02
t-stat: 3.09187E+00
p-stat: 8.57996E-03
95% confidence intervals: [2.58784E-01, 1.45914E+00]

Coefficient Covariance Matrix
[  2.22119894e+02  -5.17965896e-02   8.95871374e+01  -7.83675558e+01
-3.62713522e+01]
[ -5.17965896e-02   1.22351509e-05  -1.99822391e-02   1.74993754e-02
8.05904780e-03]
[  8.95871374e+01  -1.99822391e-02   4.50111094e+01  -3.89773831e+01
-1.86449684e+01]
[ -7.83675558e+01   1.74993754e-02  -3.89773831e+01   3.37814021e+01
1.61229511e+01]
[ -3.62713522e+01   8.05904780e-03  -1.86449684e+01   1.61229511e+01
7.74329075e+00]


text:
Q: $ _POST returns the original name of dynamically modified inputs with Jquery instead of the modified name i use jquery.repeater within several steps form manage with the October Ajax Framework.
the repeater have to change dynamically form input name like my_input_text into my_group[1]my_input_text, my_group[2]my_input_text, etc
when i use F12 in my browser, i can see input names are correctly changed as needed
...
<input class="form_input" type="text" name="group[1][amount]">

...

but within my ajax handler onSomething()  $_POST still return the original input field name my_input_text, so i can't manage correctly ajax errors return with data-validate-for
array:3 [
  "group" => array:2 [
    0 => array:1 [
      "amount" => ""
    ]
    1 => array:1 [
      "amount" => "666"
    ]
  ]
]

expected result is
array:3 [
  "group" => array:2 [
    0 => array:1 [
      "amount" => ""
    ]
    1 => array:1 [
      "group[1][amount]" => "666"
    ]
  ]
]

(the first array element is expected as it corresponding at the empty form used as repeater "template" with diplay:none)
here the jquery code which change input names attributes (and my hack to change data-validate-for
    var setIndexes = function ($items, groupName, repeaters) {

        $items.each(function (index) {

            var $item = $(this);

            $item.data('item-name', groupName + '[' + index + ']');
            $filterNested($item.find('[name]'), repeaters)
            .each(function () {

                var $input = $(this);

                // match non empty brackets (ex: "[foo]")
                var matches = $input.attr('name').match(/\[[^\]]+\]/g);

                var name = matches ?
                    // strip "[" and "]" characters
                    last(matches).replace(/\[|\]/g, '') :
                    $input.attr('name');

                var newName = groupName + '[' + index + '][' + name + ']' +
                    ($input.is(':checkbox') || $input.attr('multiple') ? '[]' : '');

                $input.attr('name', newName);

                $foreachRepeaterInItem(repeaters, $item, function (nestedFig) {
                    var $repeater = $(this);
                    setIndexes(
                        $filterNested($repeater.find('[data-repeater-item]'), nestedFig.repeaters || []),
                        groupName + '[' + index + ']' +
                                    '[' + $repeater.find('[data-repeater-list]').first().data('repeater-list') + ']',
                        nestedFig.repeaters
                    );
                });
            });

            //***** add by Pat-Och
            if (fig.errorMessage) {

                $filterNested($item.find('.' + fig.errorMessageClass), repeaters)
                    .each(function () {

                        var $span = $(this);

                        // match non empty brackets (ex: "[foo]")
                        var matches = $span.attr('data-validate-for').match(/\[[^\]]+\]/g);

                        var dataValidateFor = matches ?
                            // strip "[" and "]" characters
                            last(matches).replace(/\[|\]/g, '') :
                            $span.attr('data-validate-for');

                        var newDataValidateFor = groupName + '[' + index + '][' + dataValidateFor + ']' +
                            ($span.is(':checkbox') || $span.attr('multiple') ? '[]' : '');

                        $span.attr('data-validate-for', newDataValidateFor);

                    });
            }
            //***** end add by Pat-och
        });

        $list.find('input[name][checked]')
            .removeAttr('checked')
            .prop('checked', true);
    };

the issue is submit form don't retrieve right new input names but the originals ones.first, The repeater library clone the template as many time as user asked, then change input names then, after submitting, ajax handler see correctly template clones but with original input names
if run this
$( "form" ).submit(function( event ) {
  event.preventDefault();
  console.log( $( this ).serialize() );
  console.log($('form').html());

});

the serialised form have original value and the .html have expected value, lost in the jungle ...
have no idea what happend beside and how to deal with this issue


text:
Q: Invalid parameter number when trying to run the function I have created a function to insert data into the MySQL database.
// Inserting in the database
public function addData($table, array $columns, array $values) {
    // Defining columns
    $each_column = null;
    foreach ($columns as $column) {
        $each_column .= '`' . $column . '`, ';
    }
    $column_sentence = substr($each_column, 0, -2);

    // Defining values
    $each_value = null;
    foreach ($values as $value) {
        $each_value .= ':' . $value . ', ';
    }
    $value_sentence = substr($each_value, 0, -2);

    // Go ahead with prepared SQL
    $sql = "INSERT INTO `$table` ($column_sentence) VALUES ($value_sentence)";
    $statement = $this->pdo->prepare($sql);

    foreach (array_combine($columns, $values) as $column => $value) {
        $statement->bindValue(':' . $column, $value);
    }

    // Execute that baby
    $statement->execute();

    $statement->errorCode();
    $statement->errorInfo();
}

This is how I run this function:
$db->addData('test', array('id', 'ip', 'name'), array(24, 123456789, 'Reza'));

My problem is that I get this warning:

Warning:  PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter
  number: parameter was not defined

What exactly is wrong with that function?

A: you are using the values as instead of the column names in the values area.
    public function addData($table, array $columns, array $values) {
        // Defining columns
        $each_column = null;
        foreach ($columns as $column) {
            $each_column .= '`' . $column . '`, ';
        }
        $column_sentence = substr($each_column, 0, -2);

        // Defining values
        // FIX : put the column names in the VALUES()
        $each_column = null;
        foreach ($columns as $column) {
            $each_column .= ':' . $column . ', ';
        }
        $value_sentence = substr($each_column, 0, -2);

        // rest of code snipped
    }

Before
INSERT INTO `test` (`id`, `ip`, `name`) VALUES (:24, :123456789, :Reza)

After
INSERT INTO `test` (`id`, `ip`, `name`) VALUES (:id, :ip, :name)


text:
Q: Xcode compiler error I have an app that has two view controllers the first view controller has 3 buttons one of those buttons pushes to the next view controller.
I keep getting this error
return uiapplicationmain(argc argv nil nsstringfromclass( appdelegate class)

The only files I have are:
AppDelegate.h
AppDelegate.m
ViewController.h
ViewController.m

I have only been adding things through the Main.storyboard.

A: Check for stray connections in the buttons where one button isn't supposed to be linked to an outlet or action. To do that, go to the storyboard, and for every button, click the rightmost tab in the inspector (right menu) and check for your connections.


text:
Q: How to best extract attribute values and element values with LINQ and C# Before i start this is my first post, so if there is something i have done wrong or not done please tell me and i'll edit my post
I have a document which is formated as follows.
<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'>
    <EventData>
        <Data Name='SubjectUserSid'>S-1-0-0</Data>
        <Data Name='SubjectUserName'>MACHINE$</Data>
        <Data Name='SubjectDomainName'>DOMAIN</Data>
        <Data Name='SubjectLogonId'>0x0</Data>
        <Data Name='TargetUserSid'>S-1-0-0</Data>
        <Data Name='TargetUserName'>username</Data>
        <Data Name='TargetDomainName'>TDname</Data>
        <Data Name='Status'>0x0</Data>
        <Data Name='FailureReason'>%%2313</Data>
        <Data Name='SubStatus'>0x0</Data>
        <Data Name='LogonType'>10</Data>
    </EventData>
</Event>

I have a little problem comming up with something that can extract the values from the XML (both the attribute values and the corresponding element values). Do i need a statement for each of the attribute or can i return a list and just loop over the values?
EDIT: The values needs to be extracted so i can send them to a database. I would like to try using LINQ for this, but Xpath might work aswell
EDIT2: Thank you for three good answers, i don't have the req. reputation to upvote answers yet and i need to get to my dev machine before testing, but this really looks what im looking for :)

A: As far as I understood, you need to access properties and values as examples to parse xml.

Do i need a statement for each of the attribute or can i return a list
  and just loop over the values?

no you don't. Use next code as an example to parse xml:
//str contains your xml
XDocument xml = XDocument.Parse(str);
XNamespace ns = "http://schemas.microsoft.com/win/2004/08/events/event";

foreach (var node in xml.Descendants(ns + "Data"))
{
    Console.WriteLine ("Name: " + (string)node.Attribute("Name") + "; "+
                       "Value: " + node.Value);
}

will print:
Name: SubjectUserSid; Value: S-1-0-0
Name: SubjectUserName; Value: MACHINE$
Name: SubjectDomainName; Value: DOMAIN
Name: SubjectLogonId; Value: 0x0
Name: TargetUserSid; Value: S-1-0-0
Name: TargetUserName; Value: username
Name: TargetDomainName; Value: TDname
Name: Status; Value: 0x0
Name: FailureReason; Value: %%2313
Name: SubStatus; Value: 0x0
Name: LogonType; Value: 10

A: XNamespace ns = "http://schemas.microsoft.com/win/2004/08/events/event";
var document = XDocument.Parse(
    "<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'>" +
    "<EventData>" +
    "    <Data Name='SubjectUserSid'>S-1-0-0</Data>" +
    "    <Data Name='SubjectUserName'>MACHINE$</Data>" +
    "    <Data Name='SubjectDomainName'>DOMAIN</Data>" +
    "    <Data Name='SubjectLogonId'>0x0</Data>" +
    "    <Data Name='TargetUserSid'>S-1-0-0</Data>" +
    "    <Data Name='TargetUserName'>username</Data>" +
    "    <Data Name='TargetDomainName'>TDname</Data>" +
    "    <Data Name='Status'>0x0</Data>" +
    "    <Data Name='FailureReason'>%%2313</Data>" +
    "    <Data Name='SubStatus'>0x0</Data>" +
    "    <Data Name='LogonType'>10</Data>" +
    "</EventData>" +
    "</Event>");

var q = from element in document.Root.Element(ns + "EventData").Elements(ns + "Data")
        select new
        {
            Name = element.Attribute("Name").Value,
            Value = element.Value
        };

A: To get the attributes of each element:
var attributes = from n in xml.Descendants("Data")
                        select n.Attributes("Name").Select(s => s.Value);

To get the data of each element:
var data = from n in xml.Descendants("EventData")
                        select n.Elements("Data").Select(s => s.Value);

Or in one single query: -
var nodes = from n in xml.Descendants("EventData").Elements("Data")
                        select new
                        {
                            Data = n.Value,
                            Attribute = n.Attribute("Name").Value
                        };


text:
Q: Element being trivial in a finitely presented group independent of ZFC Is there an explicit finitely presented group $G$ and an element $g\in G$ such that the statement "$g$ is equal to the identity" is independent of ZFC?

A: The answer is yes.
This is just an instance of the general phenomenon that every non-computable decision problem is saturated with logical independence. (See this related MO answer.)
Theorem. If $A$ is a computably enumerable undecidable decision problem, such as the word problem for groups, then for any consistent c.e. theory $T$ extending PA, such as ZFC, there must be true instances of $n\notin A$ that are not provable in $T$.
Proof. Suppose that $T$ is a consistent c.e. theory extending PA. It follows that all the true instances of $n\in A$ are provable in PA and hence in $T$. If conversely $T$ proved all true instances of $n\notin A$, then we could decide $A$ as follows: on input $n$ we search, during the day, for positive instances of $n\in A$, since $A$ is c.e., and at night, we search for a proof from $T$ that $n\notin A$. Since $T$ is consistent and proves all true existentials, it can be trusted for any proof of $n\notin A$. So if all such true instances of $n\notin A$ were provable in $T$, then $A$ would be decidable, contrary to assumption. $\Box$
In particular, if ZFC is consistent, then there must be specific concrete instances of the word problem where a word $g$ is nontrivial for a specific presentation, but this is not provable in ZFC.
If you want to get actual independence of ZFC, then you can do so by assuming that ZFC is $\Sigma_1$-sound, which means that it proves only true existential arithmetic statements. If there is an inaccessible cardinal or even only a worldly cardinal, then ZFC is $\Sigma_1$-sound. But much less is required.
Corollary. If $T$ is a consistent c.e. $\Sigma_1$-sound theory, then for any c.e. computable undecidable decision problem $A$, there must be concrete instances $n$ for which $n\in A$ is independent of $T$.
Proof. The point is that if we have a true instance of $n\notin A$ that is not provable in $T$, then also by soundness $T$ will not prove $n\in A$, and so $n\in A$ will be independent of $T$. $\Box$
In particular, assuming ZFC is $\Sigma_1$-sound, which is a mild extra assumption about ZFC, then for any nondecidable decision problem, such as the word problem for groups, there will be concrete instances that are independent of ZFC.
But finally, since I expect that you might want not just a proof that there is an explicit instance, but the explicit instance itself, let me describe how one might construct a specific instance. We know that the word problem in groups is undecidable because we can code the halting problem into it. Consider the Turing machine that searches for a proof of a contradiction in ZFC, halting only when found. From this instance of the halting problem, we can construct an group presentation $G$ and a word $g$ which is trivial in $R$ just in case the program halts. In other words, $g=1$ is true in $G$ if and only if $\neg\text{Con}(\text{ZFC})$, and this would be provable in a weak theory. If consistent, ZFC will not prove $g\neq 1$, since that would mean proving its own consistency; but if also $\text{Con}(\text{ZFC})$, then ZFC will not prove $g=1$ in $G$. And so it will be independent. This example also reduces the soundness requirement to mere consistency.

A: For any finite presentation there is an algorithm that will tell you if a word is equal to the identity: 1. Fix some positive integer $n$.  2. Write down all words in the generators that can be written as a product of at most $n$ conjugates of the given relators by elements that can be written as a product of at most $n$ of the given generators and their inverses.  3.  If none of these words is equal (as a reduced word) to your given group element, increase the value of $n$ and repeat.
If your word is not equal to the identity, the algorithm will not terminate.
If you had a proof that ZFC could not show that your word was equal to the identity, then doesn't the above algorithm imply that it is not equal to the identity?


text:
Q: Find the most frequent date for every group I'm querying the austin crime dataset from BigQuery.
This is the preview:

I want to query the total incidences and the most frequent day they happened, grouped by crime type.
My actual query goes like this:
SELECT description, count(*) as incidences
FROM bigquery-public-data.austin_crime.crime
group by description
order by incidences desc;

But i don´t find a way to find the day with most cases for every type of crime

A: Hmmm . . . One method is to aggregate by the description and weekday.  Use window functions to determine the total over the description and the highest weekday total:
select description, weekday, weekday_incidences, incidences
from (select description, format_timestamp('%a', timestamp) as weekday,
             count(*) as weekday_incidences,
             sum(count(*)) over (partition by description) as incidences,
             row_number() over (partition by description order by count(*) desc) as seqnum
      from `bigquery-public-data.austin_crime.crime` c
      group by description, weekday
     ) c
where seqnum = 1
order by incidences desc;


text:
Q: Is there any query to find this id information? Her is a sample of my table:
+--------+-------+-----+
|  name  | value | id  |
+--------+-------+-----+
| value1 |     1 | 100 |
| value2 |     2 | 100 |
| value1 |     1 | 200 |
| value2 |     3 | 200 |
| value1 |     1 | 300 |
| value2 |     4 | 300 |
|        |       |     |
+--------+-------+-----+

How to setup an SQL query to retrieve the id value 100 for given value1 = 1 and value2 = 2?

A: If I understand correctly, aggregation with a having clause does what you want:
select id
from t
group by id
having count(*) filter (where name = 'value1' and value = 1) = 1 and
       count(*) filter (where name = 'value2' and value = 2) = 1 ;

A: Group by id and set the condition in the having clause:
select id
from tablename
where (name, value) in (('value1', 1), ('value2', 2))
group by id
having count(distinct value) = 2

See the demo.

A: A case of relational-division. See:

*

*How to filter SQL results in a has-many-through relation
This query typically more efficient than what has been suggested so far:
SELECT id
FROM  (SELECT id FROM tbl WHERE name = 'value1' AND value = 1) t1
JOIN  (SELECT id FROM tbl WHERE name = 'value2' AND value = 2) t2 USING (id);

Or equivalent (results in identical query plan):
SELECT id
FROM   tbl t1
JOIN   tbl t2 USING (id)
WHERE  t1.name = 'value1' AND t1.value = 1
AND    t2.name = 'value2' AND t2.value = 2;

db<>fiddle here
Not enforcing uniqueness in the query (like other answers do) as I assume one or more constraints in the table already doing so.
Have a "covering" index on (name, value, id). Optimized index variations are possible, depending on your undisclosed table definition.
But first reconsider your relational design if you are in a position to change it. EAV models are typically sub-optimal. See:

*

*Is there a name for this database schema of key values?

A: SELECT id from TABLE_NAME WHERE value IN (1, 2);
This is will retrieve the id column from your table when value column is either 1 or 2


text:
Q: Combine multiple select statements in SOQL and python I am trying to combine three columns(same data type) from three tables. I am receiving a malformed request error that I can't quite figure out. Initially I tried a UNION ALL but I learned that SOQL does not support this. Is there a way to write this query in a single line as below? I would like to have a single column ,single table result.
This is the error I am getting
^\nERROR at Row:1:Column:43\nunexpected token: namecolumn', 'errorCode': 'MALFORMED_QUERY'}]

from sf_query_pull import QueryDataToFile
from pathlib import Path
import pandas as pd

class Pull_data:
    '''Pulls salesforce data'''

    def __init__(self):
        '''performs the actual query of salesforce data and calls the other methods.'''

        self.query = "".join(
            ["SELECT namecolumn FROM table1","SELECT namecolumn FROM table2","SELECT namecolumn FROM table3;"])

        self.files = { 'results': str(Path.cwd()) + '\\TestQueryResult.csv'}

        self.query_data()

    def query_data(self):
        '''Pull real-time data from Salesforce.'''
        print(': Pulling data from Salesforce.')
        QueryDataToFile('prod', self.query, self.files['results'])

Pull_data()

A: You can't do this in Salesforce's SOQL. You'll need three separate queries, which you can then combine at the end to create your CSV file.
You have two basic choices, though: you can use /services/data/v51.0/composite to perform three different queries via a Composite API request, or you can perform each one in sequence. I'd recommend the first option, as it uses only one API call and should be easier to code for.


text:
Q: Where is SobjectType.newSObject useful I was going through a document at the SObjectType class where there was a method named - newSObject(recordTypeId, loadDefaults). I see that using this method one can create a new Sobject with default values of
custom fields assigned. But I am started to think that what is the difference between below two ways of creating a object say Account object:
Suppose there is a custom field on account named class__c with a default value as "Fresh".
1st approach: this will create a new account- Acme, with a default value of class__c as "Fresh":
Account acc = new Account(Name='Acme);
Insert acc;

2nd approach: this is from the documentation:
// Create an account with predefined default values
Account acct = (Account)Account.sObjectType.newSObject(null, true);
// Provide a value for Name
acct.Name = 'Acme';
// Insert new account
insert acct;

I am a bit confused here that why would we use Account.sObjectType.newSObject(null, true); to populate the default value of custom field when the default value of field
gets populated automatically when a new account is created. My question is why do we need to explicitly do Account.sObjectType.newSObject(null, true)? What is a difference between
1st way and 2nd way. I am sure I am missing some concept here:)

A: If you want to write a utility that creates records, this function is absolutely necessary in order to be generic at all. Sure, you could also use Type.forName, but that doesn't take nearly as good advantage of strict typing.
Simply contrast these test utility styles and imagine which will balloon massively each time you want to support new object types:
public static List<SObject> createRecords(SObjectType sObjectType, Integer count)
{
    List<SObject> records = new List<SObject>();
    for (Integer i = 0; i < count; i++)
        records.add(sObjectType.newSObject());
    return records;
}

public static List<Account> createAccounts(Integer count)
{
    List<Account> records = new List<Account>();
    for (Integer i = 0; i < count; i++)
        records.add(new Account());
    return records;
}

Also, note that the optional parameters allow you to instantiate the object with its default values, a useful feature that you would not  be able to accomplish using your first approach (concrete type instantiation). This functionality is quite useful in writing tests that perform consistently as expected.

A: The question appears to be about the difference between the various newSObject methods, not about the general need for that family of methods.
From my reading of the (not entirely clear) documentation the key statement may well be:

If the loadDefaults argument is false, this method creates the sObject
  with field values of null.

So this:
newSObject(null, true)

may be the equivalent of:
newSObject()

and the new behavior is achieved with this:
newSObject(null, false)

that does not apply the default values.
Would need some exploratory tests to be written to be more sure.


text:
Q: No root user password for MariaDB I've gone through the process of installing MariaDB several times now, and it has never asked me to create a root password.  The upshot of this is I can't get in and create the database.  Obviously I'm doing something wrong, but I can't find what!

A: For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

A: Basically, you can connect by root from localhost from root shell without password.
If you don't known root password, there is a way to start mysql without using mysql db, where users and passwords stored. Run each command with sudo, except  mysql console commands:
# service mysql stop
# mysqld_safe --skip-grant-tables &

# mysql -u root
use mysql;
update user set password=PASSWORD('NEWPASSWORD') where User='root';
flush privileges;
exit;

# service mysql restart

Now you can login with new password: # mysql -u root -p
Update: Its better not change password for root, but create new user with all privileges who can connect only from localhost. When in mysql console do following:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

If you need external connections to mysql - limit it by hosts and/or don`t grant all privileges and limit to only required databases(the * in above example).


text:
Q: Use 14.04 application in 15.04 I am running 15.04. I need to install ghdl. However after adding the repository when I do
apt-get update

I keep getting
failed to fetch http://ppa.launchpad.net/pgavin/ghdl/ubuntu/dists/vivid/main/binary-i386/Packages

Why is this?

A: There are no packages for 15.04 in this ppa, but the ones for 14.04 (trusty) may work.
You can directly download a deb file from PPA.
Click View Package details and download a 32 or 64-bit deb.
32-bit
64-bit

A: As @Pilot6 said, there are no packages for Trusty.
In this case, it's not a problem to use the Trusty packages and it's OK to use the list file for Trusty packages to get updates. What you need is the installation of some additionally Trusty packages.
Here the example for 32-bit. For 64-bit packages select your download from this sites: libgnat-4.8, gnat-4.8-base

*

*libgnat-4.8 (32-bit)
cd
wget http://mirrors.kernel.org/ubuntu/pool/universe/g/gnat-4.8/libgnat-4.8_4.8.2-8ubuntu3_i386.deb

*gnat-4.8-base (32-bit)
cd
wget http://mirrors.kernel.org/ubuntu/pool/universe/g/gnat-4.8/gnat-4.8-base_4.8.2-8ubuntu3_i386.deb

*Install the deb files
sudo dpkg -i ~/Downloads/gnat-4.8-base_4.8.2-8ubuntu3_i386.deb
sudo dpkg -i ~/Downloads/libgnat-4.8_4.8.2-8ubuntu3_i386.deb

After that, replace vivid with trusty in your list file:
sudo nano /etc/apt/sources.list.d/pgavin-ubuntu-ghdl-vivid.list

Or as one-liner
sudo sed -i 's/vivid/trusty/' /etc/apt/sources.list.d/pgavin-ubuntu-ghdl-vivid.list

and install ghdl
sudo apt-get update
sudo apt-get install --reinstall ghdl

From time to time you should check the PPA for Vivid packages.

A: Installation from source is very simple
sudo apt-get install gnat-5
git clone https://github.com/tgingold/ghdl
git checkout v0.33
cd ghdl
./configure --prefix=/usr/local
make
make install
ghdl --version

And now you can try the hello world documented at: http://ghdl.readthedocs.io/en/latest/Starting_with_GHDL.html#the-hello-world-program
Tested on Ubuntu 16.04.
Compiling with the GCC backend is harder, but may have advantages like simulation speed. Procedure and trade-off discussed at: https://github.com/tgingold/ghdl/blob/f2b83716c79e7c6123aa9b6215a6dc6ac1c9d83b/BUILD.txt


text:
Q: Laptop does not go to sleep mode nor hibernation Whenever I drop down my laptop screen it does not go to the sleep mode nor hibernation. I  went to the "more power options" and then select "choose when to turn off the display" and there I choose sleep for plugged in and hibernate for unplugged. I also tried cmd prompt as administration and use the command "powercfg -HIBERNATE ON" But it still does not work. I've a INTEL ENERGY MANAGEMENT DRIVER installed in my laptop(Lenovo G580 model 20157 with Win7 Ultimate).
Any suggestions ?


text:
Q: Why I'm receiving a None value although I'm using return in the function? def list_min(lst, low, high):
    if high == low:
        #### IT prints the value that I want when I do : "print(lst[low]) or print(lst[high])"
        return lst[low]
    elif lst[low] >= lst[high]:
        list_min(lst, low+1, high)
    else:
        list_min(lst, low, high-1)

lst1 = [1, 2, 3, 4, 2, 3, 1, 2, 34, 44]
print(list_min(lst1, 0, len(lst1)-1))


text:
Q: Disable the access of the product Individually by product url, but product should be listed in serach In my site I need to show product detail in popup. I have done that, but there is a problem product url is also open in browser. I need to disable all the product url open in browser for all product without sat the product Not Visible Individually.

A: If you set the product to be SEARCH ONLY - as per your question, then the product will be simply that.  The code you implement for the popup should not use this flag when querying your product collection (i.e. don't apply a visibility filter) and then you can still get the data out into your popup.


text:
Q: How to set the fixed value for the create/edit form field in Flask-Admin I'm using Flask-Admin and Flask-Security to write a website. I want to implement a function: The user which has admin role only can create user which is foo role. The user which has foo role only can create user which is bar role.
I have tried the QueryAjaxModelLoader:
form_ajax_refs = {
    roles: QueryAjaxModelLoader("role", db.session, Role, fileds=["name"])

and form_choices:
form_choices = {"roles": [(3, "foo"), ]}

These two methods don't solve the problem. Can anyone give me some advice?

A: At first, I use on_model_change to set the default value of the roles field.
And then, I use form_args and query_factory to limit the choices of roles field.
def filter_func():
    return db.session.query(Role).filter_by(name="applicant")

form_args = {
    "roles": {
        "query_factory": filter_func
    }
}


text:
Q: Recursive bubble sort in X-Y coordinate in C I would like to sort the elements associated with X
The method tried not in a recursive way, any idea how to do it
The expected output is:
{5,73} , {11,19}, {11,34}, {11,68}, {13,5}
I have tried this so far, but only X is sorted while Y remain in original position
void sort(struct Points a[], int n)
        {

            if (n == 1) return;

            for (int i=0; i<n-1; i++)
                if (a[i].X > a[i+1].X)
                    swap(&a[i].X, &a[i+1].X);

            //sort(&a[0], n);

        }
    struct Points {
        int X, Y;
    };

    void swap(int *a, int *b)
    {
        int t;

        t  = *b;
        *b = *a;
        *a = t;
    }

        void sort(struct Points a[], int n);

        int main()
        {
            int i;
            struct Points ptArray[5] = { {11, 34}, {5, 73}, {11, 19}, {13, 5}, {11,
                68}};

            sort(ptArray, 5);

            for (i = 0; i < 5; i++){
                printf("(%d, %d)\n", ptArray[i].X, ptArray[i].Y);
            }

            return 0;
        }

A: There are a few issues in your code:
[1] you want to swap Points object so modified swap function looks
void swap(Points *a, Points *b)
{
    Points t;

    t  = *b;
    *b = *a;
    *a = t;
}

[2] now you are sorting elements only by checking X coordinates, you don't have condition to check Y - values
[3] when you want to call sort function recursively, n parameter must be decremented before calling function
sort function should be
void sort(struct Points a[], int n)
{
  if (n > 1)
  {
    for (int i=0; i<n-1; i++)
        if (a[i].X > a[i+1].X || (a[i].X == a[i+1].X && a[i].Y > a[i+1].Y))
            swap(&a[i], &a[i+1]);
    sort (a,--n);
  }
}

A: full working code -
struct point{
    int x; int y;
};

bool isGreater(point p1, point p2){
    if(p1.x>p2.x) return true;
        else if(p1.x==p2.x){
            return p1.y>p2.y;
        }
    return false;
}

void recBubble(point *arr, int n){
    if (n == 1) return;

    for (int i=0; i<n-1; i++)
        if (isGreater(arr[i],arr[i+1]))
            swap(arr[i], arr[i+1]);
    recBubble(arr, n-1);
}


text:
Q: Trigger creation of other tkinter windows I am trying to create a python script that will trigger a tkinter window every time a certain event happens. The python script will have a while true loop and during the loop the tkinter event may or may not happen (if-else block). Right now the actual loop part isn't done, so I am currently testing the tkinter part but I can't seem to open more than tkinter window.
Below is the test script I am using.
from tkinter import *
from sys import exit
import os

onetwo = "C:/Users/I/Downloads/Transfer_Out_1016_Outlook.txt"

def popupError(s):
    popupRoot = Tk()
    ##popupRoot.after(20000, exit)
    popupButton = Button(popupRoot, text = s, font = ("Verdana", 12), bg = "yellow", command = lambda: os.system(onetwo))
    popupButton.pack()
    popupRoot.geometry('400x50+700+500')
    popupRoot.mainloop()

popupError("HelloWORLD")

def popupTwo(s):
    popupRoot = Tk()
    ##popupRoot.after(20000, exit)
    popupButton = Button(popupRoot, text = s, font = ("Verdana", 12), bg = "yellow", command = lambda: os.system(onetwo))
    popupButton.pack()
    popupRoot.geometry('400x50+700+500')
    popupRoot.mainloop()

popupTwo("HEWWWWWEWEWKOO")

I apologize for the lack of an actual piece of code but this is the best I can do right now given the dev status of the other parts of the overall python script.
Note that the tkinter window may be triggered more than once in a single loop session.
If any other details are needed, I'll try my best to add more in.

A: Here's what you can do:
from tkinter import *

def popup(winName):
    newWin = Toplevel()
    btn2 = Button(newWin, text=winName)
    btn2.pack()

root = Tk()

btn = Button(root, text="Popup", command=lambda: popup("text"))
btn.pack()

root.mainloop()


text:
Q: Error executing a gem Initially, I tried to push my application up to heroku with the git push heroku master command and I got this error:
$ git push heroku master
Counting objects: 106, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (94/94), done.
Writing objects: 100% (106/106), 20.47 KiB | 0 bytes/s, done.
Total 106 (delta 21), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Ruby app detected
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.2.4
remote: ###### WARNING:
remote:        Removing `Gemfile.lock` because it was generated on Windows.
remote:        Bundler will do a full resolve so native gems are handled properly.
remote:        This may result in unexpected gem versions being used in your app.
remote:        In rare occasions Bundler may not be able to resolve your dependencies at all.
remote:        https://devcenter.heroku.com/articles/bundler-windows-gemfile
remote:
remote: -----> Installing dependencies using bundler 1.11.2
remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4
remote:        Fetching gem metadata from https://rubygems.org/...........
remote:        Fetching version metadata from https://rubygems.org/...
remote:        Fetching dependency metadata from https://rubygems.org/..
remote:        Resolving dependencies....
remote:        Installing json 1.8.3 with native extensions
remote:        Installing i18n 0.7.0
remote:        Installing rake 11.1.2
remote:        Installing minitest 5.8.4
remote:        Installing thread_safe 0.3.5
remote:        Installing builder 3.2.2
remote:        Installing erubis 2.7.0
remote:        Installing mini_portile2 2.0.0
remote:        Installing rack 1.6.4
remote:        Installing mime-types-data 3.2016.0221
remote:        Installing arel 6.0.3
remote:        Using bundler 1.11.2
remote:        Installing sass 3.4.21
remote:        Installing execjs 2.6.0
remote:        Installing coffee-script-source 1.10.0
remote:        Installing thor 0.19.1
remote:        Installing concurrent-ruby 1.0.1
remote:        Installing multi_json 1.11.2
remote:        Installing pg 0.18.4 with native extensions
remote:        Installing rails_serve_static_assets 0.0.5
remote:        Installing rails_stdout_logging 0.0.5
remote:        Installing sqlite3 1.3.11 with native extensions
remote:        Installing tilt 2.0.2
remote:        Installing tzinfo 1.2.2
remote:        Installing nokogiri 1.6.7.2 with native extensions
remote:        Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
remote:        /tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160328-319-1a7qvmc.rb extconf.rb
remote:        checking for sqlite3.h... no
remote:        sqlite3.h is missing. Try 'port install sqlite3 +universal',
remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
remote:        and check your shared library search path (the
remote:        location where your sqlite3 shared library is located).
remote:        *** extconf.rb failed ***
remote:        Could not create Makefile due to some reason, probably lack of necessary
remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may
remote:        need configuration options.
remote:        Provided configuration options:
remote:        --with-opt-dir
remote:        --without-opt-dir
remote:        --with-opt-include
remote:        --without-opt-include=${opt-dir}/include
remote:        --with-opt-lib
remote:        --without-opt-lib=${opt-dir}/lib
remote:        --with-make-prog
remote:        --without-make-prog
remote:        --srcdir=.
remote:        --curdir
remote:        --ruby=/tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME)
remote:        --with-sqlite3-dir
remote:        --without-sqlite3-dir
remote:        --with-sqlite3-include
remote:        --without-sqlite3-include=${sqlite3-dir}/include
remote:        --with-sqlite3-lib
remote:        --without-sqlite3-lib=${sqlite3-dir}/lib
remote:        extconf failed, exit code 1
remote:        Gem files will remain installed in /tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection.
remote:        Results logged to /tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out
remote:        Installing rack-test 0.6.3
remote:        Installing mime-types 3.0
remote:        Installing rdoc 4.2.2
remote:        Installing autoprefixer-rails 6.3.5
remote:        Installing uglifier 3.0.0
remote:        Installing coffee-script 2.4.1
remote:        Installing sprockets 3.5.2
remote:        Installing rails_12factor 0.0.3
remote:        Installing activesupport 4.2.5
remote:        An error occurred while installing sqlite3 (1.3.11), and Bundler cannot
remote:        continue.
remote:        Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.
remote:        Bundler Output: Fetching gem metadata from https://rubygems.org/...........
remote:        Fetching version metadata from https://rubygems.org/...
remote:        Fetching dependency metadata from https://rubygems.org/..
remote:        Resolving dependencies....
remote:        Installing json 1.8.3 with native extensions
remote:        Installing i18n 0.7.0
remote:        Installing rake 11.1.2
remote:        Installing minitest 5.8.4
remote:        Installing thread_safe 0.3.5
remote:        Installing builder 3.2.2
remote:        Installing erubis 2.7.0
remote:        Installing mini_portile2 2.0.0
remote:        Installing rack 1.6.4
remote:        Installing mime-types-data 3.2016.0221
remote:        Installing arel 6.0.3
remote:        Using bundler 1.11.2
remote:        Installing sass 3.4.21
remote:        Installing execjs 2.6.0
remote:        Installing coffee-script-source 1.10.0
remote:        Installing thor 0.19.1
remote:        Installing concurrent-ruby 1.0.1
remote:        Installing multi_json 1.11.2
remote:        Installing pg 0.18.4 with native extensions
remote:        Installing rails_serve_static_assets 0.0.5
remote:        Installing rails_stdout_logging 0.0.5
remote:        Installing sqlite3 1.3.11 with native extensions
remote:        Installing tilt 2.0.2
remote:        Installing tzinfo 1.2.2
remote:        Installing nokogiri 1.6.7.2 with native extensions
remote:
remote:        Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
remote:
remote:        /tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160328-319-1a7qvmc.rb extconf.rb
remote:        checking for sqlite3.h... no
remote:        sqlite3.h is missing. Try 'port install sqlite3 +universal',
remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
remote:        and check your shared library search path (the
remote:        location where your sqlite3 shared library is located).
remote:        *** extconf.rb failed ***
remote:        Could not create Makefile due to some reason, probably lack of necessary
remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may
remote:        need configuration options.
remote:
remote:        Provided configuration options:
remote:        --with-opt-dir
remote:        --without-opt-dir
remote:        --with-opt-include
remote:        --without-opt-include=${opt-dir}/include
remote:        --with-opt-lib
remote:        --without-opt-lib=${opt-dir}/lib
remote:        --with-make-prog
remote:        --without-make-prog
remote:        --srcdir=.
remote:        --curdir
remote:        --ruby=/tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME)
remote:        --with-sqlite3-dir
remote:        --without-sqlite3-dir
remote:        --with-sqlite3-include
remote:        --without-sqlite3-include=${sqlite3-dir}/include
remote:        --with-sqlite3-lib
remote:        --without-sqlite3-lib=${sqlite3-dir}/lib
remote:
remote:        extconf failed, exit code 1
remote:
remote:        Gem files will remain installed in /tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection.
remote:        Results logged to /tmp/build_7c1c7338241e4f828405d4c473f1dfdd/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out
remote:        Installing rack-test 0.6.3
remote:        Installing mime-types 3.0
remote:        Installing rdoc 4.2.2
remote:        Installing autoprefixer-rails 6.3.5
remote:        Installing uglifier 3.0.0
remote:        Installing coffee-script 2.4.1
remote:        Installing sprockets 3.5.2
remote:        Installing rails_12factor 0.0.3
remote:        Installing activesupport 4.2.5
remote:        An error occurred while installing sqlite3 (1.3.11), and Bundler cannot
remote:        continue.
remote:        Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.
remote:  !
remote:  !     Failed to install gems via Bundler.
remote:  !
remote:  !     Detected sqlite3 gem which is not supported on Heroku.
remote:  !     https://devcenter.heroku.com/articles/sqlite3
remote:  !
remote:
remote:  !     Push rejected, failed to compile Ruby app
remote:
remote: Verifying deploy...
remote:
remote: !       Push rejected to pengame.
remote:
To https://git.heroku.com/pengame.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/

When I try to install a gem I get this error:
$ gem install sqlite3 -v '1.3.11'
ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied @ rb_sysopen - C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/sqlite3-1.3.11-x86-mingw32/lib/sqlite3/2.1/sqlite3_native.so

Here's my Gemfile:
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.3', '>= 1.3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

gem 'bootstrap-sass'

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'
end

group :production do
  gem 'pg'
  gem 'rails_12factor'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

I'm not sure what I could be doing wrong.
My application works perfectly on the development server.
Anybody know why this might be happening??

A: Heroku doesn't support sqlite and is therefore refusing to install the native extensions. Since you're not using sqlite in production you should probably isolate the sqlite gem to environments run on your local machine (i.e. test and dev groups). Though I'd also recommend using Postgres in all environments, including tests, for consistency.
Perhaps you've seen this but there's also a very useful article on Heroku on how to setup Postgres on Heroku here: https://devcenter.heroku.com/articles/getting-started-with-rails4#heroku-gems.


text:
Q: Empty error when running Table to Excel tool The Table to Excel tool in the Conversion toolbox does not work for some reason. When I open it, it shows a red cross in the top left corner. When I try to run it an error pops up that says nothing. I've tried different input tables, different output locations and tried to do it it in python, which gives the "serious application error" and quits ArcMap. The result does not even show up in the geoprocessing window.
I have ArcMap 10.5.1.


text:
Q: dynamically adding Python sys.path entries that refer to inside a .zip file I have a Python program which adds something dynamically to sys.path. It works fine, but I'd like to distribute my Python program as a .zip file where __main__.py runs.
Can I add entries to sys.path from the zip file? After searching around a bit, I found the pkgutil documentation but I can't figure out what will work.
note: the stuff I need to add in sys.path includes .pyd and .dll files for Windows.

A: I'm not entirely sure I understand your question, but I'll have a crack at answering it anyway ...
Unfortunately, while you can import from a zipfile by adding it to sys.path:

sys.path contains a list of strings providing search locations for
  modules and packages. It is initialized from the PYTHONPATH
  environment variable and various other installation- and
  implementation-specific defaults. Entries in sys.path can name
  directories on the file system, zip files, and potentially other
  "locations" (see the site module) that should be searched for modules,
  such as URLs, or database queries. Only strings and bytes should be
  present on sys.path; all other data types are ignored. The encoding of
  bytes entries is determined by the individual path entry finders.
source: http://docs.python.org/3/reference/import.html#path-entry-finders

... that doesn't extend to .pyd and .dll files:

Any files may be present in the ZIP archive, but only files .py and
  .py[co] are available for import. ZIP import of dynamic modules (.pyd,
  .so) is disallowed.
source: http://docs.python.org/3/library/zipimport.html

I'm not aware of any way of working around this restriction.


text:
Q: cmake dependency problem I have 3 small dependent tools:
main-tool/
    tool1/
    tool2/

       * ----- main-tool ----- *
       |                       |
      tool1   ---------- >    tool2

The main-tool depends on tool1 & tool2.
The tool1 depends on tool2.
The CMakeFiles look like that:
main-tool/CMakeLists.txt
   SUBDIRS{"tool1"}
   SUBDIRS{"tool2"}

main-tool/tool1/CMakeLists.txt
   SUBDIRS("../tool2"}

I can compile tool1 smoothly. However whenever I want to compile main-tool the tool2 is included twice and produces error. How can I avoid this?
Thanks.

A: First off, you should use add_subdirectory() instead of subdirs(), which is deprecated.  You get more precise control of the order of processing that way.
Second, because everything depends on tool2, you should build tool2 first.
main-tool/CMakeLists.txt:
   add_subdirectory{"tool2"}
   add_subdirectory{"tool1"}

Don't add another add_subdirectory command in the tool1 directory.  There are two approaches you can use to access tool2 from the tool1 build.

*

*First, you could define some cmake variables in the top level main CMakeLists.txt related to tool2, then populate those variables in the tool2 build.  You might need to use the PARENT_SCOPE directive to set those variables from the tool2 subdirectory.  Then use those variables to access tool2 from the tool1 subdirectory.

*Alternatively, you could build all three tools (tool2, tool1, and main tool, in that order) from the top level CMakeLists file.  The build file can get long, but it saves headaches trying to manage the scope of cmake variables.  This is the approach I usually take and I recommend it.

To summarize, my recommendation is "one big CMakeLists.txt file".  Unless it gets really, really big.

A: You really should use SUBDIRS only for sub directories. What you actually mean by dependency? If you link some libraries together use TARGET_LINK_LIBRARIES, CMake will find them in your project regardless directory. If it is run time dependency, you usually care about it only after installation or you can use "${CMAKE_CURRENT_BINARY_DIR}/../tool2/tool2" as path to the binary.


text:
Q: How to reconstruct a 4 byte uint8 array into a uint32 integer I have a web app (javascript) that needs to send a arduino(ESP32) a 12bit value (0x7DF).
I have a websocket connection that only accepts a Uint8_t payload, so I split the value into 4 bytes (Uint8_t).
I can send the array to the arduino, but how do i reconstruct it back into a 32bit value?
This is the code i am using to turn it into bytes:
const uInt32ToBytes = (input) => {
  const buffer = Buffer.alloc(4)
  buffer.writeUInt32BE(input, 0)
  return [
    buffer[0],
    buffer[1],
    buffer[2],
    buffer[3]
  ]
}

//With an input of 0x7DF i get an output of [0, 0, 7, 223]

I have tried a lot of options given in other questions but none work. This is what they suggested:
uint32_t convertTo32(uint8_t * id) {
  uint32_t bigvar = (id[0] << 24) + (id[1] << 16) + (id[2] << 8) + (id[3]);
  return bigvar;
}
//This returns an output of 0.

Any help is appreciated
EDIT: My convert function has a test variant and not the original solution. fixed that.

A: On Arduino, ints are 16 bit, so id[0] << 24 (which promotes id[0] from uint8_t to int) is undefined (and wouldn't be able to hold the value anyways, making it always 0).
You need some casts beforehand:
return (static_cast<uint32_t>(id[0]) << 24)
     | (static_cast<uint32_t>(id[1]) << 16)
     | (static_cast<uint32_t>(id[2]) << 8)
     | (static_cast<uint32_t>(id[3]));


text:
Q: Providing context to Firebase EventListener I have setup a value event listener in Activity's onCreate method. In that method I am logging the data to console. I opened the activity and everything works fine. But if I close the activity and change the data, It still gets called and I can see that in logs.
So if I opened that activity say 5 times, on each update I see 5 logs messages.
Isn't there any solution where we can provide a context of that activity so the listeners die when the activity finishes.
rootRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.v(TAG, "Data Changed in Activity2");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

I need to provide too many value listeners in RecyclerView also. It also causes multiple value changed event calls after it is scrolled. Because it is bind a new liestener at the existing position, and no reference to remove from the onViewRecycled method. So they are called multiple times and changes data randomly on screen.
Having context makes it easier to set value event listeners. Is there way I can keep track of all the listeners? There is also no method to get the listeners for a reference.

A: As there is currently no way to provide a context to listeners, need to keep track of all attached listeners and remove them as shown by David in the answer here: https://stackoverflow.com/a/33782474/1820644

For managing value listeners inside the RecyclerView I have came up with a solution that works well. I am using FirebaseUI's RecyclerView, but the solution should work on every RecyclerView.
Step 1: Firstly create a global Map<String,ValueEventListener> in your activity:
HashMap<String, ValueEventListener> mRecyclerViewFirebaseListeners = new HashMap<>();

Step 2: Bind ValueEventListener in populateViewHolder (in firebaseUI) or onBindViewHodler and add it to our map mRecyclerViewFirebaseListeners. Also, attach a Tag to view holder with the value of our key
protected void populateViewHolder(final ViewHolder viewHolder,
                                  Boolean model, int position) {

    Log.v(TAG, "Populating viewHolder for position: " + position);

    // Get the key and add listener
    String key = this.getRef(position).getKey();
    ValueEventListener listener = mRootRef.child("events").child(key)
            .addValueEventListener(new ValueEventListener() {
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Log.v(TAG, "Event Data Change");
                    // ...
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.v(TAG, databaseError.getMessage());
                }
            });

    Log.v(TAG, "Listener set for event key: " + key + " (position: " +
            position + ")");

    // Add to our map and set tag on view holder
    mRecyclerViewFirebaseListeners.put(key, listener);
    viewHolder.itemView.setTag(R.id.TAG_RCV_EVENT_KEY, key);
    Log.d(TAG, "Added tag for position:" + position);

    // do other work here

}

Step 3: Remove a listener for the view holder when a view is recycled.
@Override
public void onViewRecycled(ViewHolder holder) {
    super.onViewRecycled(holder);

    // Get key from the view holder
    String key = (String) holder.itemView.getTag(R.id.TAG_RCV_EVENT_KEY);
    Log.v(TAG, "Recycling view set for key: " + key);

    // Remove listener for the retrieved key and also remove it from our map
    mRootRef.child("events").child(key)
            .removeEventListener(mRecyclerViewFirebaseListeners.get(key));
    mRecyclerViewFirebaseListeners.remove(key);
    Log.v(TAG, "On View Recycled, Removed Event listener for key: " + key);

    // ...

}

Step 4: Remove remaining listeners in onDestroy()
@Override
public void onDestroyView() {
    super.onDestroyView();

    // Iterate over map and remove listeners for the key
    for (Map.Entry<String, ValueEventListener> entry : mRecyclerViewFirebaseListeners.entrySet()) {
        String key = entry.getKey();
        ValueEventListener value = entry.getValue();
        mRootRef.child("events").child(key).removeEventListener(value);
        Log.v(TAG, "Removed Event listener for key: " + key);
    }
}

This will remove all your listeners from recycler view.
If you have more value listeners other than recyclerview, use a new map for those others all combine it in this map if it matches the key pattern for the same path.
Alternatively you can put a full path instead of just a key as the key of a Map. Like in example we have used value of 'key' under the child events as the key of a Map, but you can put events/<key> as the key of a Map and remove in one go in onDestroy with mRootRef.child("<your_combined_key_from_map>").removeListener(listener).
Hope this helps someone.


text:
Q: Unable to create a GCP machine due to access rights I have multiple GCP servers and am trying to build a new one based on cpanel with ubuntu. Now whenever I try and create it tells me I'm unable to build and try giving access rights to my account.
I've gone in and added google compute admin to my account and a firewall admin still failing
Any ideas


text:
Q: How can I get the pixel color of an image at the current pointer position in a universal app with C#? I want to get the Pixel Color of an Image at the current pointer/mouse position in a universal app with C#. As the Bitmap Class does not work anymore, all the hints I found, were useless. The purpose of this is to program a color picker.

A: Using an image that's a resource in the project, this seems to work (using WriteableBitmapEx)
WriteableBitmap wb;

private async void ImageOpened(object sender, RoutedEventArgs e)
{
    wb = await BitmapFactory.New(1, 1).FromContent(((sender as Image).Source as BitmapImage).UriSource);
}

private async void ImageTapped(object sender, TappedRoutedEventArgs e)
{
    var pos = e.GetPosition(sender as UIElement);

    var px = wb.GetPixel((int)pos.X, (int)pos.Y);

    System.Diagnostics.Debug.WriteLine($"R: {px.R} G: {px.G} B: {px.B} ");
}