text:
Q: Grunt connect-modrewrite do not work I used generator-angular for create my project.
I use HTML5 History. ($locationProvider.html5Mode(true).hashPrefix('!');)
For url rewrite I use connect-modrewrite
I did all like described in tutorial.
Here is my GruntFile.js
// Generated on 2013-12-13 using generator-angular 0.6.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
var modRewrite = require('connect-modrewrite');

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // proxy for backend
  grunt.loadNpmTasks('grunt-connect-proxy');

  // lib for run rales server
  grunt.loadNpmTasks('grunt-exec');

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      js: {
        files: ['{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all']
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 80,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ],
          middleware: function (connect, options) {
            var middlewares = [];
            options.base.forEach(function(base) {
              // Serve static files.
              middlewares.push(connect.static(base));
            });
            middlewares.push(proxySnippet);
            middlewares.push(modRewrite([
              '^/offers$ /index.html',
              '!\\.html|\\.js|\\.css|\\woff|\\ttf|\\swf$ /index.html'
            ]));
            return middlewares;
          }
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      },
      proxies: [
        {
          context: '/api',
          host: 'localhost',
          port: 8080,
          https: false,
          changeOrigin: true,
          xforward: true,
          rewrite: {
            '^/api': ''
          }
        }
      ]
    },

    exec: {
      rales: {
        // here I use code for run backend
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ],
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: '<%= yeoman.app %>/bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>']
      }
    },

    // The following *-min tasks produce minified files in the dist folder
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },
    htmlmin: {
      dist: {
        options: {
          // Optional configurations that you can uncomment to use
          // removeCommentsFromCDATA: true,
          // collapseBooleanAttributes: true,
          // removeAttributeQuotes: true,
          // removeRedundantAttributes: true,
          // useShortDoctype: true,
          // removeEmptyAttributes: true,
          // removeOptionalTags: true*/
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>',
          src: ['*.html', 'views/*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // Allow the use of non-minsafe AngularJS files. Automatically makes it
    // minsafe compatible so Uglify does not destroy the ng references
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            'bower_components/**/*',
            'images/{,*/}*.{webp}',
            'fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: [
            'generated/*'
          ]
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server',
        'copy:styles'
      ],
      test: [
        'compass',
        'copy:styles'
      ],
      dist: [
        'compass:dist',
        'copy:styles',
        'imagemin',
        'svgmin',
        'htmlmin'
      ]
    },

    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%= yeoman.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',
      'autoprefixer',
      'configureProxies',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('unicorn', [
      'exec:rales'
  ]);

  grunt.registerTask('server', function () {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve']);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngmin',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};

What I did wrong ? When I reload page in browser I've got "Cannot GET /offers"

A: Problem was with grunt-connect-proxy and connect-modrewrite.
      middleware: function (connect, options) {
        var middlewares = [];

        middlewares.push(modRewrite([
          '!/api|/assets|\\.html|\\.js|\\.css|\\woff|\\ttf|\\swf$ /index.html'
        ]));
        options.base.forEach(function (base) {
          // Serve static files.
          middlewares.push(connect.static(base));
        });
        middlewares.push(proxySnippet);
        return middlewares;
      }

If I push modRewrite to middlewares after proxySnippet (grunt-connect-proxy) - connect-modrewrite don't work. I decided to put modRewrite before and exclude all grunt-connect-proxy contexts (/api /assets) and all become to work well :)
Hope it will be useful for some one :)


text:
Q: how to upload file to Google cloud Storage via Delphi hello my friends i am need upload a files to google cloud storage account using Delphi , have one have a example for me. Thank

A: There is a component: TAdvGDrive that can do this for you.
http://www.tmssoftware.com/site/cloudpack.asp

redpajama_set_name: RedPajamaStackExchange


text:
Q: DKIM for email through Google Apps domain with external outbound relay I'd like to enable the new Domain Keys DKIM email authentication feature for a domain hosted in Google Apps.
Some of my users use an external SMTP gateway (such that when they send email, it doesn't go through smtp.gmail.com).
I have an SPF record configured for the domain, and this allows the external SMTP gateways as valid SMTP hosts. (I realise SPF is different to DKIM)
Will enabling DKIM adversely affect the external gateway email? eg. Are the externally sent emails at risk of being marked as spam because they would not have the DKIM signature, or will DKIM only positively benefit emails sent through Google's SMTP server?

A: Your users can use an external SMTP server. But of course, their emails will have a worse reputation, compared to those directly sent from Google's server, and for two reasons :

*

*The first one is that they won't be signed by DKIM (luckily the server is declared in the SPF record)

*You'll send mails from a server that is not declared as a MX for the domain

We're just talking here about email reputation (ie the spam score). But don't worry it will work : You may just sometimes have mails seen as spam, in general with big companies with high spam protections (AOL, Yahoo, Gmail, Hotmail, ...).


text:
Q: Evaluating Indefinite Integral $$∫  \frac{1}{(1-x^3)^{1/3}}\, dx$$
I tried substituting $1-x^3$ as $t^3$ but I am not able to calculate it after that.
Thanks!

A: For solving
$$
I=∫\frac{1}{\sqrt[3]{1-x^3}}\, \mathrm{d}x
$$
Let $t=\dfrac{x}{\sqrt[3]{1-x^3}}$,
solved
$$
\begin{aligned}
x&=\frac{t}{\sqrt[3]{t^3+1}}\\
\mathrm{d}x&=\frac{1}{(t^3+1)\sqrt[3]{t^3+1}}\mathrm{dt}\\
\end{aligned}
$$
and
$$
\frac{1}{\sqrt[3]{1-x^3}}=\sqrt[3]{t^3+1}
$$
then
$$
I = \int\frac{\sqrt[3]{t^3+1}}{(t^3+1)\sqrt[3]{t^3+1}}\mathrm{dt}=\int\frac{1}{t^3+1}\mathrm{d}t
$$

The next part is simple.
$$
\begin{aligned}
I
&= \frac{1}{3}\int\frac{1}{1+(-1)^{2/3} t}+\frac{1}{1-(-1)^{1/3}t}+\frac{1}{t+1}\mathrm{d}t\\
&= \frac{1}{3}\left(\ln (t+1)-(-1)^{1/3} \ln \left((-1)^{1/3}-t\right)+(-1)^{2/3} \ln \left(t+(-1)^{2/3}\right)\right)\\
&=\frac{1}{3} \left(\ln \left(\frac{x}{\sqrt[3]{1-x^3}}+1\right)+(-1)^{2/3} \ln \left(\frac{x}{\sqrt[3]{1-x^3}}+(-1)^{2/3}\right)-(-1)^{1/3} \ln \left((-1)^{1/3}-\frac{x}{\sqrt[3]{1-x^3}}\right)\right)
\end{aligned}
$$
Finally, take the derivation and verify that the result is correct.
D[1 / 3 (-(-1)^(1 / 3) Log[(-1)^(1 / 3) - x / (1 - x^3)^(1 / 3)] + Log[1 + x / (1 - x^3)^(1 / 3)] + (-1)^(2 / 3) Log[(-1)^(2 / 3) + x / (1 - x^3)^(1 / 3)]), x] // FullSimplify


text:
Q: Select all columns except one when joining two tables in AWS Athena I want to join two large tables with many columns using Presto SQL syntax in AWS Athena. My code is pretty simple:
select
    *
from TableA as A
left join TableB as B
on A.key_id = B.key_id
;

After joining, the primary key column (key_id) is repeated two times. Both tables have more than 100 columns, and the joining takes very long. How can I fix it such that the key_id column does not repeat twice in the final result?
P.S. AWS Athena does not support except command, unlike Google BigQuery.

A: This would be a nice feature, but is not part of standard SQL. The EXCEPT keyword is a set-based operation (i.e. filtering rows).
In Athena, as with standard SQL, you will have to specify the columns you want to include. The argument for this is that it's lower maintenance, and in fact best practice is to always explicitly state the columns you want - never leaving this to "whatever columns exist". This will help ensure your queries don't change behaviour if/when your table structure changes.
Some SQL languages have features like this. I understand Oracle has this too. But to my knowledge Athena (/ PrestoSQL / Trino) does not.


text:
Q: BubbleSort Output Graph Trouble Hi I have written a bubble sort application in JAVA. The application is working fully and give sufficient output, but it doesn't give me an out put for average time.
Here is my code:
public class BubbleSort {
static double bestTime = 10000000, worstTime = 0;
public static void main(String[] args) {
    int BubArray[] = new int[]{**#interger values are placed in here#**};
         System.out.println("Unsorted List Before Bubble Sort");
         for(int a = 0; a < BubArray.length; a++){
         System.out.print(BubArray[a] + " ");
            }

        System.out.println("\n Bubble Sort Execution ...");

                    for(int i=0; i<10000;i++) {
                        bubbleSortTimeTaken(BubArray, i);
                        }

         int itrs = bubbleSort(BubArray);
    System.out.println("");
    System.out.println("Array After Bubble Sort");
    System.out.println("Moves Taken for Sort : " + itrs + " Moves.");
    System.out.println("BestTime: " + bestTime + " WorstTime: " + worstTime);
    System.out.print("Sorted Array: \n");

        for(int a = 0; a < BubArray.length; a++){
                System.out.print(BubArray[a] + " ");
        }
}

private static int bubbleSort(int[] BubArray) {

int z = BubArray.length;
int temp = 0;

int itrs = 0;

for(int a = 0; a < z; a++){
        for(int x=1; x < (z-a); x++){

                if(BubArray[x-1] > BubArray[x]){

                        temp = BubArray[x-1];
                        BubArray[x-1] = BubArray[x];
                        BubArray[x] = temp;

                }

                itrs++;
        }
}

return itrs;
}

public static void bubbleSortTimeTaken(int[] BubArray, int n)
{
long startTime = System.nanoTime();
    bubbleSort(BubArray);
    double timeTaken = (System.nanoTime() - startTime);
    if (timeTaken > 0)
    {
        worstTime = timeTaken;
    }
    else if (timeTaken < bestTime)
    {
        bestTime = timeTaken;
    }

    System.out.println(n + "," + timeTaken);

}
}

But I am unsure of how to a) get the average time for each and also how I would plot the Best, Average and Worst Case results on a graph.
Here is a sample output:
Unsorted List Before Bubble Sort
#Integers Values of Unsorted List#

Bubble Sort Execution ... **#(execution number, time in nanoseconds)#**
0,6336584.0
1,5063668.0
2,3364580.0
3,3373289.0
4,3755912.0
5,3383866.0
....
9995,3431772.0
9996,3368312.0
9997,3743469.0
9998,4639362.0
9999,3433638.0

Moves Taken for Sort : 499500 Moves.
BestTime: 1.0E7 WorstTime: 3433638.0

Also I'm not sure if my bubbleSortTimeTaken() function works properly as 1.0E7 is given for every run of the program regardless of the number of integers used
(100, 1000, 10000, 100000, 1000000) have been tested. I wish to find the average, best and worst case to plot.
Any help would be appreciated, thanks.

A:    if (timeTaken > 0)   // <- PROBLEM, Shouldn't be zero
    {
        worstTime = timeTaken;
    }
    else if (timeTaken < bestTime) //<- PROBLEM! , the 2 comparisons are unrelated
    {
        bestTime = timeTaken;
    }

Right there. If timeTaken>0, which it will be mostly, the else if is never executed.
Thus, bestTime never gets updated, and retains the original value (1E7).
To fix this, the function should be modified to look like :
public static void bubbleSortTimeTaken(int[] BubArray, int n)
{
long startTime = System.nanoTime();
    bubbleSort(BubArray);
    double timeTaken = (System.nanoTime() - startTime);
    if (timeTaken > worstTime)
    {
        worstTime = timeTaken;
    }
    if (timeTaken < bestTime)
    {
        bestTime = timeTaken;
    }

    System.out.println(n + "," + timeTaken);

}
}

Note that  I have added a possible fix about worstTime too.

A:  if (timeTaken > 0)
{
    worstTime = timeTaken;
}

This should be
 if (timeTaken > worstTime)
{
    worstTime = timeTaken;
}

otherwise you'll not be setting this properly. This explains why your bestTime is always 10e7.
To find the average, simply do it a certain number of times, recording all the times, then add them and divide by number of times done.


text:
Q: sys.objects get modfiy_date is showing empty table I am trying to get name, create_date and modify_date of procedures, table, functions, and views from sql-server using this query
use ecomm
select name, create_date, modify_date from sys.objects where type = 'U' and name = 'dbo.Users'

It is returning empty table instead of populating it with data. The query is correct, but I don't know why it is returning empty results.
Please correct me where I am going wrong.

My Database version is
Microsoft SQL Server 2017 (RTM-GDR) (KB4505224) - 14.0.2027.2 (X64)


text:
Q: How to print div in landscape mode in angularjs I have a table with some datas. In my screen its in correct format, but i want on click of print button, it should print the div in landscape mode.
jsfiddle
In this example, if I click print it will print the page exactly what it is. But i want to print in landscape. Can anyone please tell me how to do this?

<link rel="stylesheet" type="text/css" href="styles.css">
<title>Form</title>

AROPOLIS INSUARANCE BROKERS LTD.

2nd Floor, Shamneel Court, Parklands Road, Nairobi, Kenya.

P.O. Box 1157, Sarit Centre, Post Offive, Nairobi 00606, Kenya.

Telephones 020 - 4444746 / 7 / 8, Fax 020 - 4444745. Email info@acropolisinsurance.com

CLAIM FORM FOR PROPERTY DAMAGE OR LOSS.

      Applicable to Fire, Special Perils, Home Covers, Theft, All-Risks, Money, Baggage and Glass. The issue of this form is not an admission of liability on the part of the company. All questions must be answered in full.

Name of Insurer:

Type of Cover:

    Policy
Number:  <input type="text" class="input" size="30">
    Renewal
date:

Last premium

    date paid on:

    INSURED

    Name: <?php echo $firstname; ?> <?php echo $middlename; ?> <?php echo $lastname; ?>

    Occupation / Profession: <?php echo $occupation; ?>

    Address: <?php echo $physadd; ?>

    Telephone: <?php echo $mobileno; ?>
    Fax/Email: <?php echo $email; ?>

    CIRCUMSTANCES GIVING RISE TO A CLAIM

    Date of
Loss
    Time of
Loss

When/Who discovered
the loss or damage

Describe fully how the loss or damage occured

    GENERAL INFORMATION

    Type of premises involved

Were the permises unoccupied?
     Yes
        <input type="checkbox">
     |
       No <input type="checkbox">. if so, when were they last occupied?

Are the premises self-contained?
     Yes <input type="checkbox">
     |
       No <input type="checkbox">. if not, please list the names of other occupants

    Are you the owner of premises? Yes <input type="checkbox">
    | No
    <input type="checkbox">
    Are you responsible for repairs? Yes <input type="checkbox">
    |
    No <input type="checkbox">

Have you any suspicion as to parties implicated? Yes
      <input type="checkbox">
      | No
      <input type="checkbox">

Is there any other insurance in force providing covers for this loss? If so, give particulars including insurers name, address, policy numbers, type of policy, etc.

Have you suffered similar loss or damage in the past? If so, give particulars and whether claim was made on insurers

At the time of loss, what was

        the value of: a) the buildings? _______________________   b) all the property in the premises? _______________________

    Complete in all cases involving THEFT, MALICIOUS DAMAGE or MISSING ARTICLES

When were the Police notified (date & time)?

Address of the Police Station?

what other steps have you taken to recover property?

Give full details of method of entry to premmises

If alarm intalled, did it function properly? If not, give reasons

Are guards employed? If so, name the firm

Do other parties i.e. banks have an interest on property lost or damaged? If so, state reasons

    Compete in all cases involving loss in transit

Starting point and destination of transit

Who was accompanying property lost or damaged?

If employees, state names, age and duties

Are they insured under Fidelity Guarantee Policy? If so, give insurer's name, address and policy number

    How often is
 this transit made?
    What is maximum ever
 carried at on time?

    AMOUNT CLAIMED

    Kenyan Shilings

    Amount_________________________________Please refer to the following pages for details

    I / we declare that I / wehave not withheld any material information and that all statments made on this form are true to the best of my / our knowledge and belief. And that articles and property described overleaf belong to me / us, and that no other person has any interest whether as owner, mortgagee, trustee or otherwise except as mentioned in the policy.

Date____________________  Signature_____________________________________________

(If policy Holder body corporate, title of person signing & Company Stamp)

logout | Print

A: Hi just change the  @page {size: a4 portrait;} to @page { size: a4 landscape}
in your HTML file. and you should be good to go.
Thanks
code snippet just in case.

<link rel="stylesheet" type="text/css" href="styles.css">
<title>Form</title>

AROPOLIS INSUARANCE BROKERS LTD.

2nd Floor, Shamneel Court, Parklands Road, Nairobi, Kenya.

P.O. Box 1157, Sarit Centre, Post Offive, Nairobi 00606, Kenya.

Telephones 020 - 4444746 / 7 / 8, Fax 020 - 4444745. Email info@acropolisinsurance.com

CLAIM FORM FOR PROPERTY DAMAGE OR LOSS.

      Applicable to Fire, Special Perils, Home Covers, Theft, All-Risks, Money, Baggage and Glass. The issue of this form is not an admission of liability on the part of the company. All questions must be answered in full.

Name of Insurer:

Type of Cover:

    Policy
Number:  <input type="text" class="input" size="30">
    Renewal
date:

Last premium

    date paid on:

    INSURED

    Name: <?php echo $firstname; ?> <?php echo $middlename; ?> <?php echo $lastname; ?>

    Occupation / Profession: <?php echo $occupation; ?>

    Address: <?php echo $physadd; ?>

    Telephone: <?php echo $mobileno; ?>
    Fax/Email: <?php echo $email; ?>

    CIRCUMSTANCES GIVING RISE TO A CLAIM

    Date of
Loss
    Time of
Loss

When/Who discovered
the loss or damage

Describe fully how the loss or damage occured

    GENERAL INFORMATION

    Type of premises involved

Were the permises unoccupied?
     Yes
        <input type="checkbox">
     |
       No <input type="checkbox">. if so, when were they last occupied?

Are the premises self-contained?
     Yes <input type="checkbox">
     |
       No <input type="checkbox">. if not, please list the names of other occupants

    Are you the owner of premises? Yes <input type="checkbox">
    | No
    <input type="checkbox">
    Are you responsible for repairs? Yes <input type="checkbox">
    |
    No <input type="checkbox">

Have you any suspicion as to parties implicated? Yes
      <input type="checkbox">
      | No
      <input type="checkbox">

Is there any other insurance in force providing covers for this loss? If so, give particulars including insurers name, address, policy numbers, type of policy, etc.

Have you suffered similar loss or damage in the past? If so, give particulars and whether claim was made on insurers

At the time of loss, what was

        the value of: a) the buildings? _______________________   b) all the property in the premises? _______________________

    Complete in all cases involving THEFT, MALICIOUS DAMAGE or MISSING ARTICLES

When were the Police notified (date & time)?

Address of the Police Station?

what other steps have you taken to recover property?

Give full details of method of entry to premmises

If alarm intalled, did it function properly? If not, give reasons

Are guards employed? If so, name the firm

Do other parties i.e. banks have an interest on property lost or damaged? If so, state reasons

    Compete in all cases involving loss in transit

Starting point and destination of transit

Who was accompanying property lost or damaged?

If employees, state names, age and duties

Are they insured under Fidelity Guarantee Policy? If so, give insurer's name, address and policy number

    How often is
 this transit made?
    What is maximum ever
 carried at on time?

    AMOUNT CLAIMED

    Kenyan Shilings

    Amount_________________________________Please refer to the following pages for details

    I / we declare that I / wehave not withheld any material information and that all statments made on this form are true to the best of my / our knowledge and belief. And that articles and property described overleaf belong to me / us, and that no other person has any interest whether as owner, mortgagee, trustee or otherwise except as mentioned in the policy.

Date____________________  Signature_____________________________________________

(If policy Holder body corporate, title of person signing & Company Stamp)

logout | Print


text:
Q: reading signals sent between 2 radios, serial comms I am currently reading from a reciever via the com port on my pc, reading the signals sent between 2 other radios. The problem I am having is how it is displaying to the listbox properly, as it doesnt start at the top, it puts lots of blank lines above the output, forcing me to scroll down to see it, and also that my loop is behaving strangely.
Here is the code:
void Cserial_NewDlg::OnBnClickedButton1()
{
    CString tempStr;
    bool bReading = true;
    //memset(&port, 0, sizeof(port));
    //memset(buffer,0,BUFFER_SIZE);
    while(bReading) {
        ReadFile(file,&buffer[0],BUFFER_SIZE,&bytesRead,NULL); //reading opened port
        if(bytesRead == 0)
            break;
        tempStr = buffer;
        int Pos = tempStr.Find("TX",0); //finding the start of each transmission
        if(Pos > 0){/*memcpy*/}
        else {
            memmove(processBuffer,&buffer[Pos],PROCESS_SIZE); //copying buffer to a new buffer of correct size
            m_ListBox.AddString(processBuffer); //displaying
        }
        /*if(bytesRead == PROCESS_SIZE)
            bReading = false;*/
    }
}

The first time the 'read' button is pressed it reads in fine, but I am having a problem with the processBuffer(29 bytes, as that is the length of the tranmission) not re-copying the data from the previous buffer(64 bytes, allowing for some overflow) after the first time round the loop, so its forcing me to press the read button again, this is not what I intended and I can't spot the problem, any ideas?

A: The Pos > 0 branch in your listing is a dead branch, but this is a problem because your else only gets executed if "TX" is at the very beginning, or not found at all.  If ever you read your buffer, and "TX" does not appear, you have a buffer read error, where you start at index -1 of buffer.
Basically, say you have a short read that doesn't return an entire message, or say you simply have an ill-formatted message that doesn't contain this "TX" key you're looking for - the CString::Find function returns -1, meaning "not found".  In those cases, you have to continue reading (maybe throw a sleep in there?) until you have found the end of your message before you add it.  This would prevent multiple button-presses.
I would encourage you to gave the details on what your expected message looks like - that will help me give more targeted advice.

A: You'd be better off using a std::deque<char>  for your processBuffer. As the name suggests, that class is designed for a double-ended queue. You can simply append the bytes from buffer, and take bytes from the start.


text:
Q: Change margin programmatically in WPF / C# For this xaml:
<WebBrowser Name="test" Margin="0,0,0,0" />

How can I change the web browser control margin on top to be -5 programmatically in C#?

A: test.Margin = new Thickness(0, 0, 0, 0);

A: test.Margin = new Thickness(-5);

A: You can access the control from code behind using the Name property.
In this case, test.Margin property can be used to change it dynamically.
Margin is set as thickness, so the solution could be:
test.Margin = new Thickness(0,-5,0,0);

Note: Thickness have 4 parameters viz left, top, right and bottom. In above solution, we have just changed top margin, rest remained unchanged.

A: test.Margin = new Thickness(0, -5, 0, 0);

Alignment, Margins and Padding Overview (MSDN)
FrameworkElement.Margin (MSDN)


text:
Q: How to not make the randint to not repeat a question that was already shown before? How to not make the randint to not repeat a question that was already shown before. after finishing the range of 10 in randint how can i add an option where the program will ask the user if it desire to choose another level. after i tried doing it in else. even if only 2 questions have asked so far. it always ended the quiz immedietely. what did i missed out with this code. help me please
import random
import string

def name():
    allowed_alpha = string.ascii_letters + string.whitespace + string.digits
    while True:
        Name = input("What is your name? ")
        if all(c in allowed_alpha for c in Name):
            grade()
        else:
            print("invalid character")
            name()

def grade():
    allowed_alpha = string.ascii_letters + string.whitespace + string.digits
    while True:
        grade.var = input("What is your grade level? (Grade 8, Grade 9, Grade 10) ")
        if all(c in allowed_alpha for c in grade.var):
            diff()
        else:
            print("invalid character")

def diff():
    Difficulty = input("\nWhat is your chosen difficulty level? (Easy, Medium, Hard) ")
    if grade.var == ("Grade 8"):
        correct = 0
        if Difficulty == ("Easy"):
            Difficulty = 1
            QN = 10
            for question in range (QN):
                Question1 = 1
                Question2 = 2
                Question3 = 3
                Question4 = 4
                Question5 = 5
                Question6 = 6
                Question7 = 7
                Question8 = 8
                Question9 = 9
                Question10 = 10
                QN = random.randint(1, 10)
                if QN == 1:
                    QA = input("\nThis is a part of speech that shows the relationship of a noun or pronoun to another word. They can indicate time, place, or relationship. \n(noun, adjective, pronoun, preposition)\n")
                    if QA == "preposition":
                        print("Correct")
                        correct = correct + Difficulty
                    else:
                        print("incorrect")
                        correct = correct - Difficulty
                        print("Your current score is " +str(correct))
                    input("\npress enter to continue")

                if QN == 2:
                    QA = input("\nWhich word indicates correct spelling? \n(belive beleive, believe, bilieve)\n")
                    if QA == "believe":
                        print("Correct")
                        correct = correct + Difficulty
                    else:
                        print("incorrect")
                        correct = correct - Difficulty
                        print("Your current score is " +str(correct))
                    input("\npress enter to continue")

                if QN == 3:
                    QA = input("\nthis figure of speech pertains to the use of 'as' and 'like' in comparing. \n(metaphor, personification, simile, hyperbole)\n")
                    if QA == "simile":
                        print("Correct")
                        correct = correct + Difficulty
                    else:
                        print("incorrect")
                        correct = correct - Difficulty
                        print("Your current score is " +str(correct))
                input("\npress enter to continue")

                if QN == 4:
                    QA = input("\nThe part of a sentence or clause containing a verb and stating something about the subject \n(subject, phrase, clause, predicate)\n")
                    if QA == "predicate":
                        print("Correct")
                        correct = correct + Difficulty
                    else:
                        print("incorrect")
                        correct = correct - Difficulty
                        print("Your current score is " +str(correct))
                    input("\npress enter to continue to the next question")

                if QN == 5:
                    QA = input("\na figure of speech that expresses exageration \n(simile, hyperbole, metaphor, personification)")
                    if QA == "hyperbole":
                         print("Correct")
                         correct = correct + Difficulty
                    else:
                        print("incorrect")
                        correct = correct - Difficulty
                        print("Your current score is " +str(correct))
                    input("\npress enter to continue to the next question")
                else:
                    next = input("Do you want to proceed to another level? (yes, no) ")
                    if next == "yes":
                        grade()
                    if next == "no":
                        exit()
                    else:
                        break
name()

A: without getting into your quiz logic, if you want to randomly pop an item from a list you may use a function like the following:
from random import Random
def rand_pop(random: Random, lst: list):
    if not lst:
        return None
    index = random.randint(0, len(lst)-1)
    return lst.pop(index)

Then, you can use it in the following way:
random = Random()
list_of_questions = [...]
for i in range(len(list_of_questions)):
    question = rand_pop(random, list_of_questions)
    print(question)
    ...


text:
Q: Drupal - Add image and text under contact form I am trying to add an image and some text directly under the 'send message' form in Drupal 7.  When I create a new block and add it under the contact form it displays the block far below the form.  I have tried several ways to line up the block so it displays correctly, but no matter what I try it does not appear directly under the 'send message' section.
So now I'm thinking I might be able to simply edit the php file related to the contact form.
So I'm editing contact.pages.inc and I see:
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Send message'),
);

Any idea how I can do this?
Thanks

A: It is recommended that you avoid hacking core or other modules. From the image you posted, the problem looks like a CSS one. You could place the form and the block that should appear below it in the same region (let's say sidebar 1) and the block on the right in its own region (sidebar 2). Then set width on sidebar 1 and sidebar 2 to 50% and float the sidebars left.


text:
Q: UITableView, registerClass and detailTextLabel -- strange behavior Recently I noticed the following behavior and I can't understand why does it work as it is.
I have a UITableView on my storyboard and the following code in the view controller:
override func viewDidLoad() {
    super.viewDidLoad()

    self.threadsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: UITableViewCell? = self.threadsTableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
    }

    cell!.detailTextLabel!.text = "str"
}

In this case application crashes at the
cell!.detailTextLabel!.text = "str"

line because detailTextLabel is nil
Then I decided to remove the registerClass function call and noticed that code doesn't really crash anymore, but dequeueReusableCellWithIdentifier function call returns nil every time. I think that I don't somehow enable the "Subtitle" style of the table view's cells in the storyboard, but I don't see any option like this in the Interface Builder.
What am I doing wrong? How can I fix it?
Thanks in advance.

A: In your storyboard, do you have prototype cells within your tableView?  If not, drag a table view cell in from the object library (bottom right) and embed it in the table view.  You can then use the attributes inspector for that cell to set the reuseIdentifier.  If the cell style defaults to "Custom", amend it to "Subtitle" - IB will then automatically add labels for textLabel and detailTextLabel (and will hook them up to the outlets in UITableViewCell).  See below:


text:
Q: Window function and time difference in Big Query I have a big query table defined as:

+----+----------------------------+------------+
| id |            time            |   event    |
+----+----------------------------+------------+
|  1 | 2015-10-01 16:31:48.000000 | signup     |
|  1 | 2015-10-01 16:41:48.000000 | 1_purchase |
|  1 | 2015-10-01 16:51:48.000000 | 2_purchase |
|  2 | 2015-10-01 16:31:48.000000 | signup     |
|  2 | 2015-10-01 16:41:48.000000 | 1_purchase |
|  3 | 2015-10-01 16:31:48.000000 | signup     |
+----+----------------------------+------------+

I would like to calculate time differences within each id group (1,2,3), obtaining a result as:

+----+----------------------------+------------+-----------------+--+
| id |            time            |   event    | timedifference  |  |
+----+----------------------------+------------+-----------------+--+
|  1 | 2015-10-01 16:31:48.000000 | signup     | -               |  |
|  1 | 2015-10-01 16:41:48.000000 | 1_purchase | 00:10:00.000000 |  |
|  1 | 2015-10-01 16:61:48.000000 | 2_purchase | 00:20:00.000000 |  |
|  2 | 2015-10-01 16:31:48.000000 | signup     | -               |  |
|  2 | 2015-10-01 16:41:48.000000 | 1_purchase | 00:10:00.000000 |  |
|  3 | 2015-10-01 16:31:48.000000 | signup     | no_purchase     |  |
+----+----------------------------+------------+-----------------+--+

After some research, I guess I would need to use window function... But I couldn't figure out any solution.
Any help is highly appreciated!
Best,
V.

A: Yes, you can use analytic window functions for that - here is one way to do it using FIRST_VALUE analytic function:
SELECT id, time, event, (time - firsttime) / 60000000 FROM (
SELECT id, time, event,
       FIRST_VALUE(time) OVER(PARTITION BY id ORDER BY time) AS firsttime FROM
(SELECT 1 id, TIMESTAMP('2015-10-01 16:31:48.000000') time, 'signup' event),
(SELECT 1 id, TIMESTAMP('2015-10-01 16:41:48.000000') time, '1_purchase' event),
(SELECT 1 id, TIMESTAMP('2015-10-01 16:51:48.000000') time, '2_purchase' event),
(SELECT 2 id, TIMESTAMP('2015-10-01 16:31:48.000000') time, 'signup' event),
(SELECT 2 id, TIMESTAMP('2015-10-01 16:41:48.000000') time, '1_purchase' event),
(SELECT 3 id, TIMESTAMP('2015-10-01 16:31:48.000000') time, 'signup' event)
)

A: select
  id, time, event,
  time(sec_to_timestamp((timestamp_to_sec(timestamp(time)) -
    timestamp_to_sec(timestamp(prev_time))))) as timedifference,
  (timestamp_to_sec(timestamp(time)) -
    timestamp_to_sec(timestamp(prev_time)))/60 as timefifference_in_min,

  right('0' + string(datediff(timestamp(time),timestamp(prev_time))),2) + ' ' +
  time(sec_to_timestamp((timestamp_to_sec(timestamp(time)) -
    timestamp_to_sec(timestamp(prev_time))))) as timedifference_as_dd_hh_mm_ss

from (
  select
    id, time, event,
    lag(time) over(partition by id order by time) as prev_time
  from (
  select f0_ as id, f1_ as time, f2_ as event from
    (select 1, '2015-10-01 16:31:48.000000', 'signup'),
    (select 1, '2015-10-01 16:41:48.000000', '1_purchase'),
    (select 1, '2015-10-01 16:51:48.000000', '2_purchase'),
    (select 2, '2015-10-01 16:31:48.000000', 'signup'),
    (select 2, '2015-10-01 16:41:48.000000', '1_purchase'),
    (select 3, '2015-10-01 16:31:48.000000', 'signup')
  )
)
order by id, time


text:
Q: how to match partial search query from 2 columns in lumen I have a table called stores with a name and address column.
I have a store record with name; "Target" and address; "112 W 34th St., New York, NY 10120, United States".
My Expectation:
querying the database for "Target NY" should return the above record
Current Result:
the database query can't find the record.
What I have tried:
$stores = DB::table('stores')
        ->where('name', 'like', "%$query%")
        ->orWhere('address', 'like', "%$query%")
        ->get();

the above query is unable to find the record.
I have also tried concatenating the query on both columns
 $stores = DB::select("
            SELECT *
            FROM stores
            WHERE CONCAT(name, ' ', address) LIKE '%".$query."%'
           ");

the example above can't find the record as well.
I don't want to believe that it's impossible to query the table as i want.
and if it's possible to perform that query, how can i do it?

A: You can use MATCH and AGAINST for the search name and address string.
$stores = DB::select("
    SELECT *
    FROM stores
    WHERE MATCH(name, address) AGAINST (? IN BOOLEAN MODE)
   ", [$query]);

Notes : In order to use the MATCH function, you'll need to have a full-text index set up on the name and address columns.
You can setup by this query inside sql : ALTER TABLE stores ADD FULLTEXT INDEX ft_index (name, address);


text: Q: Allow user to edit UITableViewCell When using a UITableView, is it possible to have a user touch a UITableViewCell, have a keyboard appear, then have cell.textlabel.text disappear and be replaced with the users own input from the keyboard?


text:
Q: php mysql upload an image to database Found several examples online on how to upload an image to a mysql database table, in binary
NOT a link or a folder in the server.
the imag isn't viewable when i try to print it
when I check the database table,it shows a bunch of data in weird format, i'm assuming the image data
here is code
if(!empty($_FILES['image']) && $_FILES['image']['size'] > 0 && !empty($_POST['name']))
{
    // Temporary file name stored on the server
       $tmpName = $_FILES['image']['tmp_name'];

// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);

code for displaying image
$sql = "SELECT * FROM `photos` WHERE userName = '$currentUser'";
    $result = mysqli_query($con,$sql);
    while($row = mysqli_fetch_array($result))
    {
        $content = $row['image'];
        echo $content;
        echo '
'.$row['caption'].'
';
    }

when i try to display the image i get nothing as output, i check the database via putty, and i see a massive amount of weird characters, i'm assuming the items for the image.
ideas?

A: you could eventually try to replace these two lines:
$content = $row['image'];
        echo $content;
with:
echo '';


text:
Q: Why is my for loop running only 2 times instead of 10? I am trying to find the third highest number in the array with O(n) space and time complexity.
MY program is obviously wrong but that is not the problem.
My for loop in the thirdhighestnum function seem to running only 2 times. I can't seem to find the reason for it. Can anyone help me. Sorry for such basic question I am a beginner here.
#include<iostream>

using namespace std;

int thirdhighestnum(int a[],int size)
{
    cout<<" "<<size<<endl;
    int first=a[0],second=0,third=0;
    for(int i=1;i<size;i++)
    {
        cout<<a[i]<<";"<<endl;
        if(a[i]>first)
        {
            first=a[i];
            if(a[i+1]>first)
            {
                second=first;
                first=a[i+1];
                if(a[i+2]>first)
                {   third=second;
                    second=first;
                    first=a[i+2];

                }
            }
            cout<<i<<endl
            return third;
        }
    }
}
int main()
{  int num,a[10];
    cout<<"Enter the elements in the array"<<endl;
    for(int i=0;i<10;i++)
        cin>>a[i];
    cout<<"Third highest number is "<<thirdhighestnum(a,10)<<endl;
    return 0;
}

A: It's the location of your return third statement. The moment any number is larger than the first number, it exits the thirdhighestnum function and returns a value. Put it outside your for loop and it should be fine.

A: This is known as nth_element and library function can do this for you.
As for why your code fails, there is a flaw in your logic
for(int i=1;i<size;i++)
{
    // some code
    if(a[i]>first)
    {
        // some more code
        cout<<i<<endl
        return third;
    }
}

So your code exits the first time a[i] is greater than first.
[edit - After reading comments]
The generic name for this type of algorithm is a QuickSelect. It is unlikely you will find a faster algorithm, as this has been the subject of years of academic study.

A: Actually it is executing only one time i.e. the first iteration only. When i=1 then it prints a[1] i.e. 2; after that it prints i i.e. 1 so it appears as 2;1 here you think it is printing 2 numbers.
The main problem is your return third statement which terminates your for loop in first iteration only.


text:
Q: What's the difference between application and request contexts? Flask documentation says that there are 2 local context: application context, and request context. Both are created on request and torn down when it finishes.
So, what's the difference? What are the use cases for each? Are there any conditions when only one of these are created?

A:
Both are created on request and torn down when it finishes.

It is true in the request lifecycle. Flask create the app context, the request context, do some magic, destroy request context, destroy app context.
The application context can exist without a request and that is the reason you have both. For example, if I'm running from a shell, I can create the app_context, without the request and has access to the ´current_app` proxy.
It is a design decision to separate concerns and give you the option to not create the request context. The request context is expensive.
In old Flask's (0.7?), you had only the request context and created the current_app with a Werkzeug proxy. So the application context just create a pattern.
Some docs about appcontext, but you probably already read it: http://flask.pocoo.org/docs/appcontext/


text:
Q: Save a selection from Holoview Points as CSV This is a part of my code:
filtered_df = data.loc[data["ini_sin"].between(str(self.inicio), str(self.final))]
points = hv.Points(filtered_df, kdims=
             ['x','y'],vdims['no_caso','dir_est','edad','sexo','semana','ini_sin','depto','muni']
points = points.select(edad = self.edad_s)
points = points.select(edad = self.semana_s)

I need to pass from the selection of points(hv.Points) to csv , and later download the csv file.


text:
Q: in_array vs strpos for performance in php I am logging in users via windows authentication and then storing that user's rights in a session variable.  I use a delimited method of rights storage in a database i.e:
$rights //retrieved from database
= 'read,edit,delete,admin'

so my question is should I;
//generate variable
$_SESSION['userrights'] = $rights ($rights is retrieved from database)

//use strpos to find if right is allowed
if (strpos($_SESSION['userrights'],"admin") !== false) { // do the function }

OR
//make array of rights
$_SESSION['userrights'] = explode(',',$rights)

//use in_array to find if right is allowed
if (in_array("admin",$_SESSION['userrights'])) { // do the function }

Bit of a OCD question as I presume the difference will be pretty much negligible for what I am doing but which would be the faster (use less resources) method?
Any answers appreciated except ones that insult my method of rights storage!

A: strpos is the fastest way to search a text needle, per the php.net documentation for strstr():

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.1

A: As I often work with large datasets, I'd go with isset or !empty on an associative array and check for the key, like @Barmar suggests. Here is a quick 1M benchmark on an Intel® Core™ i3-540 (3.06 GHz)
$test = array("read", "edit", "delete", "admin");

echo "<pre>";

// --- strpos($rights,$test[$i%4]) ---

$rights = 'read,edit,delete,admin';
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (strpos($rights,$test[$i%4]) !== false) { }}
echo '  strpos(... '.round(microtime(true)-$mctime,3)."s\n";

// --- in_array($test[$i%4],$rights) ---

$rights = array("read", "edit", "delete", "admin");
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (in_array($test[$i%4],$rights)) { }}
echo 'in_array(... '.round(microtime(true)-$mctime,3)."s\n";

// --- !empty($rights[$test[$i%4]]) ---

$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (!empty($rights[$test[$i%4]])) { }}
echo '  !empty(... '.round(microtime(true)-$mctime,3)."s\n";

// --- isset($rights[$test[$i%4]]) ---

$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (isset($rights[$test[$i%4]])) { }}
echo '   isset(... '.round(microtime(true)-$mctime,3)."s\n\n";

echo "</pre>";

The winner is isset:
  strpos(... 0.393s
in_array(... 0.519s
  !empty(... 0.232s
   isset(... 0.209s

A: A benchmark that proofs that strpos is not the fastest method, but faster than in_array:
<?php

echo phpversion() . PHP_EOL;

// build random array
$array = array_fill(0, 10000, 16);
$array = array_map('openssl_random_pseudo_bytes', $array);
$array = array_map('bin2hex', $array);
$array_flipped = array_flip($array);
$string = implode($array);
$random_keys = array_rand($array_flipped, 10);

$loops = 10000;

$start = microtime(true);
for ($i = 0; $i < $loops; $i++) {
    strpos($string, $random_keys[ rand(0, 9) ]);
}
echo __LINE__ . ': ' . round(microtime(true) - $start, 5) . PHP_EOL;

$start = microtime(true);
for ($i = 0; $i < $loops; $i++) {
    in_array($random_keys[ rand(0, 9) ], $array);
}
echo __LINE__ . ': ' . round(microtime(true) - $start, 5) . PHP_EOL;

$start = microtime(true);
for ($i = 0; $i < $loops; $i++) {
    isset($array_flipped[ $random_keys[ rand(0, 9) ] ]);
}
echo __LINE__ . ': ' . round(microtime(true) - $start, 5) . PHP_EOL;

$start = microtime(true);
for ($i = 0; $i < $loops; $i++) {
    $array_flipped = array_flip($array);
    isset($array_flipped[ $random_keys[ rand(0, 9) ] ]);
}
echo __LINE__ . ': ' . round(microtime(true) - $start, 5) . PHP_EOL;

?>

Result:
5.6.31
19: 1.11484
25: 1.3109
31: 0.00237
38: 13.64204

As you can see it is important not to flip an array on-the-fly to benefit from isset.

A: Have you considered the possibility of doing a query on the database if $_SESSION['userrights'] exists in the database? You're already doing a query to get the list of rights in your example, why not do a query for a specific $_SESSION['userrights'] and check if there are any rows returned?


text:
Q: How to use scissors library in Eclipse ADT? I want to use this library for image cropping but I don't know how to include it in an Eclipse project?
https://github.com/lyft/scissors
Can I just copy-paste the classes in some folder or is that against the license?

A: I've convert this lib into Eclipse compatible project.
Download it from here.
for integrating it into eclipse follow these step:

*

*Unzip file.

*Import into eclipse.

*Mark Project as library project.

*Make sure you are using support library version 22.2.1 or higher from Android SDK Manager. If not update it.

*Copy android-support-v4 JAR into libs folder from appcompat_v7 Project (I guess).

Now you're ready to go. Just add this project as library into your desire project.

A: Start using Android studio, Google has already stopped support for Eclipse (ADT), so it would be better for you to start emphasising on Android studio.
The Github project mentioned is Gradle based, you can either use Eclipse or Android studio to import the project.
Android Studio - You can mention the project's dependancy i.e. compile 'com.lyft:scissors:1.0.3'
in your build.grade and you are good to go.
Eclipse


text:
Q: Placeholder not working with angular2 I have the following code:

    Account <select class="form-control" required [(ngModel)]="model.accountId" ngControl="account" #account="ngForm">
    <option value="" disabled="disabled" selected="selected">Account</option>
    <option *ngFor="#acc of accounts" [value]="acc.id">{{acc.name}}</option> </select>

in which the Placeholder is not working with ANGULAR2.
Please let me know if you require anything more?

A: It will work if you will set up this.accountId = ""; in your constructor.
Plnkr here.
It was not working before, because ngModel you set in select. It waas trying to create data binding with values that dont exist.

A: you have not posted error you faced in your question. but still by assuming your use case i have created a plnkr for the
same.Try using this code

    Account
    <select class="form-control" required #account (change)='selectValue(account.value)'>
        <option value="" disabled selected>Account</option>
        <option *ngFor="#acc of accounts" [value]="acc.id">{{acc.name}}</option>
    </select>

here is plnkr link http://plnkr.co/edit/JFGhqxugZrSxyiWIzvzu?p=preview


text:
Q: AWS s3 - node sdk : Get Signed URL for an object in an encrypted bucket I am using the AWS s3 node-sdk to put an object in a KMS encrypted bucket. I want to get the signedURL for the object, so I could use it to offer the file as a browser download. Currently, Im doing the following:
const url = s3.getSignedUrl('getObject', {
                    Bucket: bucketName,
                    Key: fileName,
                    Expires: signedUrlExpireSeconds
                })

I get a url as the response. Using the URL, I get the following error in the browser
<Error>
InvalidArgument
<Message>
Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4.
</Message>
<ArgumentName>Authorization</ArgumentName>
<ArgumentValue>null</ArgumentValue>
<RequestId>XXXXXXXXXXXXXXX</RequestId>
<HostId>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
</HostId>
</Error>

I've been looking for documentation to use the AWS signature version 4, but found no leads. How can I get the signedURL for this encrypted object using the node sdk?

A: This is a bug in the sdk. You need to explicitly tell it to use v4.
const s3 = new AWS.S3({maxRetries: 10, signatureVersion: "v4"});


text:
Q: KeyboardInterrupt doesn't work when arcgisscripting module is loaded The KeyboardInterrupt exception -- thrown when Ctrl-C, or Ctrl-Break on some machines, are pressed in a Python console window -- is commonly used to gracefully break out of long-process loops, allowing your script to perform cleanup, logging etc, before exiting.
Under my ArcGIS 9.3.1 SP2/Windows XP SP3 environment, there is an issue with catching the KeyboardInterrupt exception if the arcgisscripting module is loaded. Instead of hitting the KeyboardInterrupt catch statement, the script aborts abruptly, spitting out the following message:
forrtl: error (200): program aborting due to control-C event
If the arcgisscripting module is not loaded (removed from the import statement), the KeyboardInterrupt exception is thrown and processed properly.
From what I've read this is due to the use of Fortran in the arcgisscripting module which somehow overrides Python's interrupt processing.
Here's an example script you can use to test and reproduce the issue. Save it as a Python script, run it from the Windows command prompt and press Ctrl-C (Ctrl-Break on some machines) to test whether the KeyboardInterrupt exception is processed. Simply toggle the commenting for the import arcgisscripting line.
#import arcgisscripting
import time

try:
    while(True):
        time.sleep(1)
except KeyboardInterrupt:
    print "KeyboardInterrupt detected!"

Anyone know of a workaround to this problem? Thanks in advance for any insights you may have.
edit: here is my test script using Jason's suggestion which unfortunately doesn't work:
import arcgisscripting
import signal
import time

def ctrlc(sig, frame):
    raise KeyboardInterrupt("CTRL-C!")

print "Waiting 65s ..."
time.sleep(65)
print "Installing SIGINT handler"
signal.signal(signal.SIGINT, ctrlc)

try:
    while(True):
        time.sleep(1)
except KeyboardInterrupt:
    print "KeyboardInterrupt detected!"

A: You can try reinstalling a custom handler for SIGINT using the signal module after importing arcgisscripting.
import arcgisscripting
import signal

def ctrlc(sig, frame):
    raise KeyboardInterrupt("CTRL-C!")

signal.signal(signal.SIGINT, ctrlc)

Let me know if this works for you.

A: I figured out a Windows-only workaround for this. It uses the msvcrt module, which is a Windows-only wrapper for the Visual C++ runtime, to read which keyboard character code was last received. It doesn't override the Ctrl-C, so I specified it should look for Ctrl-Alt-Q. When you press Ctrl-Alt-Q in my test script it will raise the KeyboardInterrupt exception. If you hit Ctrl-C it will still abruptly kill the script, however.
There are likely other ways to do this on *nix but I only needed this for Windows.
import arcgisscripting
import msvcrt
import time

def kbfunc():
   x = msvcrt.kbhit()
   if x:
      ret = ord(msvcrt.getch())
   else:
      ret = 0
   return ret

if __name__ == '__main__':
    try:
        while(True):
            time.sleep(1)

            # Check to see if Ctrl-Alt-Q is pressed
            x = kbfunc()
            if x == 16: # Ctrl-Alt-Q
                raise KeyboardInterrupt

    except KeyboardInterrupt:
        print "KeyboardInterrupt detected!"


text:
Q: Let $f$ be a function such that $ \sqrt {x - \sqrt { x + f(x) } } = f(x) , $ Let $f$ be a function such that $$ \sqrt {x - \sqrt { x + f(x) } } = f(x) , $$ for $x > 1$. In that domain, $f(x)$ has the form $\frac{a+\sqrt{cx+d}}{b},$ where $a,b,c,d$ are integers and $a,b$ are relatively prime. Find $a+b+c+d.$

A: Let's write $f$ for $f(x)$.
\begin{align}
\sqrt{x-\sqrt{x+f}}&=f\\
x-\sqrt{x+f}&=f^2\\
\sqrt{x+f}&=-f^2+x\\
x+f&=f^4-2xf^2+x^2\\
0&=f^4-2xf^2-f+x^2-x
\end{align}
This looks like a very ugly equation to solve. We want to factor that somehow (maybe there's some difference of squares in there? I can't see it...) Since we have nothing else to do, let's complete the square on the right. (Why? Well, I'm hoping for a difference of two squares somewhere, so getting a square in there seems like a good start.)
\begin{align}
0&=f^4-2xf^2-f+x^2-x\\
0&=f^4-2xf^2-f+\Big(x-\frac12\Big)^2-\frac14
\end{align}
Let's ignore the $-\frac14$ at the end for just one second, and look at the rest. What do we have here? Well, $f^4-\textit{something}+(x-\frac12)^2$. This is almost a square! (Remember that $(a-b)^2=a^2-2ab+b^2$; we have the $a^2$ and $b^2$ in here.)
So, let's try seeing what $(f^2-(x-\frac12))^2$ looks like. (Maybe we'll get lucky and find out that our thing actually is a square.)

\begin{align}
\Big(f^2-\left(x-\tfrac12 \right)\Big)^2&=f^4-2f^2 \left(x-\frac12 \right)+\Big(x-\frac12\Big)^2\\
&=f^4-2f^2x+f^2+\left(x-\frac12\right)^2
\end{align}

Drats — that's almost what we have. What we have is that thing, but with a $-f$ instead of a $+f^2$. In other words, we have $\textit{that thing}-f^2-f$. Well, let's put it into our equation above anyway:
\begin{align}
0&=f^4-2xf^2-f+\Big(x-\frac12\Big)^2-\frac14\\
&=\left(\left(f^2-\left(x-\tfrac12\right)\right)^2-f^2-f \right)-\frac14\\
&=\Big(f^2-\left(x-\tfrac12 \right)\Big)^2-f^2-f-\frac14
\end{align}
Woah! We can factor that...
\begin{align}
&=\Big(f^2-\left(x-\tfrac12 \right)\Big)^2-\left(f+\tfrac12 \right)^2
\end{align}
And suddenly it's the difference of two squares:
\begin{align}
&=\Big(f^2-\left(x-\tfrac12 \right)+\left(f+\tfrac12 \right)\Big)\Big(f^2-\left(x-\tfrac12 \right)-\left(f+\tfrac12 \right)\Big)\\
&=(f^2+f-x+1)(f^2-f-x)
\end{align}
Woohoo! We factored that beast. The end is in sight.
We now split this into two equations: $f^2+f-x+1=0$ and $f^2-f-x=0$. Each give us two possible solutions. After using the quadratic formula, we end up with
$$\frac{-1\pm\sqrt{4x-3}}2,\frac{1\pm\sqrt{4x+1}}2$$
Now, we need to test each of these to see which one works. Actually, this isn't too bad — we can just choose a good choice for $x>1$ for each of these (preferably a choice of $x$ that gives us lots of integers) and see if they work. (Why $x>1$? 'Cause that's what the problem says.)
So, let's pick good values of $x$ and plug them into the original equation: $\sqrt{x-\sqrt{x+f}}=f$.
Working with $x=3$, the first two solutions give me $1=1$ and $\sqrt2=-2$ respectively; working with $x=2$, the last two solutions give me $0=2$ and $1=-1$ respectively. Clearly, only the first one works; thus, the solution is:
$$f=\frac{-1+\sqrt{4x-3}}2$$
EDIT: Technically, they want you to find $a+b+c+d$. So, the answer is $(-1)+(2)+(4)+(-3)=2$.


text:
Q: How to import a local file in my main package Let's say, I have the following structure.
export $GOPATH = ~/workspace/go

Directory-Tree:
~/workspace
+ go
  + src
    + example
      + exp1
        - main.go
        - client.go
        + utils
          - my_utils.go

In the file main.go i'd like to import 'client.go' and 'utils/my_utils.go'.
How to do that?
import {
   "./client.go"
}

will give me

local import "./client.go" in non-local package

The same happens with any other file in subdirectories like my "utils" folder.
I've read a lot about this error message and about the GOPATH. However, coming from NodeJS and PHP and C++ I really still don't understand this concept of how GoLang will handle file imports and need some further clarification here.
I've read also that people where going to import everything from "GitHub.com", but it makes no sense for me to first push my code to GitHub before I can test it in my local project.
By the way, I'm also curious why go get will not fetch all sub-dependencies together with the specific library that will be fetch with go get?

A:
I've read also that people where going to import everything from "GitHub.com", but it makes no sense for me to first push my code to GitHub before I can test it in my local project.

You don't have to push it anywhere before you can test it. You only have to choose what your import path is, and then put your code in GOPATH accordingly (or use go mod init with Go 1.11+, which lets you place your code anywhere in the filesystem you want). But you still have to pick that import path — even if you decide to change it later.

By the way, I'm also curious why go get will not fetch all sub-dependencies together with the specific library that will be fetch with go get?

It does.


text:
Q: How to ignore "possibly lost" in valgrind I recently use valgrind with glib(with gobject), it doesn't work very well.
I have added G_SLICE=always-malloc G_DEBUG=gc-friendly in the command line,
but there's still many "possibly lost" reported by valgrind.
As I use valgrind in automated testsuit, so I add --error-exitcode=1,
but those "possibly lost" will make valgrind exit with 1, which will
case my test fail.
Does anyone know how to make valgrind not treat "possibly lost" as errors.

A: With valgrind 3.7.0, use:
    --show-possibly-lost=no|yes      show possibly lost blocks in leak check?
                                     [yes]

A: Check https://live.gnome.org/Valgrind for tips on how to use Valgrind with glib/gtk+/gnome.  You might be interested in the Suppressions's section.

A:
Does anyone know how to make valgrind not treat "possibly lost" as errors.

Use --errors-for-leak-kinds=definite for this.  See Valgrind User Manual,  Memcheck Command-Line Options section


text:
Q: Power Set and Empty Set question I have a question regarding the set of functions resulting from a set raised to a power.  I think I have part of the understanding correct, however I'm having trouble interpreting $Y^{\emptyset}$. I have read other posts and reference them at the end.  It's my understanding $Y^{X}$ is as follows:
$Y^{X} = \{f_{0}, ..., f_{n}\}$
Where $f_{n}$ = $\{(x_{0}, y_{0}), ..., (x_{n}, y_{n})\}$ and each is a total single-valued function.
For example, all the functions resulting in set inclusion and exclusion (the Power Set $\mathcal{P}(X$)) is:
$X = \{True, False\}$
$Y = \{Admit, Exclude\}$
$Y^{X} = \{f_{0}, f_{1}, f_{2}, f_{3}\}$
$f_{0} = \{(True, Admit), (False, Admit)\}$
$f_{1} = \{(True, Exclude), (False, Exclude)\}$
$f_{2} = \{(True, Admit), (False, Exclude)\}$
$f_{3} = \{(True, Exclude), (False, Admit)\}$
$\mid Y^{X} \mid = card(Y^{X}) = \mid Y \mid^{\mid X \mid} = \mid \mathcal{P}(X) \mid = 4 $
A side note, $f_{2}, f_{3}$ are surjective and injective functions and result in a dichotomy for the truth function.
$1^{n} = 1, n \gt 0$, results in a single function $f_{0} = \{(0, 0), (1, 0), ..., (n, 0)\}$.  This seems intuitive.
I begin to get confused for the $Y^{\emptyset}$ case.  From other posts here and Wiki, this is as follows:

*

*Algebra and Set Theory Definition: $\emptyset^{\emptyset} = Y^{\emptyset} = 1$

*

*Based on the "empty function", $Y^{\emptyset} = \{\emptyset\}$

*$2^2 = 1 * 2 * 2 = 4, 2^1 = 1 * 2 = 2, 2^0 = 1$ : dividing by 2 each time, where 1 is implicit in the multiplication.

*Math Analysis Definition: $\emptyset^{\emptyset} = undef$
In above cases where the $X = \emptyset$, I'm confused how there could be any function between the empty set $X$ and base set $Y$.  The empty set has no elements to map in a function.  In this case, undef seems to fit this better.  Can anyone provide guidence here?
$\emptyset^{n} = 0$ where $n \gt \emptyset$, makes sense to me because there are no functions that map between $n$ and $\emptyset$.
Perhaps it's because I'm looking at this as follows?
yn             *

y1       *

y0  *
    x0  x1 ... xn

where the $*$ indicate an ordered pair, all of which make up a single function provided it is single-valued.  The result of $Y^{X}$ is all of these unique functions.
UPDATE
Case (a) $0^{0} = 1$ because $x \notin \emptyset$ and therefore properties of a function are satisfied and $0 \subseteq X \times Y$.  Case (b) $0^{1} = 0$ because properties of a function are not satisfied, $0 \in 1 \land y \notin 0$.  Case (c) $1^{0} = 1$ because of Case (a).  Case (d) $1^{1} = 1$ because $\emptyset \in 1 \land \emptyset \in 1$ and $\{(0, 0)\} \subseteq (1 \times 1)$.
Previous Post References: Prior Post
Prior Post

A: A map $f\colon X\to Y$ is a subset of $X\times Y$ with the following properties:

*

*for every $x\in X$, there exists $y\in Y$ with $(x,y)\in f$;

*for every $x\in X$ and every $y_1,y_2\in Y$, if $(x,y_1)\in f$ and $(x,y_2)\in f$, then $y_1=y_2$.

The first property ensures that every element of $X$ has an image, the second property ensures the image is uniquely defined.
If $X=\emptyset$, then there is a single subset of $\emptyset\times Y$, namely the empty set, which satisfies the properties above (because there is no way they can be false). You are questioning about what is mapped where: you have to assign an image to every element of $X$, if there's no element you're already done, aren't you?
Thus the set of maps $Y^\emptyset$ is a singleton consisting of the empty set:
$$
Y^\emptyset=\{\emptyset\}
$$
has cartinality $1$. Note that $Y$ has no special role here and can be any set.
The problem is with $Y=\emptyset$, because $\emptyset^X$ is empty whenever $X\ne\emptyset$, because you have no element where to map the elements of $X$; but there's no problem when $X=\emptyset$ as well, because of the argument above. Thus
$$
|\emptyset^X|=\begin{cases} 1 & X=\emptyset \\[4px] 0 & X\ne\emptyset \end{cases}
$$
Facts regarding limits and indeterminate forms have nothing to do with this combinatorial framework.


text:
Q: Can I subscribe event fire from smart contract's events with NodeJS? I just wrote smart contract function with fire event like this.

And create my node.js application with following code.

const express = require('express')
const Web3 = require('web3');
const app = express()
const PORT = process.env.PORT || 8080
const privateKey = "-- secret"
const { CONTRACT_ABI, CONTRACT_ADDRESS } = require('./config');
const web3 = new Web3('https://data-seed-prebsc-1-s1.binance.org:8545');
const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);

app.get('/send_transaction', async (req, res) => {
    const reciept = await send(web3, privateKey, contract)
    res.send(reciept);
});

contract.events.EndedRound({
    fromBlock: 0
}, function(error, event) { console.log(event); })
.on('data', function(event) {
    console.log(event) // no event coming here.
})

async function send(web3, privateKey, contract) {
    const account = web3.eth.accounts.privateKeyToAccount(privateKey).address;
    const transaction = contract.methods.endRound(1651799819, [1], Web3.utils.toWei("100"));
    const options = {
        to: transaction._parent._address,
        data: transaction.encodeABI(),
        gas: await transaction.estimateGas({ from: account })
    };
    const signed = await web3.eth.accounts.signTransaction(options, privateKey);
    const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
    return receipt;
}

app.listen(PORT, () => {
    console.log(`Server is running on port : ${PORT}`)
})
module.exports = app

But after I call function in smart contract which fire event EndedRound, My nodejs app not receive any event at all.
Is it possible to do that?

A: The event in the smart contract is 'EndRound' and the one in your express server is 'EndedRound'.


text:
Q: Is there a library or web service that provides pronunciations for text? Is there a library or web service that can tell you the pronunciation of a string? I'm thinking of character-based languages, where the pronunciation of the word is not apparent from how it's written.

A: Check out the Wordnik API:
http://developer.wordnik.com/
Free API key will get pronunciations, definitions, and a whole lot more. Easy to use, and the API documentation site is interactive and lets you get your feet wet quickly. Lots of wrappers in various languages.
Disclosure: I work there and love it.

A: This is a similar question. Research the CMU Pronouncing Dictionary.

A: Google's Text To Speech


text:
Q: Is the following rv integrable? Consider the probability space $((0,1],\mathcal{B}((0,1]),\lambda|_{(0,1]})$ and define $$X_n(\omega) := \frac{1}{\omega} 1_{\big(0, \frac{1}{n}\big]}(\omega).$$
I am told that this R.V. is not integrable. Why is this the case? I know that for a R.V. to be integrable in$L^1$, it must have finite expectation. But I can not see why $E[X_n(w)]=\infty$.

A: By definition, our probability measure here is $\lambda\vert_{(0,1]}$ so $\mathsf d\mathbb P(\omega) = \mathsf d\omega$ and
$$
\mathbb E[X] = \int_\Omega X(\omega)\ \mathsf d\mathbb P(\omega)
= \int_{(0,1/n]} \frac1\omega\ \mathsf d\omega = +\infty,
$$
so $X$ is not integrable.


text:
Q: Angular 13 Service define structure Literally very new to Angular13. Our application need some configuration data on startup, so Shared service to be called out on AppComponent and its data will be shared around application header, menu and footer to show/hide few div's. Below is the sample code of SharedService.
Shared.service.ts
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {

  private data: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  data$: Observable<any> = this.data.asObservable();

  private companyLogo: string = '';
  private languages: string = 'en-us';
  constructor(private http: HttpClient) {
    this.http.get('/shared').subscribe(data => {
      //let us say data will be like
      data = {
        "logourl" : '/img/mg1.jpg',
        "showDashboard": true,
        "language": 'en',
        "username": 'user-1', //so on and it has 20+ values
      }
      //How to structure this data and called throughout application
    })
  }

}```
I have no idea that how to use return data whether to get it through observables/getter/setter. Guide me in implementing this.

A: To pass data to a BehaviorSubject (or any Subject) you need to call .next() method and pass the data as a parameter:
@Injectable({
  providedIn: 'root'
})
export class SharedService {

  private data: BehaviorSubject<any> = new BehaviorSubject<any>(null);

  private companyLogo: string = '';
  private languages: string = 'en-us';

  constructor(private http: HttpClient) {
    this.http.get('/shared').subscribe(data => {

      data.next({
        "logourl" : '/img/mg1.jpg',
        "showDashboard": true,
        "language": 'en',
        "username": 'user-1', //so on and it has 20+ values
      })

    })
  }

  getData(){
    return data.asObservable();
  }

  //...

To get the data from other places in your app:
// after injecting service..
this.sharedService.getData().subscribe(data => {
  // handle data
}


text:
Q: Get the code of the page with a get/post request including "script" I need to get an access token request on FaceBook using cookies.
I tried to make get/post requests to the advertising account page (facebook.com/adsmanager), but in response I get an html page that does not contain the script I need.
This is what this script looks like if you look from the browser in the element code, located in the script and starts with EAAB:
screenshot facebook token
How and with what I can make a request to the page of the account (using pre-prepared cookies) to get in response the code of the page, which will contain a script with the token EAAB, which is shown in the screenshot.


text:
Q: Logic app: Mapping to base64 encoding of dynamic content We have a list on a Sharepoint site that we need to copy to a CSV file in a different Azure tenant.  As part of that, we've been asked to take one field containing free-form comments (called "Support Comments") and covert it to base64.  I can access the comments field with no problem:

I can access the base64 expression:

Now, how do I get the base64 conversion of a comment?  That is, if "Support Comments" contains "This is a test", I want it to return "VGhpcyBpcyBhIHRlc3Q=".  I've tried expressions like this:
base64([SupportComments])

with variations on quoting types and places, with no luck.

A: I don't have your exact example but it's the same concept.  Bottom line, you shouldn't need to type the entire expression in.
Try one of these two approaches ...
Approach 1
After typing in base64(), click back to the Dynamic Content tab and then simply select your Support comments content.
Step 1

Step 2

Result

The expression won't be exactly the same as what's shown but it should yield the same result on your side.
Approach 2
Put the dynamic content directly in the field you want it to go to ...

Now go into Code View ...

... and update the expression directly.

If the flow doesn't save or it doesn't work then there's something different about your Support Comments field that we need to get to the bottom of.

A: Since the list has items, it needs to be in a for loop to retrieve each item and so you need to use for loop with list values in a compose connector and then use the same compose connector for conversion(i.e., base64). Here is my logic app

RESULTS


text:
Q: Radius of a Sphere inscribed in a Convex Polyhedron My teacher gave me this problem in class as a challenge. It has stumped me for days, yet he refuses to give me the answer!
Let $PQRSTU$ and $PQR'S'T 'U'$ be two regular planar hexagons in three dimensional space, each having side length $1$, and such that $\angle TPT'=60^{\circ}$. Let $P$ be the convex polyhedron whose vertices are $P, Q, R, R', S, S', T, T', U, U'$. How would one go about determining:
a) The radius $r$ of the largest sphere that can be inscribed in the polyhedron?
b) Let $E$ be a sphere with radius $r$ enclosed in polyhedron $P$ (as derived in part a)). The set of all possible centers of $E$ is a line segment $\overline{XY}$. What is the length $XY$?
I have tried EVERYTHING in my arsenal... I even made a cutout polyhedron $P$! But i still cant solve it. Can someone help?

A: Hint to start: $P T T'$ is an equilateral triangle, and is the cross-section of your polyhedron through $P$ orthogonal to $PQ$.  Same goes for $Q S S'$.

A: I have a very mediocre solution for the maximum radius $r$.
If we consider the cross section $SQS'$, we see that it is a equilateral triangle with side length $\sqrt{3}$. The maximum radius of a circle that can be inscribed in it is $\frac{1}{2}$, which is believe is the answer. This is however, far from a complete proof, as we fail to account for the restraint of the rest of the polyhedra, and so we might need to make a smaller value of $r$.
1) is this logic that the maximal radius is $\frac{1}{2}$ even correct?
2) How do we prove that this radius can actually be attained?
3) and what about part b) of this question... the movement of the sphere?
If anyone could give a complete solution of the three above questions, I would be sincerely grateful!


text:
Q: SolrCloud boot with existing cores I am playing with solrcloud 4.6.0 and have a question. I have 3 standalone zookeeper v3.4.5 servers and 2 solr instances. Zookeeper was freshly installed and empty.
I configured the first solr node with the new discovery format, prepared initial existing cores (with data) and started the first solr with the bootstrap_conf set to true.
By observing the solr log I saw the cores config was uploaded to zookeeper and can also confirm that by looking at zookeeper registry. Also the cores are visible in the solr web console, searchable. All in all working.
Now I wanted the second solr node to kick in. The second solr was only having solr.xml (exactly the same as the first solr node). My understanding was that starting the second solr node will read the cores info from zookeeper and after a while all cores will replicate to it.
Didn't happen.
No errors in the logs, second solr web console says no cores are available.
What did I miss?
Best regards

A: No errors in the log, huh? Bad eye I have.
It turns out that the initial configuration which was uploaded to zookeeper wasn't expending the variables in solr.xml, so the clusterstate.json had wrong ports for my Jetty solr installations - the default port 8983 was taken for replicas, but they were running on different ports.
I just modified the default value on all replicas in solr.xml file prior to booting the first solr instance with bootstrap_conf and now the cores are immediately visible. Also I deleted all zookeeper info before.
But still replicas have to be created on each node via web gui or by rest api.


text:
Q: Проблема jQuery UI dialog Проблема: почему-то когда на странице есть скролинг и пользователь находится внизу страницы, то страница автоматически скролится вверх, а модальное окно при этом остается вверху. В чем может быть проблема?
Привожу фрагмент кода:
$("#dialog3").dialog({
position: ['center','center'],
autoOpen: false,
modal: false,
height: 160,
width: 400,
buttons: {...

A: Проблема в вызове диалога. Надо делать привязку клика к кнопке не как показано на офф сайте, а через $('#button').on('click', function () { /* ... */ }); или просто в коде кнопки на onclick=""

A: Последняя библиотека?
Не работает во всех браузерах?
Так тоже не работает?
$( "#dialog3" ).dialog( "option", "position", 'center' );

А у #dialog3 у Тебя в стилях ничего криминального не прописано?
A: Попробуй поставить
modal: true
тогда у тебя при вызове диалога скрола нету, при закрытии есть.


text:
Q: Time Series - Splitting Data Using The timeSlice Method Referring to this post:createTimeSlices function in CARET package in R where createTimeSlices was suggested as an option for cross-validating when using time series data. I would like to understand how to go about selecting values for 'initialWindow', 'horizon' and 'fixedWindow' in trainControl.
They are defined within caret as follows (?createTimeSlices):
initialWindow - The initial number of consecutive values in each training set sample
horizon - The number of consecutive values in test set sample
fixedWindow - A logical: if FALSE, the training set always start at the first sample.
Can someone please elaborate further on how to go about selecting the right values  for initialWindow & Horizon and the actual implications of selecting TRUE or FALSE for fixedWindow?

A: initialWindow: The size of the training set/window for the first modeling iteration. How large this should be depends on the complexity of the model you are fitting, so you have to research what minimum sample size is expected to get a reliable fit. Obviously, a larger window is needed for more complex models, see for example Measuring forecast accuracy, p. 6.
fixedWindow: If TRUE this implies a moving window (always equal to the size of initialWindow), if FALSE it implies a growing window (in other words, it always starts at the first sample) that is used to fit the model. In the usual output of the models from caret you can observe the sizes of the training sample and whether it is growing or moving as in (fixedWindow = FALSE, horizon = 1):
Resampling: Rolling Forecasting Origin Resampling (1 held-out with no fixed window)

Summary of sample sizes: 100, 101, 102, 103, 104, 105, ...

horizon: This defines for how many consecutive steps ahead the model is tested. The output of the caret model gives a summary of the model accuracy when predicting n steps ahead. The value that should be chosen here depends on your application, i.e. whether short-term or longer-term forecasts are desired. See again Measuring forecast accuracy, p. 7.


text:
Q: "Use of closed network connection." Our web service developer is getting a "DeliveryPoint=Unknown Failed:  error on connection with 17.172.233.147:2195: Use of closed network connection. Will retry in 20s" on my Push Notification Service using Uniqush. I cannot seem to detect which is the problem. Is this a problem with the pem/p12 files or the server cannot reach the Apple gateway? I am not very experienced in push notifications. What could be the common problems if the problem is the pem/p12 files? He is saying that it's the pem/p12 files causing the error. I suspect it is the server where the push notification service is being ran. I tested my pem/p12 files on Pushbots, a popular push notification service and I can receive push notifications with it. So it is a strong guess that the problem is on the push noticication server side.
I also cannot use the tag "Uniqush" here on stackoverflow, it doesn't seem popular. I hope I get help here.

A: I see this is a bit old, but i just had that very same problem.
First, you need to check your certificate and key to be sure to have them both in .pem format, and remove the key password/encription before using them with uniqush.
For detailed instructions go to this blog post and do steps 4 and 5 only http://blog.boxedice.com/2010/06/05/how-to-renew-your-apple-push-notification-push-ssl-certificate/
(steps 1-3 are for renewing your certificate, step 6 is for merging certificate and key which isn't needed for uniqush)
If you've already done this, maybe the problem aren't the certificates, but a problem in the setup of uniqush.
If this is happening only in Ad-hoc/production environment, after checking that you are using the correct certificates (Ad-hoc/production uses different APNS certs than development), be sure not to include the -sandbox=true when adding the PSP (Push Service Provider) to uniqush.
If the problem persists, maybe yours is the one in this issue https://github.com/uniqush/uniqush-push/issues/47 (my case), so you should try the following:

*

*Download the latest version of uniqush (1.5.2a5 right now) from http://uniqush.org/downloads/uniqush-push_1.5.2a5_x86_64.tar.gz

*Extract the downloaded file with command tar zxvf <downloaded_file>

*Kill uniqush-push process, either using kill -9 <PID> or killall uniqush-push (you will probably need sudo for both)

*Copy/move uniqush-push from extracted folder to /usr/bin/uniqush-push (assuming you have it installed here in the first place)

*Run uniqush again with uniqush-push & or with a script or something (if you have one already)

Maybe you'll have to re-register the devices that weren't receiving push notifications.
This worked for me, so i hope it helps you.


text:
Q: Whats the meaning of "countertops" here? Anthralin is a topical medication used in treatment of psoriasis. I took the following text from online article.
Anthralin. This medication is believed to normalize DNA activity in skin cells. Anthralin (Dritho-Scalp) can also remove scale, making the skin smoother. However, anthralin can irritate skin, and it stains virtually anything it touches, including skin, clothing, countertops and bedding. For that reason doctors often recommend short-contact treatment — allowing the cream to stay on your skin for a brief time before washing it off. Anthralin is sometimes used in combination with ultraviolet light.
countertop means top surface of the basin, but it has no connection to the above context.

A: Here it means:
"The flat working surface on top of waist-level kitchen cabinets."
See countertop
Here it is used as an item in a list of things that can easily be stained.


text:
Q: React - console.log inside JSX map I have a component Tbody as follows (sorry for the long code) - I want to print the value of val in console (line #23) - note the val is inside a map . However, getting error - Parsing error: Unexpected token, expected ","
import React from "react";
import styled from "styled-components";

const Td = styled.td`
  ${(props) =>
    props.rowSpan &&
    `   &&&&& {
            text-align: left;
            vertical-align: top;
        }
    `}
`;

const ListItem = styled.div`
  white-space: nowrap;
`;

const Tbody = ({ data }) => (

    {data.map((row, i) => (

        {row.map((val, j) => (
          console.log(val) //- gives error

            {Array.isArray(val.text)
              ? val.text.map((line, lineIndex) => (
                  <ListItem key={val.text + j + line + lineIndex}>
                    {typeof line === "object"
                      ? Object.entries(line)
                          .map(([key, value]) => `${key}: ${value}`)
                          .join(", ")
                      : line}
                  </ListItem>
                ))
              : val.text}

        ))}

    ))}

);

export default Tbody;

Error:

A: The ( after the map means: everything being returned is JSX.
Use curly braces
{row.map((val,j) => {
  console.log(val);
  return (
    ... JSX
  )
}}

A: If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

const Console = props => (
  console[Object.keys(props)[0]](...Object.values(props))
  ,null // ➜ React components must return something
)

// Some component with JSX and a logger inside
const App = () =>

this is some component / element

    <Console log='Success' />

another component / element

    <Console warn='Error' />

ReactDOM.render(
  <App />,
  document.getElementById("root")
)

A: Inside JSX just write {console.log(val)}
for eg:
array.map(item => <>{console.log(item}</>)

This will work


text: Q: Develop android launcher for multi display screen I want to develop a launcher which support multiple Display like Automotive-specific features such as driver screens, passenger screens, and rear-seat entertainment. I can have a multiple instance of same app launching on individual display. Any help is appreciated


text:
Q: Prove that a simple connected graph has even numbers of vertex Given a simple connected graph G that all of its vertex degree is 3.
how can I prove that G has even number of vertex?
and does G has a perfect matching and why?

A: Suppose for a contradiction that $G$ has odd number of vertices $n$ and $e$ edges. Then, by Handshaking Lemma we have $2e = 3n$ where $n$ is odd so $e = \frac{3n}{2}$ is not an integer, which is a contradiction as required. Therefore $G$ has even number of vertices.
But $G$ may not have a perfect matching as in this example:


text:
Q: How to update ,insert and delete the rows in Sqlite? I am new to android development and i have gone through some tutorials and i wrote an application using sqlite Db.
I have couple of issues as mentioned below
1.How to update rows in my DB?
2.Delete the updated rows?
3.How to insert new rows?
//below code is for updating the rows
SQLiteDatabase db = dbHandler.getWritableDatabase();
for (int i = 0; i <= 100000; i = i + 100) {
    ContentValues cValues = new ContentValues();
    cValues.put(DbHandler.COLUMN_ID, i + 1);
    cValues.put(DbHandler.COLUMN_NAME, "Test");
    cValues.put(DbHandler.COLUMN_SERIALNUMBER, String.valueOf(i + 1));
    cValues.put(DbHandler.COLUMN_COUNTALL, 10);
    cValues.put(DbHandler.COLUMN_COUNTHIGH, i + 1);
    cValues.put(DbHandler.COLUMN_COUNTLOW, i + 1);
    cValues.put(DbHandler.COLUMN_RAWDATA, i + 1);
    db.update(DbHandler.TABLE_USERS, cValues, DbHandler.COLUMN_ID,new String[]{String.valueOf(i)});
}
db.close();

Delete the specific rows - Below code is clearing total the DB instead of specific rows
for (int i = 0; i <= 100000; i = i + 100) {
    db.delete(DbHandler.TABLE_USERS, i+"", null);
}

A: you can write dao class (Data Access Object) and working with the class
this is simple you just run sql query on db
this link will be helping you
for example insert
        val query = ("insert into " + DownloaderDatabase.TABLE_NAME + " " +
            "(" +
            ColumnModel.URL + "," +
            ColumnModel.FILE_NAME + "," +
            ColumnModel.STATUS + "," +
            ColumnModel.PERCENT + "," +
            ColumnModel.SIZE + "," +
            ColumnModel.TOTAL_SIZE
            + ")" +
            " VALUES(" + "\"" + fileModel.url + "\"" + ","
            + " " + "\"" + fileModel.fileName + "\"" + ","
            + " " + fileModel.status + ","
            + " " + fileModel.percent + ","
            + " " + fileModel.size + ","
            + " " + fileModel.totalSize + ")")
    database.writableDatabase.execSQL(query)
    database.close()

for example update
  val query = "update " + DownloaderDatabase.TABLE_NAME + " " +
            " set " + ColumnModel.STATUS + " = " + status +
            " , " + ColumnModel.PERCENT + " = " + percent +
            " , " + ColumnModel.SIZE + " = " + size +
            " , " + ColumnModel.TOTAL_SIZE + " = " + totalSize +
            " where " + ColumnModel.URL + " = " + "\"" + url + "\""
    database.writableDatabase.execSQL(query)
    database.close()

for example get data
        var model: FileModel? = null
    val query =
        "select * from " + DownloaderDatabase.TABLE_NAME + " where " + ColumnModel.URL + " = \"" + url + "\""
    val cursor = database.readableDatabase.rawQuery(query, null)
    while (cursor.moveToNext()) {
        val itemId = cursor.getInt(cursor.getColumnIndex(ColumnModel.ID))
        val itemUrl = cursor.getString(cursor.getColumnIndex(ColumnModel.URL))
        val itemFileName = cursor.getString(cursor.getColumnIndex(ColumnModel.FILE_NAME))
        val itemStatus = cursor.getInt(cursor.getColumnIndex(ColumnModel.STATUS))
        val itemPercent = cursor.getInt(cursor.getColumnIndex(ColumnModel.PERCENT))
        val itemSize = cursor.getInt(cursor.getColumnIndex(ColumnModel.SIZE))
        val itemTotalSize = cursor.getInt(cursor.getColumnIndex(ColumnModel.TOTAL_SIZE))
        model = FileModel(itemId, itemUrl, itemFileName, itemStatus, itemPercent, itemSize, itemTotalSize)
    }
    cursor.close()
    database.close()
    return model

A: Here is methods to perform update, insert and delete action in SQLite

*

*insertData
public long insertData() {
  SQLiteDatabase db = this.getWritableDatabase();
  ContentValues values = new ContentValues();

  values.put(KEY_TITLE, "Title");
  values.put(KEY_ACTIVITY_TYPE,"Event Type");
  values.put(KEY_PLACE, "Event place");
  values.put(KEY, "VALUE");
  values.put(KEY_, "VALUE");

  long id = db.insert(TABLE_NAME, null, values);
  return id;
}

*updateRow
public int updateRow(String row_id) {

SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();

values.put(KEY_TITLE, "Title");
values.put(KEY_ACTIVITY_TYPE,"Event Type");
values.put(KEY_PLACE, "Event place");
values.put(KEY, "VALUE");
values.put(KEY_, "VALUE");

return db.update(TABLE_NAME, values, KEY_ID + " = ?",
        new String[]{row_id});
}

*deleteRow
public int deleteRow(String row_id) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    return db.delete(TABLE_NAME, WHERE KEY_ID + " = ?", new String[]{row_id});
}

A: If you want to insert rows to the table, use ContentValues (just like your update code) and the insert() method:
SQLiteDatabase db = dbHandler.getWritableDatabase();
for (int i = 0; i < 3; i++) {
    ContentValues cValues = new ContentValues();
    cValues.put(DbHandler.COLUMN_ID, i + 1);
    cValues.put(DbHandler.COLUMN_NAME, "Test");
    cValues.put(DbHandler.COLUMN_SERIALNUMBER, String.valueOf(i + 1));
    cValues.put(DbHandler.COLUMN_COUNTALL, 10);
    cValues.put(DbHandler.COLUMN_COUNTHIGH, i + 1);
    cValues.put(DbHandler.COLUMN_COUNTLOW, i + 1);
    cValues.put(DbHandler.COLUMN_RAWDATA, i + 1);
    db.insert(DbHandler.TABLE_USERS, null, cValues);
}
db.close();

The above code will insert 3 rows in the table:
1 Test 1 10 1 1 1
2 Test 2 10 2 2 2
3 Test 1 10 3 3 3

Now, say that you want to update the column COLUMN_COUNTHIGH to 100 and the column COLUMN_COUNTLOW to 0 of the row with id = 2, then you use the update() method:
SQLiteDatabase db = dbHandler.getWritableDatabase();
ContentValues cValues = new ContentValues();
cValues.put(DbHandler.COLUMN_COUNTHIGH, 100);
cValues.put(DbHandler.COLUMN_COUNTLOW, 0);
db.update(DbHandler.TABLE_USERS, cValues, DbHandler.COLUMN_ID + " = ?", new String[] {String.valueOf(2)});
db.close();

So the update() method's arguments are:
the table's name
the ContentValues
the WHERE clause which contains the column names and the placeholders ? that will decide which row(s) will be updated
and the value(s) of the column(s) which will be set at the place of ?
If you want to delete say the row with id = 1, use the delete() method:
db.delete(DbHandler.TABLE_USERS, DbHandler.COLUMN_ID + " = ?", new String[] {String.valueOf(1)});

The arguments are similar as of those of the update() method (without the ContentValues).