text:
Q: Deploy CakePHP to a subfolder I have created a CakePHP 2 app, and now I'm trying to deploy it to a production web server.
My app uses the default folder structure (app/lib/plugins/vendors), default htaccess, default routing, nothing special.
I've been developing locally as if the app were in the root folder of the site (e.g. http://mycakeapp.localhost/ takes me to the site). But I'm deploying to a site (shared hosting) where that will not be the case (e.g. http://www.somedomain.com/mycakeapp).
It doesn't work (I didn't really expect it to), so I assumed I had to tweak one or more htaccess files. I tried modifying the root .htaccess as suggested in this post, but that only partially worked (the link to the CSS didn't work, for instance):
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule  ^mycakeapp$  mycakeapp/app/webroot/  [L]
RewriteRule  ^mycakeapp/(.*)$  mycakeapp/app/webroot/$1  [L]
</IfModule>

So what should I do to all the htaccess files to make this CakePHP site work in a subfolder?
UPDATE:
There's an .htaccess file in the root of the site, I've pasted its contents below. Is something in there screwing it up?
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^somedomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.somedomain.com/$1 [R=301,L]
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^secure/$ https://www.somedomain.com/secure [R=301,L]
RewriteRule ^about\.html$ /contact.php [R=301,L]
RewriteRule ^contact\.html$ /contact.php [R=301,L]
RewriteRule ^download\.html$ /signup.php [R=301,L]
RewriteRule ^index\.html$ /index.php [R=301,L]
RewriteRule ^privacy\.html$ /policies.php [R=301,L]
RewriteRule ^website\.html$ /business-websites.php [R=301,L]
RewriteRule ^return\.html$ /policies.php [R=301,L]

A: This post is a little old, but found it when doing reconaissance for my first CakePHP app deployment to a subfolder. The following .htaccess line can modify the root folder (for):
RewriteBase /subdir/

Sometimes Apache requires additional permissions or options in the httpd.conf or virtual hosts configuration file, similar to below:
    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>
    <Directory /var/www/html/site_folder>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            AddOutputFilterByType DEFLATE text/html text/plain text/xml
    </Directory>


text:
Q: Error in systemjs using angular2-highcharts I get the following error when trying to configure angular2-highcharts with RC5

product:15 Error: TypeError: Cannot read property 'type' of
  null(…)(anonymous function) @ product:15ZoneDelegate.invoke @
  zone.js:332Zone.run @ zone.js:225(anonymous function) @
  zone.js:586ZoneDelegate.invokeTask @ zone.js:365Zone.runTask @
  zone.js:265drainMicroTaskQueue @ zone.js:491ZoneTask.invoke @
  zone.js:435

My systemjs is as follows
/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs',
    'angular2-highcharts':        'node_modules/angular2-highcharts/dist',
    'highcharts/highstock.src':   'node_modules/highcharts/highstock.js'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    'angular2-highcharts' :       { main: 'index', defaultExtension: 'js' }
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

This is my app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { routing }       from './app.routing';
import { AppComponent }  from './app.component';
import { ProductDetail } from './detail.component';
import { CHART_DIRECTIVES } from 'angular2-highcharts';

@NgModule({
    imports:      [ BrowserModule, routing,FormsModule , CHART_DIRECTIVES],
    declarations: [ AppComponent,Detail ],
    exports:[Detail],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

A: You are importing the CHART_DIRECTIVES inside the imports array. the imports array is there specifically to import modules, nothing else.
Thus, you either need to wait for angular2-highcharts to package their directives into an Angular2 RC5 module, you can then simply import that module, or you will need to move CHART_DIRECTIVES into your "declarations" array for now

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get nested element using ServiceStack? Although I am able to access the SchemaVersion using code below, I cannot access FormatDocID nested element.
Any ideas how can I easily get FormatDocID using ServiceStack and AutoQueryFeature (or similar)?
I put only relevant parts of code here
public override void Configure(Container container)
{
    JsConfig.DateHandler = DateHandler.ISO8601;
    SetupValidators(container);
    SetupIOC(container);
    SetupPlugins(container, log);
    ContentTypes.Register("application/xml"
    , CLXmlSerializer.Serialize, ServiceStack.Text.XmlSerializer.DeserializeFromStream);
    SetupMetaDataRedirectionPath();
    SetupGlobalResponseFilters();
}

Setup plugins
private void SetupPlugins(Container container)
{
    Plugins.Add(new ValidationFeature());
    Plugins.Add(new SwaggerFeature());
    Plugins.Add(new AutoQueryFeature
    {
        MaxLimit = 1000,
        EnableUntypedQueries = false,
        IncludeTotal = true
    });

    Plugins.Add(new AutoQueryDataFeature {MaxLimit = 100}
        .AddDataSource(ctx => ctx.MemorySource(new List<WordDocument>
        {
            new WordDocument()
            {
                SchemaVersion = "",
                Format = new Word.DocumentFormat()
                {
                    FormatDocID = 254
                }
            }
        }))
        );

    typeof(RequestLogs).AddAttributes(new RestrictAttribute {VisibilityTo = RequestAttributes.None});
    typeof(AssignRoles).AddAttributes(new RestrictAttribute {VisibilityTo = RequestAttributes.None});
    typeof(UnAssignRoles).AddAttributes(new RestrictAttribute {VisibilityTo = RequestAttributes.None});
    typeof(Authenticate).AddAttributes(new RestrictAttribute {VisibilityTo = RequestAttributes.None});
}

Serializable classes
public abstract class Document
    {
        public DocumentFormat Format;

        public class DocumentFormat
        {
            [XmlAttribute] public int Version;

            public int FormatDocID;
            public string DocShortName;
        }
    }

public class WordDocument : Document
{
    [XmlAttribute] public string SchemaVersion { get; set; } = "1.0";
}

Thanks in advance for the answers.

A: It's not clear what you're trying to achieve or why, AutoQuery creates Auto Queryable APIs where the Response is the API Response serialized in the specified Response Content Type.
If you want to intercept the Typed Response DTO before it's returned you can create a Custom AutoQuery Implementation and introspect the response that way, e.g:
public class MyQueryServices : Service
{
    public IAutoQueryData AutoQuery { get; set; }

    //Override with custom implementation
    public object Any(MyQuery query)
    {
        var q = AutoQuery.CreateQuery(query, base.Request);
        var response = AutoQuery.Execute(query, q);
        return response;
    }
}

But the AutoQuery Memory Data Source you're using lets you provide your own collection of Typed POCOs as the Data source so you already have access to them when you create it, but the source POCOs should be a flat Type with public properties (in contrast to your class with public fields and nested types) - it's not possible to query nested object graph values.
This is an example of a POCO that doesn't use nested classes, or public fields:
public abstract class Document
{
    public int Version { get; set; }
    public int FormatDocID { get; set; }
    public string DocShortName { get; set; }
}

So the solution if you want to use AutoQuery would be to change your Data Source to use Flat POCOs with public properties otherwise you'd need to create the impl of your Service yourself.


text:
Q: How do i send headers in php without creating a new file? I'm using wordpress to create a 'download' popup that goes to a file attachment ID. The complexities aren't important, but basically I have it open in a new window with a "Download" link.
The file type is going to be mp3 so I don't want the browser to go to the mp3 and try to use an embedded quicktime player or anything like that, I just want it to force it to download.
Is there an easier way to do this than using php header() type stuff?
My 'download' popup has a whole bunch of code in it that loads the WP environment, pulls some attachment urls, changes the title of the page, etc, so its not like the php file can be blank with no whitespace except JUST the header() code (which I know it cant have anything else in the file in order to work).
Here's the code for the popup window that comes up with the 'download' link. to sum up my question, how do i make the download link in the following code just download the mp3 rather than trying to load it into the browser.
As a sidenote is there a way i can close the window automatically once the download starts? Its not a big deal because I have a close window that would just be nice.
<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');

$mix_id = $_GET['m'];
$track_id = $_GET['t'];

$mix_attachment_id  = get_post_meta( $mix_id, 'zip', true );
$mix_attachment_url = wp_get_attachment_url( $mix_attachment_id );

// Update download count
$downloads = get_post_meta($mix_id, 'downloads', true);
$downloads = (int)$downloads + 1;
update_post_meta($mix_id, 'downloads', $downloads );

// Determine if track or mix download
if ($track_id == '') {
  // Mixtape Play
  $title = get_the_title($mix_id);
  $link_text = "Download Mixtape";
  $download_link = wp_get_attachment_url( $mix_attachment_id );
} else {
  // Track Download
  $title = get_the_title($track_id);
  $track_attachment_id = get_post_meta($track_id, 'mp3', true);
  $download_link = wp_get_attachment_url( $track_attachment_id );
  $link_text = "Download Track";

}
?>
<!DOCTYPE html>

<title><?php echo $title; ?></title>

  <a class="download" href="<?php echo $download_link; ?>"><?php echo $link_text; ?>
  Close Window

A: You need to specify a couple of PHP headers to prompt the user to download the file: http://php.net/manual/en/function.header.php#example-4064.
Basically, the combination of headers and readfile() with an exit after tells the browser to offer the file as a download as opposed to displaying it as a web page.

A: You either have to use header() or you have to link directly to the file. You could use a single script though by simply adding an if statement. Something like:
// wordpress stuff

if( !empty($_GET['do_download']) ) {
    // headers here and output the mp3 file.
}
else {
    // show the download page
}

The main thing you have to ensure is that you don't output anything (including blank lines!) before you call header()
Note in my example I accessed $_GET directly. I believe there's a Wordpress specific way to access it and you should use that instead (I just don't know what it is offhand)

A: I've done something similar, although not within WP. I don't understand why you can't just do the Header() logic at the top of the page, before any headers are sent?
Something like below should work, just put it at the top of the page
$s_filename = $_GET['s'];

// SAVE FILE
if( !empty( $s_filename ) )
{
    if( file_exists( $s_filename ) )
    {
            $fsize = filesize( $s_filename );
            // SET HEADERS
            header("Content-Disposition: attachment; filename = " . $s_filename);
            header("Content-Type: application/octet-stream");
            header("Content-Length: " . $fsize);
            header("Cache-Control: private");

            readfile( $s_filename );

            $result = "Your file download will begin shortly.
\r\n";
    }
}
else
{
    $result = "Error: File not found.
\r\n";
}


text:
Q: Cloud Functions for Firebase: completing long processes without touching maximum timeout I have to transcode videos from webm to mp4 when they're uploaded to firebase storage. I have a code demo here that works, but if the uploaded video is too large, firebase functions will time out on me before the conversion is finished. I know it's possible to increase the timeout limit for the function, but that seems messy, since I can't ever confirm the process will take less time than the timeout limit.
Is there some way to stop firebase from timing out without just increasing the maximum timeout limit?
If not, is there a way to complete time consuming processes (like video conversion) while still having each process start using firebase function triggers?
If even completing time consuming processes using firebase functions isn't something that really exists, is there some way to speed up the conversion of fluent-ffmpeg without touching the quality that much? (I realize this part is a lot to ask. I plan on lowering the quality if I absolutely have to, as the reason webms are being converted to mp4 is for IOS devices)
For reference, here's the main portion of the demo I mentioned. As I said before, the full code can be seen here, but this section of the code copied over is the part that creates the Promise that makes sure the transcoding finishes. The full code is only 70 something lines, so it should be relatively easy to go through if needed.
const functions = require('firebase-functions');
const mkdirp = require('mkdirp-promise');
const gcs = require('@google-cloud/storage')();
const Promise = require('bluebird');
const ffmpeg = require('fluent-ffmpeg');
const ffmpeg_static = require('ffmpeg-static');

(There's a bunch of text parsing code here, followed by this next chunk of code inside an onChange event)
function promisifyCommand (command) {
    return new Promise( (cb) => {
        command
        .on( 'end',   ()      => { cb(null)  } )
        .on( 'error', (error) => { cb(error) } )
        .run();
    })
}
return mkdirp(tempLocalDir).then(() => {
    console.log('Directory Created')
    //Download item from bucket
    const bucket = gcs.bucket(object.bucket);
    return bucket.file(filePath).download({destination: tempLocalFile}).then(() => {
      console.log('file downloaded to convert. Location:', tempLocalFile)
      cmd = ffmpeg({source:tempLocalFile})
               .setFfmpegPath(ffmpeg_static.path)
               .inputFormat(fileExtension)
               .output(tempLocalMP4File)
      cmd = promisifyCommand(cmd)
      return cmd.then(() => {
        //Getting here takes forever, because video transcoding takes forever!
        console.log('mp4 created at ', tempLocalMP4File)
        return bucket.upload(tempLocalMP4File, {
            destination: MP4FilePath
        }).then(() => {
          console.log('mp4 uploaded at', filePath);
        });
      })
    });
  });

A: As follow up for the random anonymous person who tries to figure out how to get past transcoding videos or some other long processes, here's a version of the same code example I gave that instead sends a http request to a google app engine process which transcodes the file. No documentation for it as of right now, but looking at Firebase/functions/index.js code and the app.js code may help you with your issue.
https://github.com/Scew5145/GCSConvertDemo
Good luck.

A: Cloud Functions for Firebase is not well suited (and not supported) for long-running tasks that can go beyond the maximum timeout.  Your only real chance at using only Cloud Functions to perform very heavy compute operations is to find a way to split up the work into multiple function invocations, then join the results of all that work into a final product.  For something like video transcoding, that sounds like a very difficult task.
Instead, consider using a function to trigger a long-running task in App Engine or Compute Engine.


text:
Q: ionic 4 native http get empty data in html I am beginner in ionic 4. And I am trying to get json data from an api using native http. My code is working fine with a json data response, but the problem is I got empty data in html
json
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

main code :
import { Component } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  object : any  ;
  constructor(private http: HTTP) {
   this.http.get('https://jsonplaceholder.typicode.com/todos/1',{},{})
   .then(data => {

    this.object = data

  })    .catch(error => this.object = error);
  }

}

if l use only object in html he is return json response
 {{object}}

but if l want get title form data json l got empty page
 {{object.title}}

A: Digging into the documentation a bit, first of all, what the native http returns is:
this.http.get('http://ionic.io', {}, {})
  .then(data => {
    console.log(data.status);
    console.log(data.data); // data received by server
    console.log(data.headers);
  })
  .catch(error => {
    console.log(error.status);
    console.log(error.error); // error message as string
    console.log(error.headers);
  });

So your response is in data.data in above case. The image you posted, made me realize that we are dealing with a string! So, dug deeper and in the cordova docs I found that the response returned by native http, is indeed a string!

docs The success function receives a response object with 4 properties: status, data, url, and headers. status is the HTTP response code as numeric value. data is the response from the server as a string. url is the final URL obtained after any redirects as a string. headers is an object with the headers.

So what you need to do, is parse the response!
 this.http.get('https://jsonplaceholder.typicode.com/todos/1',{},{})
   .then(data => {
     this.object = JSON.parse(data.data)
   });

A: There are a few things here. If you are using angular, and you want to provide data to your HTML code, then you are going to need to use the @component decorator at the top of this class.
Inside of that decorator, you'll add some metadata. Part of this metadata will be the folder reference of your html template that you want to be controlled by this now component. Your html doesn't know about the data in this class because they are not tied together in any way that angular can understand.
I would try something closer to this:
@Component({
  selector: 'my-page-selector',
  templateUrl: './myPage.component.html',
  styleUrls: ['./myPage.component.css']
})
export class HomePage {

  object : any  ;
  constructor(private http: HTTP) {
   this.http.get('https://jsonplaceholder.typicode.com/todos/1',{},{})
   .then(data => {

    this.object = data.data

  })    .catch(error => this.object = error);
  }
}

You would then have a an html file 'myPage.Component.html' that could then know about it's driving component.
<div>
{{object.title}}
</div>

I would look up the angular documentation and get familiar with the angular CLI. This would help you generate components and templates together and you can avoid some of this confusion.


text:
Q: kill process after stop service I'm trying to kill a service process after I'm stopping the service, The service is going down very slow - something like 7 seconds, the program kill the process by the process id but it gets ArgumentException when I'm trying to do that with command line it still show me that the process is running  though I need to kill it with /F (force)
what am I missing?
    public void KillService(uint processID)
    {
     try
        {
            process = Process.GetProcessById((int)processID);
            if (process != null)
            {
                process.Kill();

            }
        }
        catch (ArgumentException)
        {
            // Thrown if the process specified by processID
            // is no longer running.
        }
        catch (Win32Exception)
        {
            // Thrown if process is already terminating,
            // the process is a Win16 exe or the process
            // could not be terminated.

        }
        catch (InvalidOperationException)
        {
            // Thrown if the process has already terminated.

        }
   }


text:
Q: How do I build a dynamic SQL query? Right, so I have a set of dropdowns on my page. Depending on whether a value is selected, I want to add it to an SQL query string in PHP. Example:
select1: options("*" "op1", "op2)
select2: options("*" "op1", "op2)
select3: options("*" "op1", "op2)

'*' refers to anything. i.e the data should not be filtered by that query option. Now, how do I build the query for this quickly and simply? Currently, I have something like this:
$query='';
$found=0;
$op1=$_POST['select1'];
$op2=$_POST['select2'];
$op3=$_POST['select3'];

if($op1!='*')
{
$found=1;
$op1="'".$op1."'";
$query="WHERE op1=$op1 ";

}

if($op2!='*')
{$op2="'".$op2."'";
if($found==1)
    {
    $query=$query. "AND op2=$op2 ";
    }
else{
    $found=1;
    $query="WHERE op2=$op2 ";
    }
}

if($op3!='*')
{$op3="'".$op3."'";
if($found==1)
    {
    $query=$query. "AND op3=$op3 ";
    }
else{
    $found=1;
    $query="WHERE op3=$op3 ";
    }
}

Now, obviously, this is quite annoying to implement. Is there any easier method?
Thanks.

A: I would have used a class MyQueryBuilder with following methods probably..
AddSelectionColumn(String ColumnName, string Alias)
AddTableSource(String TableName, String Alias)
AddTableJoin(String Table1, String Alias1, String Table2, String Alias2, String Col1, String Col2, JoinType Join)
AddFilterCondition(String ColumnName, String Alias, String Condition)

It might give a better control on the code...

A: I do a lot of this in my perl CGI scripts, and this is how I format it for simplicity / readability:
First, I use a separate variable for the where clause, and always set a condition of
1 = 1 so all subsequent conditions are "and" conditions:
my $whereClause      =<<ENDWHERESQL;
where
   1 = 1
ENDWHERESQL

if ( $op1 ne "*" )    { $whereClause .= "     and op1 = '".safeSQL($op1)."'\n"; }
if ( $op2 ne "*" )    { $whereClause .= "     and op2 = '".safeSQL($op2)."'\n"; }
if ( $op3 ne "*" )    { $whereClause .= "     and op3 = '".safeSQL($op3)."'\n"; }

then I use a simple function to protect against simple SQL injection attacks, because even though you are using drop down lists - someone could still put a "?op1=(evil sql)" on the end of your URL, and it might get through your form into your query:
#******************************************************************************
# Function: safeSQL()
#   Author: Ron Savage
#     Date: 04/22/2009
#
# Description:
# This removes update,create,drop,deletes from SQL.
#******************************************************************************
sub safeSQL
   {
   my $cmd;
   my ( $inText,$commandList ) = @_;

   if (!defined($commandList)) { $commandList = "create,delete,select,update,dele,drop,exec,insert"; }

   foreach $cmd (split(/\,/,$commandList))
      {
      $inText =~ s/ $cmd |^$cmd /** no_${cmd}_allowed! **/gi;
      }

   return($inText);
   }


text:
Q: http request cross-domain in Nodejs I need to call http request cross-domain which I can consume successfully by $.ajax with code below. The request bases on Basic Authentication, it works.

$.ajax({
    type: "GET",
    url: "https://" + username + ":" + password + "@/api/systems",
    //crossDomain: true,
    dataType: 'jsonp',
    async: true
}).done(function (result) {
    $("#div1").html(JSON.stringify(result.data));
});

However, I can't get it to work in nodejs running in server. My code is as below:

var request = require('request');
var url = "https://" + username + ":" + password + "@/api/systems";
var option = {
    url: url,
    auth: {
        user: username,
        password: password
    }
};
request(option,
    function (error, response, body) {
        console.log(body);
    }
);

It always returns Error 401 Unauthorized.
How can I get it in nodejs?

A: Use the npm for "cors", use it as middleware
https://www.npmjs.com/package/cors


text:
Q: In IIS7, gzipped files do not stay that way I have configured IIS7 to gzip static content.
http://www.coderjournal.com/2008/04/iis-7-compress-javascript-gzip/
However, the files don't "stay" gzipped.
Here's my use case:

*

*Request test.css file. It is not gzipped.

*Request it again within a few seconds. It is gzipped.

*Wait 5 minutes.

*Request test.css file again. It is not gzipped.

This doesn't make sense -- shouldn't the gzipped version of a static file be delivered on all subsequent requests, if the original did not change?
Note: I am using Firefox and Firebug to verify gzipped content by checking the Content-Encoding header.

A: According to this article:

Changes to compression in IIS7 by Kanwaljeet Singla

In IIS7, content is compressed depending on it's hit frequency which is configurable like this:
<system.webServer>
  <serverRuntime enabled="true"
    frequentHitThreshold="5"
    frequentHitTimePeriod="00:00:20" />
</system.webServer>

Maybe you're not hitting these thresholds?

A: Depending on how badly you need to optimize performance on your site, you might want to use Combres instead.
The big advantage is that it does only only minify and gzip your javascript files, but it also combines all files into one, so there is only one http request for all your javascript files. In addition, it also makes use of client-side caching, so that the file is only downloaded when necessary. Also, it does the all this for CSS files as well.
It's quite easy to set up, so instead of trying to fix this, your time might be better spent on getting Combres instead.

A: I would suggest you to pay attention on another software—Helicon Ape http://www.helicontech.com/ape
It's free for 3 web-sites and includes compression/caching solutions which work smoothly. Just in one string of configuration you will get gzip and cache enabled:
SetEnvIfNoCase mime text/.* gzip=9 cache-enable=mem

The rule above tells Ape to compress text/* mime-types with the highest level as well as cache them in memory. Just give it a try.


text:
Q: NoSuchElementException: Message: Unable to locate element while trying to click on the button VISA through Selenium and Python I can't click on this button to create a checkout on my bot.
I want to click the image to get another page.

    <input type="radio" class="visuallyhidden" name="cardTypeRadio" id="VISA" value="VISA" title="VISA" onclick="validateAndSubmit('VISA');">

            Visa

this is my code:

try:
             check = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID,"VISA" )))

             print ("Page is ready!")
             visa = driver.find_elements_by_xpath("label[@class='choiceLabel'][4]")
             visa.click()

        except TimeoutException:
             print ("Loading took too much time!")
             return check

im getting this error:

 File "C:\Users\x\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\x\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "c:/Users/pietro/Documents/monitor/x/bot.py", line 48, in all
    visa = driver.find_element_by_xpath("label[@class='choiceLabel'][4]")
  File "C:\Users\x\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\x\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\x\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\x\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: label[@class='choiceLabel'][4]

A: The button to create a checkout on my bot seems to be a Credit Card related field and historically Credit Card related fields resides within .
You can find a couple of relevant discussions in:

*

*Unable to locate element of credit card number using selenium python

*org.openqa.selenium.NoSuchElementException: Returned node (null) was not a DOM element when trying to locate card-fields-iframe by CssSelector
So if the the desired element is within an  so you have to:

*

*Induce WebDriverWait for the desired frame to be available and switch to it.

*Induce WebDriverWait for the desired element to be clickable.

*You can use either of the following solutions:

*

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe_css_selector")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for='VISA']"))).click()

*Using XPATH:
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe_xpath")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='VISA']"))).click()

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: The xPath you are searching for might look more like this:
//input[@name='cardTypeRadio' and @value='VISA']

If this doesn't give you the unique element we can refine it a bit.

A: Probably your xpath is  wrong.Try this below code.Hope this helps.
driver.find_element_by_xpath("//input[@name='cardTypeRadio']").click()

OR
driver.find_element_by_xpath("//input[@id='VISA']").click()

If the webdriver click do not work.Try JavaScript to click.
driver.execute_script("arguments[0].click();", driver.find_element_by_xpath("//input[@name='cardTypeRadio']"))

driver.execute_script("arguments[0].click();", driver.find_element_by_xpath("//input[@id='VISA']"))


text:
Q: How can i modifier a state only when has the same ID editItem = (id) => {
    this.setState(
      {
        lanche: [
        {
          id: id,
          editItem: true
        }]
      }
    )
  }

In this way, setState runs on all items in the array, I need to edit only the item that has the same ID

A: You need to find the item in the array with the given id, and modify that one only. setState method changes the whole object with the given key.
try this:
editItem = (id) => {
    this.setState(
      {
        lanche: this.state.lanche.map(item => {
           if(item.id === id) {
            item.editItem = true
           }
           return item;
        })
      }
    )
 }

A: You can use map like this:
editItem = (id) => {
  // update the relevant item
  const updatedItems = this.state.lanche.map(item => {
    if (item.id === id) {
      item.editItem = true;
    }
    return item;
   } );

    this.setState(
      {
        lanche: updatedItems
      }
    )
  }

A: If I understand your question;
You could search for the index like so;
const index = this.state.lanche.findIndex((e) => e.id === id);

and then alter the object
const newLanche = this.state.lanche;
newLanche[index].editItem = true;

And then update the store;
this.setState({ lanche: newLanche });


text:
Q: Proof: ((A or B) and (A or ~C) and (~B or ~C)) <=> ((A or B) and (~B or ~C)) How to prove the following using logical connectivities laws?
((A or B) and (A or ~C) and (~B or ~C)) <=> ((A or B) and (~B or ~C))

A: There are two related questions here.  The first is to show that each side of the double arrow implies the other, following rules of deduction.  In this interpretation, the forward direction follows immediately from the fact that $(X \wedge Y) \implies X$.  For the backwards direction, it suffices, as Trevor Wilson suggests in the comments, to prove $(A \vee B) \wedge (\neg B \vee \neg C) \implies (A \vee \neg C)$.  For this, note that $(X \vee \neg Y)$ is equivalent to the sentence $(Y \rightarrow X)$; then the problem to prove is equivalent to $(B \rightarrow \neg A) \wedge (C \rightarrow B) \implies (C \rightarrow A)$, which is almost surely either one of your axioms or something you proved early on.
A second interpretation is to find a series of algebraic manipulations that identify the two sides.  After some toying, I don't see a clever way to do this.  One non-clever way is the following.  You can treat $\vee$ as "multiplication" in a ring of characteristic $2$ (meaning $+$ and $-$ are the same), and $X \wedge Y = X + Y + XY = (X+1)(Y+1)+1$.  Finally, $X^2 = X$ and $\neg X = 1+X$.  Substituting $D = 1+C$, the LHS is:
$ (AB + AD + ABD) + (1+B)D + (AB + AD + ABD)(1+B)D = AB + AD + ABD + D + BD + (1+B)(ABD + AD + ABD) = AB + AD + ABD + D + BD + (1+B)AD = AB + AD + ABD + D + BD + AD + ABD = AB +  D + BD $
whereas the RHS is:
$ AB + (1+B)D + AB(1+B)D = AB + D + BD + ABD + ABD = AB + D + BD$.
Anyway, unpacking this final equality will in principal give you a direct proof, but it won't be short.

A: Here is a direct proof where we basically keep simplifying:
\begin{align}
& (A \lor B) \land (A \lor \lnot C) \land (\lnot B \lor \lnot C) \;\equiv\; (A \lor B) \land (\lnot B \lor \lnot C) \\
\equiv & \;\;\;\;\;\text{"simplify $\;P \equiv P \land Q\;$ to $\;P \Rightarrow Q\;$"} \\
& (A \lor B) \land (\lnot B \lor \lnot C) \;\Rightarrow\; A \lor \lnot C \\
\equiv & \;\;\;\;\;\text{"rewrite $\;P \Rightarrow Q\;$ to $\;\lnot P \lor Q\;$, using DeMorgan"} \\
& (\lnot A \land \lnot B) \lor (B \land C) \lor A \lor \lnot C \\
\equiv & \;\;\;\;\;\text{"use negation of $\;A\;$ and $\;\lnot C\;$ on other side of $\;\lor\;$"} \\
& (\text{true} \land \lnot B) \lor (B \land \text{true}) \lor A \lor \lnot C \\
\equiv & \;\;\;\;\;\text{"simplify"} \\
& \lnot B \lor B \lor A \lor \lnot C \\
\equiv & \;\;\;\;\;\text{"excluded middle"} \\
& \text{true} \lor A \lor \lnot C \\
\equiv & \;\;\;\;\;\text{"simplify"} \\
& \text{true} \\
\end{align}
Normally I would do this in three steps, but I've written it out a bit more for clarity.

A: Here is a proof using a Fitch-style proof checker:

Note that I added parentheses to the left hand side to disambiguate how the conjuncts were joined. This is not totally trivial. It put a constraint on how I would have to put these conjuncts together and remove them in constructing the proof.
The definitions of the inference rules can be found on the proof checker's page. The only one that is not an introduction or elimination rule is disjunctive syllogism (DS).

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/


text:
Q: Find next element depending on the previous ones i have some tabs and i want to select the next if i swipe left. Not all of my tabs are selectable since they can be disabled temorarily.
I try to solve this problem the "functional" way, but I can't do it.

const tabs = [
  { text: 'foo', selectable: false, selected: false },
  { text: 'bar', selectable: true, selected: true },
  { text: 'baz', selectable: false, selected: false },
  { text: 'hello', selectable: false, selected: false },
  { text: 'world', selectable: true, selected: false },
];

function nextTab() {
  let result;

  const selectedIndex = tabs.findIndex(t => t.selected);

  if (selectedIndex > -1) {
    result = tabs
    .filter((t, i) => i > selectedIndex)
    .find(t => t.selectable);
  }

  return result;
}

console.log(nextTab())

Is there a way without declate a variable and add a condition?
Thank you,
Christian

A: You can use slice()

const tabs = [
  { text: 'foo', selectable: false, selected: false },
  { text: 'bar', selectable: true, selected: true },
  { text: 'baz', selectable: false, selected: false },
  { text: 'hello', selectable: false, selected: false },
  { text: 'world', selectable: true, selected: false },
];

function nextTab() {
  return tabs
    .slice(tabs.findIndex(t => t.selected) + 1)
    .find(t => t.selectable);
}

console.log(nextTab())

A: I believe nextTab should return one type, not a union. In current representation, it may return an object or undefined.
Since we don't have Maybe/Option monad data structure, I believe it worth returning just index: -1 ... 4.
So nextTab will always return a number. I think it will be easier to compose.
type Tab = {
    text: string;
    selectable: boolean;
    selected: boolean;
}
const tabs = [
    { text: 'foo', selectable: false, selected: false },
    { text: 'bar', selectable: true, selected: true },
    { text: 'baz', selectable: false, selected: false },
    { text: 'hello', selectable: false, selected: false },
    { text: 'world', selectable: true, selected: false },
];

const selected = (tabs: Tab[]) => tabs.findIndex(t => t.selected);

const find = (tabs: Tab[], selectedIndex: number) =>
    tabs.reduce((acc, elem, index) =>
        index > selectedIndex && elem.selectable ? index : acc,
        -1
    )

const nextTabIndex = (tabs: Tab[]) => find(tabs, selected(tabs)) // 4

If you have a lot more validation, you can use compose function:
type Tab = {
    text: string;
    selectable: boolean;
    selected: boolean;
}
const tabs = [
    { text: 'foo', selectable: false, selected: false },
    { text: 'bar', selectable: true, selected: true },
    { text: 'baz', selectable: false, selected: false },
    { text: 'hello', selectable: false, selected: false },
    { text: 'world', selectable: true, selected: false },
];

type Fn = (...args: any[]) => any
const compose = (...fns: Fn[]) => <T,>(data: T) => fns.reduceRight((acc, fn) => fn(acc), data)

const selected = (tabs: Tab[]) => tabs.findIndex(t => t.selected);

const find = (tabs: Tab[])=>(selectedIndex: number) =>
    tabs.reduce((acc, elem, index) =>
        index > selectedIndex && elem.selectable ? index : acc,
        -1
    )

const result = compose(find(tabs), selected)(tabs)

But, in this particular case, I don't think it worth using


text:
Q: Faraday - Multiple GET param request to Freebase API I am stuck trying to get Topic information from the Freebase API. This is mostly a Ruby Faraday question anyways.
So I request at the following path:
https://www.googleapis.com/freebase/v1/topic/m/02676m4?limit=20&filter=/film/film_series/films_in_series&filter=/common/topic/article
Notice how there are TWO &filter. This works just fine using my web browser. When doing either the following on Ruby, though:
response = Faraday.get 'https://www.googleapis.com/freebase/v1/topic/m/02676m4', {
        'limit' => 20,
        'filter' => ['/film/film_series/films_in_series', '/common/topic/article'],
        'key' => 'my_key_here'
    }, { 'Accept' => self.Headers_Accept }

or...
response = Faraday.get 'https://www.googleapis.com/freebase/v1/topic/m/02676m4', {
        'limit' => 20,
        'filter' => '/film/film_series/films_in_series&filter=/common/topic/article',
        'key' => 'my_key_here'
    }, { 'Accept' => self.Headers_Accept }

or...
response = Faraday.get 'https://www.googleapis.com/freebase/v1/topic/m/02676m4?limit=20&filter=/film/film_series/films_in_series&filter=/common/topic/article&key=my_key_here', {}, { 'Accept' => self.Headers_Accept }

Then Filters are ignored by the API. I get a huge response with every single piece of information regarding my topic.
You can replicate the result by performing the query with no filters:
https://www.googleapis.com/freebase/v1/topic/m/02676m4?limit=20
Question:
Anyone can come up with a reason why I get this issue through Faraday, but not when accessing directly through my browser?
Extra tip:
If I only use one filter on the Faraday request, it works just fine. But I really need to use more than one filter.
Freebase Topic API:
http://wiki.freebase.com/wiki/Topic_API
Thanks!

A: This sounds a lot like the Faraday bug fixed by this pull request: https://github.com/technoweenie/faraday/pull/199


text:
Q: Fastest way to delete million of files I have a list of string which are relative paths. I also have a string which contains root path for those files. Now I am deleting them like this:
foreach (var rawDocumentPath in documents.Select(x => x.RawDocumentPath))
{
    if (string.IsNullOrEmpty(rawDocumentPath))
    {
        continue;
    }
    string fileName = Path.Combine(storagePath, rawDocumentPath);
    File.Delete(fileName);
}

the problem is that I call Path.Combine for every file, and it's slow enough.
How can I speed up this code? I can't delete whole folders, I cannot change current directory (because it affects a whole program)...
I need something like a class which can delete fast several files in specified directory.

A: If your disk can handle it, parallizing should help a lot:
documents.AsParallel().ForAll(
    document =>
    {
        if (!string.IsNullOrEmpty(document.RawDocumentPath))
        {
            string fileName = Path.Combine(storagePath, document.RawDocumentPath);
            File.Delete(fileName);
        }
    });


text:
Q: Python if-elif-else expressions returning a value and scope resolution Question 1
In rust, I can write code like this:
let foo = if ... {
  1
} else if ... {
  2
} else {
  3
};

Here foo is assigned the return value of that if-elseif-else expression.
Is something similar possible in Python?
Question 2
Is the outer variable "foo" updated in this python code?
foo = "hello"

if cond1:
   foo = "world"
else:
   pass

# if cond1 is true, what is the value of foo now? "hello" or "world"

A: it seems the closest Py version is a ternary op
#scenario 2

foo = "hello"

foo = "world" if True else foo

print(foo) # prints 'world'


text:
Q: Null value while trying to read XML data I tried to read XML data that matches my post id string (not null) attributes, but it returns null even though I have tried several times.
protected void Update_btn_click(object sender, EventArgs e)
{
    String new_title = newtitle.Text.ToString();
    String new_description = update_des.Value.ToString();
    String postid = Request.QueryString["pid"];

    System.Diagnostics.Debug.WriteLine(postid);

    string filename = "C:\\Users\\user\\Source\\Repos\\FoodBlog\\FoodBlog\\Data\\blog_post.xml";
    XmlDocument xml_doc = new XmlDocument();
    xml_doc.Load(filename);

    XmlTextReader xtr = new XmlTextReader(filename);

    XmlNodeList elemList = xml_doc.GetElementsByTagName("post");
    for (int i = 0; i < elemList.Count; i++)
    {
        string getValue = elemList[i].Attributes[postid].ChildNodes[1].InnerText;
        System.Diagnostics.Debug.WriteLine(getValue);
    }
}

XML data :
<Posts>
  <post pid="pid2623">
    <title>Test</title>
    <description>Test</description>
    <subtitle>Test</subtitle>
    <date>7/29/2018 12:00:00 AM</date>
    <author>est</author>
  </post>
</Posts>

Error :

A: I think there is something wrong with your code
you need to modify those lines, because in the for loop you are looking for an element that contains an attribute with name pid2623 but actually you need to look for a post whose pid attribute contains value pid2623
XmlNodeList elemList = xml_doc.GetElementsByTagName("post");
for (int i=0;i<elemList.Count; i ++)
{
    string getValue = elemList[i].Attributes[postid].ChildNodes[1].InnerText;
    System.Diagnostics.Debug.WriteLine(getValue);
}

to
 XmlNode elemList = xml_doc.SelectSingleNode("/Posts/Post[@pid='"+ postid +"']");

A: It is easier to use Linq To SQL IMHO:
XDocument xml_doc = XDocument.Load(filename);

foreach (var p in xml_doc.Elements("Posts"))
{
    System.Diagnostics.Debug
         .WriteLine((string)p.Element("post").Attribute("pid"));
}

and you could query a specific post like this:
var post = from p in xml_doc.Elements("Posts")
           where (string)p.Element("post").Attribute("pid") == postid
           select p.Element("post");


text:
Q: PDO supports PHP 5.2 I read that PDO is not supported well (buggy) in php 5.2. I would like to how buggy is PDO in PHP 5.2?

A: I've used PDO with PHP 5.2 (mainly with MySQL databases ; sometimes with Doctrine or Zend Framework, which use PDO underneath) for years, including on some big/important projects, and have never met any kind of critical bug.

As a sidenote : PHP 5.2 itself is not quite supported anymore, as it's reached its end-of-support


text:
Q: Как в вордпресс вывести текст с вхождением запроса при поиске? В вордпресс при поиске выводится анонс записи, в которой есть поисковый запрос.
Можно ли как-то выводить не анонс записи, а часть текста, в которую входит
поисковый запрос?
A: Темы WordPress обычно выводят результаты поиска с помощью шаблона search.php. В стандартной теме twentysixteen этот шаблон
\wp-content\themes\twentysixteen\search.php
вызывает еще и
\wp-content\themes\twentysixteen\template-parts\content-search.php
Можно отредактировать этот шаблон в той части, где вызывается функция excerpt и поставить туда свой код, который получает содержимое поста и делает с ним то, что нужно. Поисковый запрос в коде шаблона можно получить так:
$search = $_GET['s'];

В других темах это работает аналогично.


text:
Q: Embeddings and Characteristic Property of Subspaces Any embedding obeys the char. prop. of subspaces: "If $X_0\cong A\leq X$ then $X_0\hookrightarrow X$"
Does the converse hold as well: "If $X_0\hookrightarrow X$ then $X_0\cong \mathrm{im}\leq X$"
...where '$\cong$' means 'being homeomorphic'
...where '$\leq$' means 'being subspace'
...where '$\hookrightarrow$' means 'obeying characteristic property'
...where '$\mathrm{im}$' means 'image of'

A: So you have a funciton $\iota:(X_0,\tau_0)\to(X,τ)$ with the universal property that for a space $(Y,\sigma)$ a set map $f:Y\to X_0$ is continuous iff $ι\circ f$ is continuous. Then first of all $ι=ι\circ\text{Id}$ is continuous since $\text{Id}$ is.
Now let $A=\text{Im}(X_0)$ be the subspace of $(X,τ)$ with $i:A\hookrightarrow X$ being the inclusion satisfying(?) the universal property. This means the restriction $\barι:X_0\to A$ is continuous iff $ι=i\barι$ is continuous, which is true. Conversely, $\barι^{-1}$ is continuous iff $i=ι\barι^{-1}$ is, which is true as well.


text:
Q: Processing Javascript on the server I'm looking to use this chart generation library: http://www.jqchart.com/
Ideally, I would prefer to use a PHP charting library for the current project I'm working, but, by the looks of it, this is the only library I've found that can handle what I need to do (given a somewhat unconventional requirement for the charts).
The issue is that I need to get the generated graphs as images (at the moment each graph seems to be a combination of images) to the server so that I can generate some PDF documents, etc.
I'm thinking of attempting to create an image using JS, pushing this back to the server and then generating the PDF although this pretty nasty and will probably cause issues between different versions of the browser.
So now what I'm looking for is a solution that will allow me to generate the graphs and turn them into images on the backend.
Any ideas?
EDIT: For the requirement that led me to rule out a number of other charting libraries, see here: Complex charts in Google Charts
That really isn't all that relevant to the question of processing Javascript on the server, though.

A: You can render a javascript graph on the server using  phantomjs. Here is an example.

A: Not sure what your requirements are, but I'd check out Google Chart Tools: http://code.google.com/apis/chart/. It's really simple to use. All the data is in the image URL get request, so you can generate charts using client-side JavaScript too.


text:
Q: BroadcastReceiver with multiple filters or multiple BroadcastReceivers? I have an Android Activity that needs to catch two different broadcasts. My current approach is to have a single BroadcastReceiver within the Activity and catch both the broadcasts with it:
public class MyActivity extends Activity {
    private MyActivity.BroadcastListener mBroadcastListener;
    private boolean mIsActivityPaused = false;

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

        // Create the broadcast listener and register the filters
        mIsActivityPaused = false;
        mBroadcastListener = new BroadcastListener();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Params.INTENT_REFRESH);
        filter.addAction(Params.INTENT_UPDATE);
        registerReceiver(mBroadcastListener, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsActivityPaused = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsActivityPaused = true;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mBroadcastListener);
        super.onDestroy();
    }

    private void refresh() {
        // refresh
    }

    private void update() {
        // update
    }

    private class BroadcastListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Params.INTENT_REFRESH && !mIsActivityPaused)) {
                refresh();
            } else if (intent.getAction().equals(Params.INTENT_UPDATE)) {
                update();
            }
        }
    }
}

I want to execute refresh() only if my Activity is visible on the screen, but I want to catch INTENT_UPDATE and execute update() during the entire lifetime of the Activity, regardless of whether the Activity is visible or not.
I didn't find any way to unregister only one of the two filters that I register in onCreate, so I use a flag to enable or disable the action to be executed when the INTENT_REFRESH broadcast is caught, depending on the state of the Activity.
The question is: is this the correct approach?
Or, would it be better to have two separate BroadcastReceivers as follows:
public class MyActivity extends Activity {
    private MyActivity.BroadcastListenerRefresh mBroadcastListenerRefresh;
    private MyActivity.BroadcastListenerUpdate mBroadcastListenerUpdate;
    private boolean mIsBroadcastListenerRefreshRegistered = false;

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

        // Create the broadcast listeners
        mBroadcastListenerRefresh = new BroadcastListenerRefresh();
        mBroadcastListenerUpdate = new BroadcastListenerUpdate();

        registerReceiver(mBroadcastListenerRefresh, new IntentFilter(Params.INTENT_REFRESH));
        registerReceiver(mBroadcastListenerUpdate, new IntentFilter(Params.INTENT_UPDATE));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBroadcastListenerRefresh != null && !mIsBroadcastListenerRefreshRegistered) {
            registerReceiver(mBroadcastListenerRefresh, new IntentFilter(Params.INTENT_REFRESH));
            mIsBroadcastListenerRefreshRegistered = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBroadcastListenerRefresh != null && mIsBroadcastListenerRefreshRegistered) {
            unregisterReceiver(mBroadcastListenerRefresh);
            mIsBroadcastListenerRefreshRegistered = false;
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mBroadcastListenerRefresh);
        unregisterReceiver(mBroadcastListenerUpdate);
        super.onDestroy();
    }

    private void refresh() {
        // refresh
    }

    private void update() {
        // update
    }

    private class BroadcastListenerRefresh extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Params.INTENT_REFRESH)) {
                refresh();
            }
        }
    }

    private class BroadcastListenerUpdate extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Params.INTENT_UPDATE)) {
                update();
            }
        }
    }
}

And which one has better performance?

A: Using KOTLIN you can do it inline:
  broadcastReceiver = NukeBroadcastReceiver()
        registerReceiver(broadcastReceiver, IntentFilter().apply {
            addAction(ACTION_DESTROY_EVERYTHING)
            addAction(ACTION_RESTART_WORLD)
        })

A: For every action , create IntentFilter and register it.
@Override
protected void onResume() {

    super.onResume();

    BroadcastListener receiver = new BroadcastListener();

    // Register the filter for listening broadcast.
    IntentFilter filterRefresh = new IntentFilter(Params.INTENT_REFRESH);
    IntentFilter filterUpdate = new IntentFilter(Params.INTENT_UPDATE);

    registerReceiver(receiver, filterRefresh);
    registerReceiver(receiver, filterUpdate);
}

private class BroadcastListener extends BroadcastReceiver {
    public void onReceive(Context ctx, Intent intent) {

        if (intent.getAction().equals(Params.INTENT_UPDATE)) {
            update();
        } else if(intent.getAction().equals(Params.INTENT_REFRESH)) {
            refresh();
        }
    }

}

A: instead, you may provide two different intent filters:
filter for refresh only
IntentFilter filterRefresh = new IntentFilter(Params.INTENT_REFRESH);

filter for refresh and update
IntentFilter filterRefreshUpdate = new IntentFilter();
filterRefreshUpdate.addAction(Params.INTENT_REFRESH);
filterRefreshUpdate.addAction(Params.INTENT_UPDATE);

now you may switch between intent filters by registering and un-registering the desired one but your receiver's implementation would be same


text:
Q: Base64 Decoded Password(Angular js) not working on server side I have an angular web app where I am trying to remember the username and password of the user on click of the checkbox . This is the code I am using
  var vm = this;

  if (rememberMeService('7ZXYZ@L') && rememberMeService('UU@#90'))
  {
    vm.username = AuthenticationService.Base64.decode(rememberMeService('7ZXYZ@L'));
    vm.password = AuthenticationService.Base64.decode(rememberMeService('UU@#90'));
  }

  vm.rememberMe = function ()
  {
    if (vm.remember)
    {
      rememberMeService('7ZXYZ@L', AuthenticationService.Base64.encode(vm.username));
      rememberMeService('UU@#90', AuthenticationService.Base64.encode(vm.password));
    }
    else
    {
      rememberMeService('7ZXYZ@L', '');
      rememberMeService('UU@#90', '');
    }
  }

This is the Html
<input data-ng-click="vm.rememberMe()" data-ng-model="vm.remember" name="remember" type="checkbox">   Remember Me

When I am trying to see the value in developer tools the value is the same as the password  that needs to be sent . But it is not validating on server side. But when I type the password again (the same password) then its validating on server side

A: may be try to call $scope.$apply rememberMe function


text:
Q: Разделить строку по первому числу Имеется строка в формате
24 Example 62.34 7

Нужно достать из этого первое число
24

И отдельно нужно получить всё, что после первого числа.
 Example 62.34 7

A: Вот решение на регулярных выражениях.
String s = "24 Example 62.34 7 ";
Pattern p = Pattern.compile("(^|\\s+)([0-9]+)(.*)");
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(m.group(2));
    System.out.println(m.group(3));
}

Output
24
 Example 62.34 7

A: Например, используя java.util.Scanner:
String input = "24 Example 62.34 7";
Scanner s = new Scanner(input);
int firstInt = s.nextInt();
// firstInt == 24

Проверка: http://ideone.com/TSB8lH

A: Можно разными способами. Например регулярками. Но, если после первого числа у вас всегда идёт пробел, то можно просто строку по пробелу на массив разбить и отбросив первый элемент собрать заново:
String input = "24 Example 62.34 7";
String[] array = input.split(" ");
String result = "";

for(int i = 1; i<array.lenght; i++)
{
    result += array[i];
    if(i != array.lenght-1) result+=" ";
}
System.out.println(result);
//выведет: Example 62.34 7

//Первое число можно вывести соответственно так:
System.out.println(array[0]);
//выведет: 24


text:
Q: Convert Oracle 12c database from WE8MSWIN1252 to utf-8 character set I've been tasked with giving my project manager development/test estimates. We are converting our Oracle12c database from a character set of WE8MSWIN1252 to utf-8 characters.
I've been tasked to come up with development change estimates on the following.

*

*Switch datatype from Byte to Char (i.e. VARCHAR2(10 byte) to VARCHAR2(10 char) )

*changing code where Length needs to be replaced by lengthb
My Questions.

*

*Do I only have to worry about changing database table columns from byte to char? or are there other objects on the database I might need to look at?

*Is Length to Lengthb the only Pl/SQL function I need to look at?

*As a developer is there any other areas I need to look at (i.e. We have Oracle forms/reports)?

*I noticed the below code can Alter all the tables columns in user_tab_columns do I need to run this for other object types and objects that are not fetched by the below query.

   BEGIN
    FOR X IN (SELECT C.TABLE_NAME,
                     C.COLUMN_NAME,
                     C.DATA_TYPE,
                     C.DATA_LENGTH
                FROM USER_TAB_COLUMNS C
               WHERE DATA_TYPE LIKE 'VARCHAR%'
                AND CHAR_USED = 'B'
                AND NOT EXISTS (SELECT 1 FROM USER_VIEWS V WHERE V.VIEW_NAME = C.TABLE_NAME))
    LOOP
        EXECUTE IMMEDIATE('ALTER TABLE '||X.TABLE_NAME||' MODIFY '||X.COLUMN_NAME||' '||X.DATA_TYPE||'('||X.DATA_LENGTH||' CHAR)');
    END LOOP;
    END;

Thanks in advance guys.

A: I would strongly suggest you take a read of note 225912.1 on support.oracle.com.
There may be a fair bit involved in changing the characterset, including scanning for existing data that might need to reloaded/altered etc.


text:
Q: How to get specific lines from the file ( between two sections)? I'm trying to read specific lines in-between two sections using Java 8.
I need to get the information in between ~CURVE INFORMATION and ~PARAMETER INFORMATION
I was able to get it using by checking startsWith() or equals and start storing the lines in some stringbuilder or collection. But is there any method available to get some specific lines in-between some sections.
I was looking at below questions for reference.
How to read specific parts of a .txt file in JAVA
How to read specific parts of the text file using Java
Sample data from file:
~WELL INFORMATION
#MNEM.UNIT      DATA TYPE    INFORMATION
#----------   ------------   ------------------------------
 STRT.FT        5560.0000:   START DEPTH
 STOP.FT       16769.5000:   STOP DEPTH
 STEP.FT           0.5000:   STEP LENGTH
 NULL.          -999.2500:   NULL VALUE
 COMP.              SHELL:   COMPANY
~CURVE INFORMATION
#MNEM.UNIT       API CODE    CURVE DESCRIPTION
#----------   ------------   ------------------------------
 DEPT.F                  :
 SEWP.OHMM   99 000 00 00:
 SEMP.OHMM   99 120 00 00:
 SEDP.OHMM   99 120 00 00:
 SESP.OHMM   99 220 01 00:
 SGRC.GAPI   99 310 01 00:
 SROP.FT/HR  99 000 00 00:
 SBDC.G/C3   45 350 01 00:
 SCOR.G/C3   99 365 01 00:
 SPSF.DEC    99 890 03 00:
~PARAMETER INFORMATION
#MNEM.UNIT          VALUE    DESCRIPTION
#----------   ------------   ------------------------------
 RMF .OHMM              -:   RMF
 MFST.F                 -:   RMF MEAS. TEMP.
 RMC .OHMM              -:   RMC
 MCST.F                 -:   RMC MEAS. TEMP.
 MFSS.                  -:   SOURCE RMF.
 MCSS.                  -:   SOURCE RMC.
 WITN.             MILLER:   WITNESSED BY
~OTHER INFORMATION

A: Using Java9 you can do it elegantly with streams
 public static void main(String[] args) {
    try (Stream<String> stream = Files.lines(Paths.get(args[0]))) {

        System.out.println(stream.dropWhile(string -> !"~CURVE INFORMATION".equals(string)).takeWhile( string -> !"~PARAMETER INFORMATION".equals(string)).skip(1).collect(Collectors.joining("\n")));

    } catch (IOException e) {
        e.printStackTrace();
    }
}

What makes it pleasing is the declarative nature of streams, your literally writing code that says drop elements until start mark then take elements until end mark and join them using "\n"! Java9 added takeWhile and dropWhile, I'm sure you can implement them or get their implementation from a library for java 8. Of course this is just another way to achieve the original goal.


text:
Q: How to check whether API endpoint request is made from AWS lambda or not? I'm using NodeJS to create REST APIs for a web app. I want a few endpoints to be triggered only from AWS Lambda functions.
How can I identify whether a request is made from AWS Lambda or not and restrict accordingly?

A: I am not sure whether there is another way to do it. But you can achieve this way :

*

*Add a secure key to the AWS Lambda environment variable.

*Whenever you call API from the lambda pass secret key in a request header.

*Check for the request header at receiving end.


text:
Q: Retornar de um sub menu para o menu principal de uma função em Python Eu criei uma aplicação simples em Python referente a um sistema de agenda com o Sqlite3. São 3 arquivos o menu principal agenda.py o de contato.py e usuario.py que farão login no sistema.
No arquivo 'agenda.py' eu faço o login do usuário chamando a função login(conexao, login, senha) que está no arquivo 'usuario.py' que me retorna a função menuContatos() que está no arquivo 'contatos.py', dentro desse menu a opção 6 é sair retornando para o menu inicial de login do arquivo 'agenda.py' é ai que eu não consigo retornar para essa tela inicial
Abaixo está o código que estou utilizando.
Agenda.py
from usuario import *
from contatos import *
import getpass

print("\n\033[47m\033[31mConectando no banco...\033[0;0m\n")
conexao = sqlite3.connect("banco.sqlite")

print("\n--- Efetuar Login no Sistema ---\n")

usuario = input("Por favor, informe o usuário: ")

senha = getpass.getpass("Por favor, informe a senha: ")

login(conexao, usuario, senha)

print("\n\033[47m\033[31mFechando conexão com o banco...\033[0;0m\n")
conexao.close()

contatos.py
from usuario import *

# --- Função para criar a tabela ----
def criar_tabela_contato(conexao):

    cursor = conexao.cursor()

    sql = """
        CREATE TABLE IF NOT EXISTS contato (
            nome text,
            fone text,
            email text,
            usuario integer
        );
    """

    cursor.execute(sql)

    conexao.commit()
# --------------------------------------------

#  --- Função para inserir o contato ---
def inserir_contato(conexao, nome, telefone, email, id):

    cursor = conexao.cursor()

    sql = """
        INSERT INTO contato VALUES(
            '{}',
            '{}',
            '{}',
             {}
        );
    """.format(nome, telefone, email, id)

    cursor.execute(sql)

    conexao.commit()
# --------------------------------------------

# --- Função para listar contatos ---
def listar_contato(conexao):

    cursor = conexao.cursor()

    sql = "SELECT rowid, * FROM contato ORDER BY nome;"

    cursor.execute(sql)

    contato = cursor.fetchall()

    print("\033[32mId Nome    Telefone     E-mail\033[0;0m\n")
    print("\033[32m== ======= ===========  ================\033[0;0m\n")
    for cont in contato:
        print("{}: {} - ({}) -".format(cont[0], cont[1], cont[2]), cont[3] )
# -----------------------------------------------------------

# --- Função para excluir contatos ---
def excluir_contato(conexao, id):

    cursor = conexao.cursor()

    sql = """
        DELETE FROM contato
        WHERE rowid = {};
    """.format(id)

    cursor.execute(sql)

    conexao.commit()
# ---------------------------------------------------------------

# --- Função para buscar contatos ---
def buscar_contato(conexao, nome):

    cursor = conexao.cursor()

    sql = "SELECT rowid, * FROM contato WHERE nome LIKE '%{}%';".format(nome)

    cursor.execute(sql)

    contato = cursor.fetchall()

    print("\033[32mId Nome    Telefone  E-mail\033[0;0m\n")
    print("\033[32m== ======= ========  ================\033[0;0m\n")
    for cont in contato:
        print( "{}: {} - ({}) -".format(cont[0], cont[1], cont[2]), cont[3] )
# ----------------------------------------------------------------

# --- Função para alterar contatos ---
def alterar_contato(conexao, nome, telefone, email, id):

    cursor = conexao.cursor()

    sql = "UPDATE contato SET nome = '{}', fone = '{}', email = '{}' WHERE rowid = {}".format(nome, telefone, email, id)

    cursor.execute(sql)

    conexao.commit()
# -----------------------------------------------------------------------------------------------------------------------

# ========== Menu Principal ==========
def menuContatos():
    print("\n\033[47m\033[31mConectando no banco...\033[0;0m\n")
    conexao = sqlite3.connect("banco.sqlite")

    opcao = 0
    while opcao != 6:
        print("""\033[32m
Em relação aos contatos do sistema, você deseja...

        1 - Inserir
        2 - Buscar
        3 - Listar
        4 - Alterar
        5 - Excluir
        6 - Retornar
\033[0;0m""")

        opcao = int(input("\033[32mInforme a opção desejada: \033[0;0m"))

        if opcao == 1:
            print("\n\033[47m\033[30m--- Digite os dados do contato ---\033[0;0m\n")

            while True:
                n = input("Nome: ")
                if n == "":
                    print("\n\033[47m\033[30mEspaço vazio! Digite um nome...\033[0;0m")
                else:
                    break

            while True:
                t = input("Telefone: ")
                if t == "":
                    print("\n\033[47m\033[30mEspaço vazio! Digite um telefone...\033[0;0m")
                else:
                    break

            while True:
                e = input("E-mail: ")
                if e == "":
                    print("\n\033[47m\033[30mEspaço vazio! Digite um endereço de e-mail...\033[0;0m")
                else:
                    break

            while True:
                i = int(input("Id: "))
                if i == "":
                    print("\n\033[47m\033[30mEspaço vazio! Digite um Id...\033[0;0m")
                else:
                    break

            print("\n\033[47m\033[30m--- Contato inserido com sucesso ---\033[0;0m\n")

            inserir_contato(conexao, n, t, e, i)

        elif opcao == 2:
            print("\n\033[47m\033[30m--- Buscar Registro ---\033[0;0m\n")

            nome = input("Digite o nome do contato: ")
            print("\n\033[47m\033[30m--- Registros Encontrados ---\033[0;0m\n")
            buscar_contato(conexao, nome)

        elif opcao == 3:
            print("\n\033[47m\033[30m--- Lista de contatos cadastrados ---\033[0;0m\n")
            listar_contato(conexao)

        elif opcao == 4:
            print("\n\033[47m\033[30m--- Alteraçao de Contatos ---\033[0;0m\n")

            n = input("Nome: ")
            t = input("Telefone: ")
            e = input("Email: ")
            i = int(input("Id: "))
            alterar_contato(conexao, n, t, e, i)
            print("\n\033[47m\033[30m--- Alteração realizada com sucesso ---\033[0;0m\n")

        elif opcao == 5:
            print("\n\033[47m\033[30m--- Exclusão de Registro ---\033[0;0m\n")

            id = input("Digite o ID para do contato para excluir: ")
            excluir_contato(conexao, id)
            print("\n\033[47m\033[30m--- Contato excluido com sucesso ---\033[0;0m")

        elif opcao == 6:
            print("\n\033[47m\033[30m--- Retornando para o Menu Agenda ----\033[0;0m\n")
            return login(conexao, usuario, senha)

    print("\n\033[47m\033[31mFechando conexão com o banco...\033[0;0m\n")
    conexao.close()

usuarios.py
import sqlite3
from contatos import *

# ---  Funções do Programa ---

# --- Função 1: Criação da Tabela ---
def criar_tabela_usuario(conexao):

    cursor = conexao.cursor()

    sql = """
        CREATE TABLE IF NOT EXISTS usuario(
            nome text,
            login text,
            senha text
        );
    """

    cursor.execute(sql)
# ---------------------------------------------------

# --- Função 2: Inserir Usuário ---
def inserir_usuario(conexao, nome, login, senha):

    cursor = conexao.cursor()

    sql = """
        INSERT INTO usuario VALUES(
            '{}',
            '{}',
            '{}'
        );
    """.format(nome, login, senha)

    cursor.execute(sql)

    conexao.commit()
# ---------------------------------------------------

# --- Função 3: Listar Usuários ---
def listar_usuarios(conexao):

    cursor = conexao.cursor()

    sql = "SELECT rowid, * FROM usuario ORDER BY nome;"

    cursor.execute(sql)

    usuarios = cursor.fetchall()

    print("\033[34mId Nome    Login\n\033[0;0m")
    print("\033[34m== ======= =========\n\033[0;0m")
    for usr in usuarios:
        print( "{}: {} - ({})".format(usr[0], usr[1], usr[2]) )
# ---------------------------------------------------------------

# --- Função 4: Excluir Usuários ---
def excluir_usuario(conexao, id):

    cursor = conexao.cursor()

    sql = """
        DELETE FROM usuario
        WHERE rowid = {};
    """.format(id)

    cursor.execute(sql)

    conexao.commit()
# ---------------------------------------------------------------

# --- Função 5: Buscar Usuários ---
def buscar_usuario(conexao, nome ):

    cursor = conexao.cursor()

    sql = "SELECT rowid, * FROM usuario WHERE nome LIKE '%{}%';".format(nome)

    cursor.execute(sql)

    usuario = cursor.fetchall()

    print("\033[34mId Nome    Login\n\033[0;0m")
    print("\033[34m== ======= ========\n\033[0;0m")
    for usr in usuario:
        print( "{}: {} - ({})".format(usr[0], usr[1], usr[2]))
# -----------------------------------------------------------------

# --- Função 6: Alterar Contatos --
def alterar_usuario(conexao, nome, login, senha, id):

    cursor = conexao.cursor()

    sql = "UPDATE usuario SET nome = '{}', login = '{}', senha = '{}' WHERE rowid = {}".format(nome, login, senha, id)

    cursor.execute(sql)

    conexao.commit()

# ----------------------------------------------------------------------------------------------------------------

#  --- Função 7: Login Menu Principal ---
def login(conexao, login, senha):

    cursor = conexao.cursor()

    sql = "SELECT rowid, * FROM usuario WHERE login LIKE '{}' AND senha LIKE '{}';".format(login, senha)

    cursor.execute(sql)

    usuario = cursor.fetchall()

    if usuario:
        for usr in usuario:
            print( "\n--- Bem Vindo! ---\n\n--- {} ---\n".format(usr[1]))
            return menuContatos()
    else:
        print("\n--- Usuário inválido! ---\n")
        print("...Retornado para o Menu Agenda...\n")

# -----------------------------------------------------------------------------------------------------------------

# --- Menu Principal do Programa ---

def menuUsuario():
    print("\n\033[47m\033[31mConectando no banco...\033[0;0m\n")
    conexao = sqlite3.connect("banco.sqlite")

    opcao = 0
    while opcao != 6:
        print("""\033[34m
Em relação aos usuários do sistema, você deseja...

        1 - Inserir
        2 - Buscar
        3 - Listar
        4 - Alterar
        5 - Excluir
        6 - Voltar
\033[0;0m""")

        opcao = int(input("\033[34mOpção desejada: \033[0;0m"))

        if opcao == 1:
            print("\n\033[47m\033[30m\--- Digite os dados do usuário ---\033[0;0m\n")

            while True:
                n = input("Nome: ")
                if n == "":
                    print("\n\033[47m\033[30mEspaço vazio! Digite um nome...\033[0;0m\n")
                else:
                    break

            while True:
                l = input("Login: ")
                if l == "":
                    print("\n\033[47m\033[30mEspaço vazio! Digite um login...\033[0;0m\n")
                else:
                    break

            while True:
                s = input("Senha: ")
                if s == "":
                    print("\n\033[47m\033[30mEspaço vazio! Digite um senha...\033[0;0m\n")
                else:
                    break

            print("\n\033[47m\033[30m--- Contato inserido com sucesso ---\033[0;0m\n")

            inserir_usuario(conexao, n, l, s)

        elif opcao == 2:
            print("\n\033[47m\033[30m--- Buscar registro ---\033[0;0m\n")

            nome = input("Digite o nome do usuário para a busca: ")
            print("\n\033[47m\033[30m--- Registros Encontrados ---\033[0;0m\n")
            buscar_usuario(conexao, nome)

        elif opcao == 3:
            print("\n\033[47m\033[30m--- Lista de usuário cadastrados ---\033[0;0m\n")
            listar_usuarios(conexao)

        elif opcao == 4:
            print("\n\033[47m\033[30m--- Alteração de Usuários ---\033[0;0m\n")

            n = input("Nome: ")
            l = input("Login: ")
            s = input("Senha: ")
            i = input("Id: ")
            alterar_usuario(conexao, n, l, s, i)
            print("\n\033[47m\033[30m--- Alteração realizada com sucesso ---\033[0;0m\n")

        elif opcao == 5:
            print("\n\033[47m\033[30m--- Exclusão de registro ---\033[0;0m\n")

            id = input("Digite o ID para do contato para excluir: ")
            excluir_usuario(conexao, id)
            print("\n\033[47m\033[30m--- Usuário excluido com sucesso ---\033[0;0m\n")

        elif opcao == 6:
            print("\n\033[47m\033[30m--- Voltando ----\033[0;0m\n")
            break
    # Fechando a conexão (ligação) com o banco
    print("\n\033[47m\033[31mFechando conexão com o banco...\033[0;0m\n")
    conexao.close()

A: O problema é que o seu menu principal não está dentro do while, e sim no escopo do módulo principal, assim, ele não se repete! depois que ele termina o programa acaba! Basta indentá-lo corretamente.
Marquei abaixo com um _ os espaços que acrescentei, para você ver a área que faltou indentar:
from usuario import *
from contatos import *
import getpass

# Menu Principal Agenda ---
print("\n\033[47m\033[31mConectando no banco...\033[0;0m\n")
conexao = sqlite3.connect("banco.sqlite")

opcao = 0
while opcao != 2:
    print("""--- Menu Agenda ---

    1 - Entrar
    2 - Sair
    """)

____opcao = int(input("Escolha uma das opções: "))
____if opcao == 1:
____    print("\n--- Efetuar Login no Sistema ---\n")
____    usuario = input("Por favor, informe o usuário: ")
____    senha = getpass.getpass("Por favor, informe a senha: ")
____    login(conexao, usuario, senha)
____elif opcao == 2:
____    print("\nFechando o programa....\n")
____    break

print("\n\033[47m\033[31mFechando conexão com o banco...\033[0;0m\n")
conexao.close()

EDIT:
Além de fazer a alteração acima, você deve alterar a linha 187 de contatos.py, essa linha aqui:
return login(conexao, usuario, senha)

deve ficar somente assim:
return

Foi a função login()  que chamou a função menuContatos()... então para retornar para a função login() basta sair da função menuContatos() com return, sem chamar a função login() novamente.
Isso fará com que a função login() finalize também e então o fluxo de execução do código vai voltar para repetir o "Menu Agenda" através do while que coloquei na primeira parte da minha resposta, logo acima.


text:
Q: Protege: Excel / csv to rdf conversion I have created a Family ontology, and now I want to convert the data in csv into rdf using the ontology, plz correct if I am wrong, how can I do this ?
The Excel Import utility of Protege is no longer supported !
I am using Protege 4.3


text:
Q: Bootstrap, col не работает при размере экрана больше 600, две col-ы должны стать рядом а не столбом, пробовал так col-md-6 но не вышло.

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}
.navbar-toggler{
    margin-right: 5%!important;
}
.navbar-brand{
    margin-left: 5%!important;
}
.col{
    display: flex;
    flex-direction: column;
    margin-left:4%;
}
.s{
    margin-right: 7%;
    margin-left: 4%;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="style.css">

Collapsed content

Add some information about the album below, the author, or any other background context. Make it a few sentences long so folks can pick up some informative tidbits. Then, link them off to some social networking sites or contact information.

Contact

                        Follow on Twitter
                        Like on Facebook
                        Email me

                Bootstrap

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">

            </button>

A: родителю row выруби flex-wrap . И самим колонкам  flex свойства


text:
Q: Spring boot 2 embed tomcat 9.0.26 can not load jks file stream closed I try to use SSL on spring boot 2.2.0 with embeded tomcat 9.0.26 but
tomcat can not load JKS file stream closed.
Here is application properties:
server.port=443
server.ssl.key-store-type=JKS
server.ssl.key-store=C:\\Keystore\\mykey.jks
server.ssl.key-store-password=cccc
server.ssl.key-alias=*.mydomain.com

Exception:
org.springframework.boot.web.server.WebServerException: Unable to
  start embedded Tomcat server
          at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:215)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.startWebServer(ServletWebServerApplicationContext.java:297)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:163)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
  ~[spring-context-5.2.0.RELEASE.jar!/:5.2.0.RELEASE]
          at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at eu.soluma.app.SolumaTdvApplication.main(SolumaTdvApplication.java:34)
  ~[classes!/:0.0.1-SNAPSHOT]
          at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
  Method) ~[na:na]
          at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  ~[na:na]
          at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  ~[na:na]
          at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
          at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
  ~[SolumaTDV-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
  ~[SolumaTDV-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
  ~[SolumaTDV-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
          at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
  ~[SolumaTDV-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT] Caused by:
  java.lang.IllegalArgumentException:
  standardService.connector.startFailed
          at org.apache.catalina.core.StandardService.addConnector(StandardService.java:231)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.addPreviouslyRemovedConnectors(TomcatWebServer.java:278)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:197)
  ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar!/:2.2.0.BUILD-SNAPSHOT]
          ... 18 common frames omitted Caused by: org.apache.catalina.LifecycleException: Protocol handler start failed
          at org.apache.catalina.connector.Connector.startInternal(Connector.java:1008)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.catalina.core.StandardService.addConnector(StandardService.java:227)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          ... 20 common frames omitted Caused by: java.lang.IllegalArgumentException: Stream closed
          at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:99)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.AbstractJsseEndpoint.initialiseSsl(AbstractJsseEndpoint.java:71)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:218)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.AbstractEndpoint.bindWithCleanup(AbstractEndpoint.java:1124)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:1210)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:585)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.catalina.connector.Connector.startInternal(Connector.java:1005)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          ... 22 common frames omitted Caused by: java.io.IOException: Stream closed
          at java.base/java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:176)
  ~[na:na]
          at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:342)
  ~[na:na]
          at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
  ~[na:na]
          at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
  ~[na:na]
          at java.base/java.security.DigestInputStream.read(DigestInputStream.java:125)
  ~[na:na]
          at java.base/java.io.DataInputStream.readInt(DataInputStream.java:392)
  ~[na:na]
          at java.base/sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:659)
  ~[na:na]
          at java.base/sun.security.util.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:222)
  ~[na:na]
          at java.base/java.security.KeyStore.load(KeyStore.java:1472) ~[na:na]
          at org.apache.tomcat.util.security.KeyStoreUtil.load(KeyStoreUtil.java:69)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.SSLUtilBase.getStore(SSLUtilBase.java:217)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.SSLHostConfigCertificate.getCertificateKeystore(SSLHostConfigCertificate.java:206)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.SSLUtilBase.getKeyManagers(SSLUtilBase.java:283)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.SSLUtilBase.createSSLContext(SSLUtilBase.java:247)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:97)
  ~[tomcat-embed-core-9.0.26.jar!/:9.0.26]
          ... 28 common frames omitted

A: Thanks Pedro. I have the issue with Spring Boot 2.1.9.RELEASE and can confirm that it is resolved by downgrading to 2.1.8.

A: It is a regression introduced in Tomcat 9.0.25 that will be fixed in 9.0.27.

A: 2.1.10.RELEASE also corrects the problem seen in 2.1.9.

A:   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

Spring boot version 2.1.4.RELEASE and Java 11 combinations solved the issue for me.


text:
Q: C# - EventHandler is always null I am trying to implement a very basic EventHandler between a UserControl and a Form. What am I doing wrong with regards to subscribing to the event? No matter what I try, the CreateButtonEvent is always null. I was originally trying to do this between two UserControl classes but decided to use a Form as the subscriber on the assumption that the UserControl subscription may have been the issue. I have also tried using delegates, with no success.
I have viewed and implemented countless solutions to this exact same questions on this site and I still cannot get the Form class to subscribe to the Event within the UserControl class. I am sure it is a very simple mistake that I just cannot pick out. Can anyone give me some insight?
Here is the UserControl class
using System;
using System.Windows.Forms;

namespace SequenceAutomation
{
    public partial class LoginUserControl : UserControl
    {
        public event EventHandler CreateButtonEvent;

        public LoginUserControl()
        {
            InitializeComponent();
        }

        protected void gotoCreate(object sender, EventArgs e)
        {
            if (CreateButtonEvent != null)
                CreateButtonEvent(this, e);
            else
                Console.WriteLine("CreateButtonEvent is null");
        }
    }
}

Here is the Form class
using System;
using System.Windows.Forms;

namespace SequenceAutomation
{
    public partial class ApplicationContainer : Form
    {
        private LoginUserControl login = new LoginUserControl();
        private CreateRecUserControl createRec = new CreateRecUserControl();

        public ApplicationContainer()
        {
            InitializeComponent();
            login.CreateButtonEvent += gotoCreate;
        }

        protected void gotoCreate(object sender, EventArgs e)
        {
            login.Hide();
            createRec.Show();
        }
    }
}

A: Your problem is here:
    private LoginUserControl login = new LoginUserControl();
    private CreateRecUserControl createRec = new CreateRecUserControl();

    public ApplicationContainer()
    {
        InitializeComponent();
        login.CreateButtonEvent += gotoCreate;
    }

You are creating a LoginUserControl as a variable in your form and subscribing to it, but you haven't added it to your form anywhere. As in, there is no place where you have Children.Add(login).
I'm guessing you have another copy of the LoginUserControl on your form that you placed in the designer, and that's the one that you're interacting with when you run your application. The event is always empty because you've subscribed to that event on a different user control.
Go to the designer, click the user control, go to properties (F4), click the events button, locate the CreateButtonEvent and add your gotoCreate method.
Then remove the member variable login that you've created, because that will just be confusing.
Also, same with CreateRecUserControl. If it's not added in the designer, add it in your designer and remove your member variable createRec.

A: I tested your code exactly and it was OK. I think it could be one of this problems:

*

*1: this code is never run:
     public ApplicationContainer()
 {
     InitializeComponent();
     login.CreateButtonEvent += gotoCreate;
 }

*or 2: you set off the event some where in your code like this:
login.CreateButtonEvent -= gotoCreate;


text:
Q: Load remote script files in background.js This is my extension code
manifest.json
"background": {
  "page": "background.html"
},

background.html
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.12.min.js"></script>
    <script type="text/javascript" src="background.js"></script>
</head>
<body>
</body>
</html>

The problem with this approch is if the network is not connected at the start of chrome, the aws sdk file wont load, leading to failure of events associated with aws till the next chrome restart (extension restart).
I do not want to use unsafe-eval as it is not secure.
Is there a way to check for internet connectivity and reload this js file in background.js
I could alternatively download this script file and store it locally, but this would be my last solution.


text:
Q: Default image is not set I am using window.FileReader to offer an instant preview of the images that the user chooses to upload.
I have created this jsFiddle
I have the following issues:
A) Code in line 63-77 seems to be ignored although when I print the value of "i" in line 25 I can see that is increasing (I am suspecting that it must have something to do with the nature of window.Filereader but not sure).
if (i == 0) //if this is the first picture add it as primary too
{
    var primaryimage = ' <img id=' + filename + '  height="220" width="220" src=' + this.result + ' /> ';

    $('#primary-pic').find('.custom-input-file').hide();
    $('#primary-pic').find('p').hide();
    $('#primary-pic').append(primaryimage);
    $('.custom-input-file').show();
}

B) If you add more than one image and press "Set as default" for some reason this doesn't seem to work for the last image but no idea why .
Thanks

A: There were numerous thing wrong with your code.
Among them:

*

*Deep nesting of one very long function, which was hard to read and debug.

*Variable scope: you assumed that i is somehow 'frozen' when you create a handler. In fact, i read within the handler was the same i as in the main function:

In this example, i progresses and the value encountered by the function will be 4.
for (var i = 0; i < 4; i++) {
    var file = input.files[i];
    var reader = new FileReader();
    reader.onloadend = (function (file) {
        return function () {
            if (i == 0) { //actually, i will be 4
            }
        }
    })(file)
}

*

*Some HTML errors.

*The use of inline event handlers. I do not recommend using those.

*The business logic and UI are tightly coupled. I would suggest creating an object that holds the image metadata and state, and let it construct the UI according to its state. It's a more robust architecture.

I have spent some time on fixing some of the issues. You can find my version here.
I hope that you find it useful and learn from it.

A: 1) Those lines will never reach because if(i == 0) then input.files.length == 1 returns true and so whenever it goes to the else section (2 lines above) i is actually bigger than 0.
2) I think the problem is you're creating multiple elements which share the same id (img and button). Id must be unique.

A: Hey there I believe I see your problem. You are using the onloadend event from the FileReader object in a loop. This is an asynchronous function, that is JavaScript will not wait for this function to execute before moving onto the next iteration of the loop. As such some of your logic depends on the onloadend function having been executed already for the image in question however in your current setup this is unreliable, the i var might be pointing to the next iteration of the loop already however the onloadend function may still be executing for the previous loop and using the wrong i value. This will mess up the rest of your logic as well. As for issue b) I didn't fully dig into this one however I noticed you declared the click event for this inside of the loop, so some of the images had multiple instances of this event attached to them. My advice, wait for ALL your images to load, then inject any extra HTML, then setup any events you require (i.e. the click event). I'll bet issue b) will sort itself out if you do this :)