text:
Q: I keep getting "CodeMirror.foldCode is not a function". Does the code folding addon not work with custom/simple modes? I'm writing a very basic website to help me edit .filter files for Path of Exile. I'm using CodeMirro and have written a custom mode to handle syntax highlighting using the mode/simple.js addon. Now I'm trying to implement code folding based on indentation.
I've looked through the examples and documentation provided on CodeMirror's site.
https://codemirror.net/doc/manual.html#overview
I've searched here on SO and found very few results that were even tangentially related to my problem. I've double checked my work based on the solutions provided by the one close match found here.
CodeMirror foldCode method not working
Yet I'm still getting the error. I've tried looking into whether the addon simply doesn't work with custom/simple modes but it seems the internet is severely lacking in both the quality and quantity of information about CodeMirror.
Any help resolving this issue would be much appreciated. Also, if anyone knows where I could find some quality tutorials that would be amazing.
html:

  <meta charset="utf-8">
  <meta name='viewport' content='width=device-width, initial-scale=1'>

  <title>Filter Editor</title>
  <meta name="description" content="HTML Editor for PoE Filters">
  <meta name="author" content="author">

  <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/styles.css">
  <link rel="stylesheet" href="codemirror/lib/codemirror.css">
  <link rel="stylesheet" href="codemirror/theme/twilight.css">
  <link rel="stylesheet" href="codemirror/addon/fold/foldgutter.css">

Item Text

                    <input id='item-text-input' type='text' placeholder='Item Text' value='Item Text'>

Sounds

1<audio src='audio/AlertSound1.mp3'></audio>

2<audio src='audio/AlertSound2.mp3'></audio>

3<audio src='audio/AlertSound3.mp3'></audio>

4<audio src='audio/AlertSound4.mp3'></audio>

5<audio src='audio/AlertSound5.mp3'></audio>

6<audio src='audio/AlertSound6.mp3'></audio>

7<audio src='audio/AlertSound7.mp3'></audio>

8<audio src='audio/AlertSound8.mp3'></audio>

9<audio src='audio/AlertSound9.mp3'></audio>

10<audio src='audio/AlertSound10.mp3'></audio>

11<audio src='audio/AlertSound11.mp3'></audio>

12<audio src='audio/AlertSound12.mp3'></audio>

13<audio src='audio/AlertSound13.mp3'></audio>

14<audio src='audio/AlertSound14.mp3'></audio>

15<audio src='audio/AlertSound15.mp3'></audio>

16<audio src='audio/AlertSound16.mp3'></audio>

Icons

Sizes

0

1

2

Shapes

Circle

Square

Hexagon

Triangle

Diamond

Star

Colors

Red

Green

Blue

Yellow

Brown

White

            <textarea id='code-mirror'></textarea>

And the JavaScript where I create the CodeMirror instance:
$(document).ready(function() {

    // CodeMirror Stuff
    var code = $("#code-mirror")[0];
    var editor = CodeMirror.fromTextArea(code, {
        mode: "poefilter",
        theme: "twilight",
        lineNumbers: true,
        lineWrapping: true,
        viewportMargin: 30,
        // saveFunction: "saveFunction",
        indentUnit: 4,
        minHeight: "100%",
        extraKeys: {"Ctrl-Q": function(cm){     CodeMirror.foldCode(cm.getCursor()); }},
        foldGutter: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
    });

    editor.foldCode(CodeMirror.Pos(0, 0));
    editor.setSize("100%", "100%");

Here's the mode I wrote (poefilter.js):
var test = {
        block: /(?:Show|Hide)/,
        condition: /(?:ItemLevel|DropLevel|Quality|Rarity|Class|Sockets|LinkedSockets|SocketGroup|Height|Width|AnyEnchantment|StackSize|GemLevel|Identified|Corrupted|ElderItem|ShaperItem|FracturedItem|SynthesisedItem|ShapedMap|BlightedMap|MapTier)/,
        opencond: /BaseType|Prophecy|HasExplicitMod|HasEnchantment|CustomAlertSound/,
        action: /(?:SetBorderColor|SetTextColor|SetBackgroundColor|SetFontSize|PlayAlertSoundPositional|PlayAlertSound|DisableDropSound|MinimapIcon|PlayEffect)/,
        operators: /(?:<|<=|=|>|>=)/,
        number: /[0-9]+/,
        literal: /(?:True|False|Normal|Magic|Rare|Unique|Temp|Red|Green|Blue|Yellow|Brown|White|Triangle|Square|Circle|Diamond|Hexagon|R|G|B)/,
        itemclass: /(?:"Life Flasks"|"Mana Flasks"|"Hybrid Flasks"|"Utility Flasks"|"Critical Utility Flasks"|Flasks|"Stackable Currency"|"Delve Stackable Socketable Currency"|"Socketable Currency"|Currency|Amulets|Rings|Claws|"Rune Dagger"|Daggers|Wands|"One Hand Swords"|"Thrusting One Hand Swords"|"Two Hand Swords"|Swords|"One Hand Axes"|"Two Hand Axes"|Axes|"One Hand Maces"|"Two Hand Maces"|Maces|Bows|Quivers|Staves|Warstaff|"Active Skill Gems"|"Support Skill Gems"|Gems|Belts|Gloves|Boots|"Body Armours"|Body|Helmets|Shields|"Quest Items"|Sceptres|Unarmed|"Fishing Rods"|"Map Fragments"|"Hideout Doodads"|Microtransactions|"Abyss Jewel"|Jewel|"Divination Card"|"Labyrinth Item"|"Labyrinth Trinket"|"Labyrinth Map Item"|Labyrinth|"Misc Map Items"|Leaguestones|"Pantheon Soul"|Piece|"Incursion Item"|Incubator|"Shard Heart"|Shard|Maps|Map)/,
        comment: /#.*/,
        custom: /.*/
    }

CodeMirror.defineSimpleMode("poefilter", {
    // The start state contains the rules that are intially used
    start: [
        // blocks
        {regex: test.comment, token: ["comment"]},
        {regex: test.block, token: "header"},
        {regex: test.condition, token: "attribute"},
        {regex: test.opencond, token: "attribute", next: "custom"},
        {regex: test.action, token: "def"},
        {regex: test.operators, token: "operator"},
        {regex: test.number, token: "number"},
        {regex: test.itemclass, token: "string-2"},
        {regex: test.literal, token: "number"}
    ],
    custom: [
        {regex: test.custom, token: "string", next: "start"}
    ],
    fold: "poefilter"
});

I expect to see little arrows in the gutter that allow me to click on them to fold-open and fold-close the code. Instead, I see no arrows and I get an error in my developer console saying:
scripts.js:19 Uncaught TypeError: CodeMirror.foldcode is not a function

A: Ok, I finally solved this issue.
The last line in the mode file, fold: "poefilter" had a few problems.
First, "poefilter" should have been "indent" since that is the name of the fold type I was trying to apply with the foldcode addon (via indent-fold.js).
Second, since I was using a simple mode, the option needed to be wrapped inside the meta property like so:
meta: {
    fold: "indent"
}

Once I fixed those two issues everything works beautifully.


text:
Q: jQuery slider pagination: Adding callback function I have set up a fiddle here: http://jsfiddle.net/YHMDN/. It's a slider pagination concept and I want it to display text parts instead of numbers, but having numbers maintained displayed in the slider to refer to different text parts (with perhaps a callback function) and having a scrollbar prompted. Who can help me out?
$(function() {

                var $update = $( '#preview > span' );

                $( "#slider" ).pagination( {
                    total : 100,
                    onChange : function( value ) {
                        $update.text( value );
                    }
                } );

            });

The pagination script github page: https://github.com/codrops/SliderPagination/

A: Try this:
$update.text($($('nav').find('a')[value-1]).text());

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I pass php variables to another page without redirecting it to that page? As a part of my college project, I'm building a web-site related to vehicle renting. Now when I click on "rent" button, I want the vehicle_id and user_id to be passed to the "notification" page of the particular user who listed the vehicle for rent on the web-site WITHOUT redirecting it to the notification page.
 <a href = "Waiting.php?vid=<?php echo $vid;?>&uid=<?php echo $uid; ?>" ><input type="button" value="Confirm to rent" name="confirm" >

At "Waiting.php" there is this simple message "Please wait until the owner reponds".
I haven't created the notification page yet, but I want to make sure if I can pass the the $vid and $uid (values of php variables) to the notification page, without actually redirecting to it.

A: you change based your requirement
 <a href="javascript:void(0)" class="btnedit btn btn-default" data-vid="<?php echo $res['sid'];  ?>" data-uid="<?php echo $res['sid'];  ?>" data-toggle="modal" title="View" data-target=".bs-example-modal-lg">


text:
Q: Configuring Jenkins build node: "Wrong password" We've currently got Jenkins running on a Windows virtual machine inside a Mac. I am trying to set up that Mac as a build node. I made a user, "jenkins", on that Mac for this express purpose. However, I can't SSH in to the Mac as that user (or any user) from the virtual Windows box. The Jenkins log says "Failed to authenticate as jenkins. Wrong password." I'm confident I have typed the right password, so this has me stumped.
[07/05/17 12:09:38] [SSH] Opening SSH connection to 192.168.1.2:22.
[07/05/17 12:09:38] [SSH] The SSH key with fingerprint 9c:50:b7:ee:8e:d6:54:55:e1:76:79:1a:7a:d2:16:aa has been automatically trusted for connections to this machine.
ERROR: Failed to authenticate as jenkins. Wrong password. (credentialId:jenkinslogin/method:keyboard-interactive)
[07/05/17 12:09:38] [SSH] Authentication failed.
Authentication failed.
[07/05/17 12:09:38] Launch failed - cleaning up connection
[07/05/17 12:09:38] [SSH] Connection closed.

I tried to SSH in to the Mac from the virtual machine using PuTTY, and I get "Access denied" responses when I try to log in as user "jenkins". What's going on?
Screenshot of Jenkins build node config
Screenshot of user "jenkins" credentials config

A: Mystery solved. I had to go into "System Preferences > Settings" and allow non-administrator accounts to tunnel into the user account. It's still unclear to me why I got "wrong password" as a response instead of, say, "permission denied," but that's life.


text:
Q: HBase Region Start and Stop Keys How HBase decides what should be the start and stop key for a region.
I am actually interested to understand how does scan works in HBase.
If the data is stored across the nodes. How does HBASE perform sorting ?

A: if you don't specify anything, when you create a table. HBase will create a single region that will contains all the keys. As soon the region gets too large, the region will be split in two, and so on.
Each region has the data in it sorted, so the scan will start from the region that contains the first-key and keep going.
take a look at this blog post, that should explain with a bit more details what is going on.
https://blog.cloudera.com/blog/2013/04/how-scaling-really-works-in-apache-hbase/


text:
Q: Generate random numbers with bivariate gamma distribution in R How to generate random numbers with bivariate gamma distribution. The density is:
F(X, Y)(x, y) = αp+qxp-1(y-x)q-1e-αy / [Γ(p) Γ(q)], 𝕀0≤ x≤ y
With y>x>0, α>0, p>0 and q>0.
I did not find any package on R that does this and nothing in literature.

A: This is straightforward:

*

*Generate X~ Gamma(p,alpha)  (alpha being the rate parameter in your formulation)

*Generate W~ Gamma(q,alpha), independent of X

*Calculate Y=X+W

*(X,Y) have the required bivariate distribution.
in R (assuming p,q,alpha and n are already defined):
x <- rgamma(n,p,alpha)
y <- x + rgamma(n,q,alpha)

generates n values from the bivariate distribution with parameters p,q,alpha


text:
Q: Django Twitter clone. How to restrict user from liking a tweet more than once? I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.
models.py
class Howl(models.Model):
    author = models.ForeignKey(User, null=True)
    content = models.CharField(max_length=150)
    published_date = models.DateTimeField(default=timezone.now)
    like_count = models.IntegerField(default=0)
    rehowl_count = models.IntegerField(default=0)

    def get_absolute_url(self):
        return reverse('howl:index')

    def __str__(self):
        return self.content

views.py
class HowlLike(UpdateView):
    model = Howl
    fields = []

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.like_count += 1
        instance.save()

        return redirect('howl:index')

Django Twitter clone. How to restrict user from liking a tweet more than once?

A: As well as tracking how many Likes a post has, you'll probably also want to track who has "Liked" each post.  You can solve both of these problems by creating a joining table Likes with a unique key on User and Howl.
The unique key will prevent any User from doing duplicate likes.
You can do this in Django with a ManyToManyField, note that since this means adding a second User relationship to Howl, we need to disambiguate the relationship by providing a related_name
Eg:
class Howl(models.Model):
    author = models.ForeignKey(User, null=True, related_name='howls_authored')
    liked_by = models.ManyToManyField(User, through='Like')

    # ...rest of class as above

class Like(models.Model):
    user = models.ForeignKey(User)
    howl = models.ForeignKey(Howl)

    class Meta:
      unique_together = (('user', 'howl'))

like_count count then becomes redundant, since you can use Howl.liked_by.count() instead.
The other benefit of this is that it allows you to store information about the Like - eg when it was added.

A: An idea could be adding a column to your table named likers and before incrementing like_counts check if the models.likers contains the new liker or not. If not increment the likes, if yes don't.

A: Changed liked_count in my models.py to
liked_by = models.ManyToManyField(User, related_name="likes")

views.py
class HowlLike(UpdateView):

    model = Howl
    fields = []

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.liked_by.add(self.request.user)

        instance.like_count = instance.liked_by.count()
        instance.save()

        return redirect('howl:index')

index.html
{{howl.liked_by.count}}


text:
Q: Problems building reusable component in SwiftUI I'm trying to use SwiftUI to build a reusable component I previously implemented with @IBDesignable, but it proving to be more difficult than I would have imagined. The problems are a) initializing the text variable and b) clipping the count value. See the code below.
I've tried modifying the value of the text variable both in an initializer and within the body closure, based on changes in the count value, but neither seems to be allowed.
The limiting of the count value and the initialization of the text variable need to happen both from within the view and also when the client of the view modifies the count value. I don't have a clue how to go about making this happen when the count is modified by the client view
    @Binding var count: Int
    @State var text : String = ""
    var maxVal = 5
    var minVal = -5

    var body: some View {
        VStack {
            TextField($text,
                      onEditingChanged: validateString
            )
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            HStack {
                Button(
                    action: { self.add(1) },
                    label: { Text("Plus")}
                )
                Button(
                    action: { self.add(-1) },
                    label: { Text("Minus")}
                )
            }
        }
    }

    func setVal(_ num: Int) {
        count = min(max(num, minVal), maxVal)
        if text != String(count) { text = String(count) }
    }

    func validateString(_ flag: Bool) {
        if !flag {
            guard let num = Int(text) else { return }
            setVal(num)
        }
    }

    func add(_ increment: Int) {
        setVal(count + increment)
    }

}

If I understood all the internal details of binding and of how SwiftUI rebuilds views, I'm sure I could figure this out. But this is one of the downsides of creating and automatic "it just works" frameworks. I'm very excited about SwiftUI and am hoping to surmount this hurdle in understanding.

A: You left some parts of the code out, specially how you are trying to initialize your view. But this should get you started.
Also note that onEditingChanged won't be called until you leave the textField (or hide the keyboard), so clipping won't happen until then.
Also I noticed you are using an older TextField initializer that has been deprecated already. I updated to its new version.
import SwiftUI

struct ContentView : View {
    @State private var count = 3

    var body: some View {
        MyView(count: $count)
    }
}

struct MyView: View {
    @Binding var count: Int
    @State private var text : String

    var maxVal = 5
    var minVal = -5

    init(count: Binding<Int>) {
        self._count = count
        self._text = State(initialValue: "\(count.value)")
    }

    var body: some View {
        VStack {
            TextField("", text: $text, onEditingChanged: validateString)
                .textFieldStyle(.roundedBorder)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            HStack {
                Button(
                    action: { self.add(1) },
                    label: { Text("Plus")}
                )
                Button(
                    action: { self.add(-1) },
                    label: { Text("Minus")}
                )
            }
        }
    }

    func setVal(_ num: Int) {
        count = min(max(num, minVal), maxVal)
        if text != String(count) { text = String(count) }
    }

    func validateString(_ flag: Bool) {
        if !flag {
            guard let num = Int(text) else { return }
            setVal(num)
        }
    }

    func add(_ increment: Int) {
        setVal(count + increment)
    }

}

A: So, basically you forgot to add a init() for your reusable component. By default, structs are created with their own initializer for the properties that are declared in those structs. But If you want to build a reusable component you need to add a init(). It helped me as I was creating a custom library of reusable SwiftUI components and then using it in my project. So, My public struct in my library had to include a init().


text:
Q: Rails 4 RoutingError: No Route Matches [POST] I'm working through a small exercise while learning Rails 4, but running into a routing error while trying to update an object.  I keep getting an error message:  No route matches [POST] "/movies/1/edit" but can't see where my code is not correct:
my movies_controller.rb
class MoviesController < ApplicationController

  def index
    @movies = Movie.all
  end

  def show
    @movie = Movie.find(params[:id])
  end

  def new
    @movie = Movie.new
  end

  def create
    @movie = Movie.create(movie_params)

    if @movie.save
        redirect_to "/movies/#{@movie.id}", :notice => "Your movie was saved!"
    else
        render "new"
    end
  end

  def edit
    @movie = Movie.find(params[:id])
  end

  def update
    @movie = Movie.find(params[:id])

    if @movie.update_attributes(params[:movie])
        redirect_to "/movies"
    else
        render "edit"
    end
  end

  def destroy

  end

  private

  def movie_params
    params.require(:movie).permit(:name, :genre, :year)
  end
end

Here's my edit.html.erb

Now Editing:

<%= @movie.name %>

<%= form_for @movie.name do |f| %>

<%= f.label :name %>
<%= f.text_field :name %>

<%= f.label :genre %>
<%= f.text_field :genre %>

<%= f.label :year %>
<%= f.number_field :year %>

<%= f.submit "Update" %>

and the routes.rb file:
MovieApp::Application.routes.draw do

  get "movies"             => "movies#index"
  post "movies"            => "movies#create"
  get "movies/new"         => "movies#new"
  get "movies/:id"         => "movies#show"
  get "movies/:id/edit"    => "movies#edit"
  put "movies/:id"         => "movies#update"

end

last, here's the output from running rake routes:
    Prefix Verb URI Pattern                Controller#Action
    movies GET  /movies(.:format)          movies#index
           POST /movies(.:format)          movies#create
movies_new GET  /movies/new(.:format)      movies#new
           GET  /movies/:id(.:format)      movies#show
           GET  /movies/:id/edit(.:format) movies#edit
           PUT  /movies/:id(.:format)      movies#update

A: form_for @movie.name should be form_for @movie. I can't tell what's going on, but I suspect this is somehow giving you a <form action="">.

A: Your error message shows that you are sending a post request to the edit url.

No route matches [POST] "/movies/1/edit"

Whereas in the route you have specified a get request.

get "movies/:id/edit"    => "movies#edit"

I believe that is somehow causing the problem and so you could change the request to post.
post "movies/:id/edit"    => "movies#edit"

A: in index file if you are using
button_to 'Edit', edit_movie_path(movie)

change it to
link_to 'Edit', edit_movie_path(movie)

because button send it as POST but the link will send it as GET.


text:
Q: Firewalld rich rules In a DMZ zone i have a CentOS7 server and i am looking to open only 2 flow :

*

*Allow incoming traffic from 192.168.1.10 on port 2222

*Allow outgoing traffic to 192.168.1.20 port 4444

*Block everything else

I look to do it with firewalld rich rules, but i think that there applied only on oncoming traffic (need confirmation). I need help to found the right rule to apply.
Thank you in advance.

A: The RedHat docs have a section on rich rules.
From that it looks like you would need two allow rules, and a drop/reject everything else rule (assuming you're allowing the connections via the tcp protocol, and you will drop everything else, but replace drop with reject if that better matches your use):
firewall-cmd --zone=dmz --add-rich-rule='rule family="ipv4" source address="192.168.1.10" port port="2222" protocol="tcp" accept'
firewall-cmd --zone=dmz --add-rich-rule='rule family="ipv4" destination address="192.168.1.20" port port="4444" protocol="tcp" accept
firewall-cmd --zone=dmz --add-rich-rule='rule family="ipv4" source address="192.168.1.10" invert="true" destination address="192.168.1.20" invert="true" drop'

This will get you most of the way there, it hasn't explicitly blocked the other ports on the two allowed addresses, but it might already be what you're looking for.
The rejection is simplified if the version of firewalld you are running supports the priority attribute, as you could simply add a catch-all drop/reject with a higher priority after the other two rules.
firewall-cmd --zone=dmz --add-rich-rule='priority=999 drop'


text:
Q: Is it possible to generate code for WS operations from eclipse web services explorer? I have successfully tested WS operation from eclipse WS explorer. I have problems with programming all the neccessary parameters for WS operation (lots of non Java types). I created my WS client from wizard.
Is it possbile to generate code that would call the same operation as in WS explorer?
If that can't be done, what is the best way to view outgoing SOAP request so i can better see which parameter is null/missing? I am tunneling my connection to the WS endpoint, so i can't see packets with e.g. Wireshark.

A: You can use SOAPUI to view the soap request and responses. Also you can refer to the section 9.5 of the notes below: -
http://www.slideshare.net/krizsan/scdjws-5-study-notes-3085287

A: You can use TCP/IP monitor of Eclipse to monitor web services.
Check: Using the TCP/IP Monitor to test Web services


text:
Q: How to format current date and hour with Twig? With Twig 3 and twig-intl :

*

*dump(date('now')) return current DateTime object : good ;

*dump(date('now')|format_date('full')) return string date : good ;

*dump(date('now')|format_date('full', 'none')) return empty string "" ; why ?

*dump(date('now')|format_date('full', 'short')) return strange string "118" or "348" or"578"`, ... ; why ?

I don't understand why I can't display the current date and time (full, short).

A: I think you are confusing format_date() and format_datetime() functions.

*

*The format_date() documentation says "It behaves in the exact same way as the format_datetime filter, but without the time."

*The format_datetime() documentation says it allows a second argument none|short|medium|long|full for the time, wich does not exist for the format_date function.

dump(date('now')|format_date('full', 'none')) return empty string "" ;
  why ?

=> Because the second argument is not correct. Possible arguments are types dateFormat, locale and pattern.

dump(date('now')|format_date('full', 'short')) return strange string
  "118" or "348" or"578"`, ... ; why ?

=> For the same reason.

I don't understand why I can't display the current date and time
  (full, short).

=> Use format_datetime() instead :
{{ date('now')|format_datetime('full', 'none') }}
{{ date('now')|format_datetime('full', 'short') }}

I hope it helped.


text:
Q: How to create a wave visualiser from AVPlayerItem? (iOS) I have been using this https://github.com/teodorpatras/Jukebox library to help playing audio from URL but i have encountered a problem trying to create wave visualizer like this https://github.com/ApplikeySolutions/PandoraPlayer but it only allows playing from Music Library. In Pandora Player there is open source wave visualiser https://github.com/ApplikeySolutions/PandoraPlayer/issues/3 but it need to convert to some kind of buffer like this
public func audioPlayer(_ audioPlayer: EZAudioPlayer!, playedAudio buffer: UnsafeMutablePointer<UnsafeMutablePointer<Float>?>!, withBufferSize bufferSize: UInt32, withNumberOfChannels numberOfChannels: UInt32, in audioFile: EZAudioFile!) {

    DispatchQueue.main.async {[weak self] in
        self?.updatePlaybackStatus()
    }
    self.waveVisualizer?.updateWaveWithBuffer(buffer, withBufferSize: bufferSize, withNumberOfChannels: numberOfChannels)
}

A: refer this https://github.com/alankarmisra/SwiftSiriWaveformView this will help you create waveform.
@IBOutlet weak var audioView: SwiftSiriWaveformView!

you could use
audioView.amplitude = 1.0

Installation (CocoaPods):

SwiftSiriWaveformView is available through CocoaPods. To install it,
  simply add the following lines to your Podfile:
For Cocoapods >= 1.0 use_frameworks! target "YOUR_PROJECT_NAME" do
      pod "SwiftSiriWaveformView" end For Cocoapods < 1.0 use_frameworks! pod "SwiftSiriWaveformView"

A: Try to use this pod with Cocoa Pods pod 'SpeechRecognizerButton'
Awesome thing and simply customizing.
Link: https://github.com/alexruperez/SpeechRecognizerButton


text:
Q: Bash: Add elements to array in for loop I have a list of hostnames like:
hostnames = (host1 host2 host3)

Also, I'm trying to resolve these hostnames into IPs:
for host in ${hostnames[@]}; do
    var=`doing some stuff`  # It returns IP address with odd spaces
    ips+=`(echo $var|xargs)`  # Removes odd spaces

It works, but returns in this format:
127.0.0.1127.0.0.2127.0.0.3

I expect to have ips to make it possible to iterate over it and fetch using indexing:
echo ${ips[2]}  # Should return 127.0.0.3

for (( i=0; i<${#ips[@]}; i++ )); do
    echo ${ips[i]}

etc.
How to add these IPs in a correct way to make it possible to iterate through these values and extract them via index?

A: There shouldn't be spaces around the equal sign:
hostnames=(host1 host2 host3)

To add entries to an array you need parentheses outside the backticks:
ips+=(`echo $var|xargs`)

A simpler way to remove spaces is with ${var//pattern/string} substitution. It's faster since it avoids unnecessary child processes.
ips+=("${var// }")


text:
Q: Who was the first African/Black superhero? While reading an article on Marvel's Luke Cage, it mentioned a few other black superheroes, but I didn't see a couple that probably opened the doors to such a thing. I then looked up who I thought was the first African superhero - Lothar (of Mandrake fame) - but apparently he wasn't the first.
Who was the first African/Black superhero (defined here as a protagonist having powers or abilities beyond normal men)?
For this question, let's limit ourselves to modern media - pulp magazines, comics, film/tv, novels, etc. No folklore, mythology, or tribal legends.

A: First black comic-book main character
This honour goes to "Lion Man", who debuted in 1945 as the hero of the groundbreaking one-shot "All Negro Comics #1". While he doesn't have any discernible 'lion powers' he does seem to have exceptional agility, hearing and aggression. He's heroic, but not superheroic.

First (regular) black character in a superheroic comic
This honour goes to Gabriel "Gabe" Jones, debuted in 1963 as one of the Howling Commandoes. Although he doesn't have any obvious superpowers, it's notable that he doesn't age, something that has been commented upon in-universe (with regard to Nick Fury).

First Black title superhero with powers
This would probably be T'Challa, otherwise known as the Black Panther, who debuted in 1966 in Fantastic Four #52.
His powers include...

...superhumanly acute senses and increases his strength, speed, stamina,
  reflexes, and agility to Olympic-levels. He has since lost this
  connection and forged a new one with another unknown Panther deity,
  granting him augmented physical attributes as well as a resistance to
  magic.[61] His senses are so powerful that he can pick up a prey's
  scent and memorize tens of thousands of individual ones. Following his
  war with Doom, T'Challa loses his enhanced abilities only to once
  again establish a connection with the Panther God.

which leads us to the...
First Superheroic black character
As pointed out by Omegacron in his comment below, the first superheroically powered black character is "Lothar", Mandrake the Magician's sidekick who briefly debuts in the first Mandrake story in 1934. Lothar is described as the "Strongest Man in the World" and on at least one occasion lifts an elephant into the air, a feat that goes well beyond normal human abilities.


text:
Q: opencv with pyqt4 dialog display I'm trying to embed video capture with my dialog box (created in pyqt4). For the same I tired the code below. But it just starts the capturing and does not display anything on the dialog. Please help me know what's missing in the following code.
Here, self.videoFrame is a QLabel under QtGui.
def onRun(self):
        self.playing = True
        capture = cv2.VideoCapture(0)
        data1=np.array([])

        while self.playing:

            _, data = capture.read()
            data1 = cv2.cvtColor(data, cv2.cv.CV_BGR2RGB)
            qImage = QtGui.QImage(data1, data1.shape[2], data1.shape[2],
                QtGui.QImage.Format_RGB888)
            qImage=QtGui.QPixmap.fromImage(qImage)
            self.videoFrame.setPixmap(
            qImage)
            self.videoFrame.setScaledContents(True)
            QtGui.qApp.processEvents()
            cv2.waitKey(5)

        cv2.destroyAllWindows()

A: This works:
from PyQt4 import QtCore,QtGui
import sys
import cv2
import numpy as np

class ImageWidget(QtGui.QWidget):
    def __init__(self,parent=None):
        super(ImageWidget,self).__init__(parent)
        self.image=None

    def setImage(self,image):
        self.image=image
        sz=image.size()
        self.setMinimumSize(sz)
        self.update()

    def paintEvent(self,event):
        qp=QtGui.QPainter()
        qp.begin(self)
        if self.image:
            qp.drawImage(QtCore.QPoint(0,0),self.image)
        qp.end()

class MainWindow(QtGui.QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.videoFrame=ImageWidget()
        self.setCentralWidget(self.videoFrame)
        self.timer=QtCore.QTimer(self)
        self.timer.timeout.connect(self.updateImage)
        self.timer.start(30)
        self.capture = cv2.VideoCapture(0)

    def updateImage(self):
        _, img = self.capture.read()
        #img=cv2.cvtColor(img, cv.CV_BGR2RGB)
        height, width, bpc = img.shape
        bpl = bpc * width
        image = QtGui.QImage(img.data, width, height, bpl, QtGui.QImage.Format_RGB888)
        self.videoFrame.setImage(image)

def main():
    app=QtGui.QApplication(sys.argv)
    w=MainWindow()
    w.show()
    app.exec_()

if __name__=='__main__':
    main()


text:
Q: Add custom ServerMux to a http.Handle I am creating a module which will provide a http.Handler that can be attached to any running server.
My module has a lot of bundled  handlerFuncs for handling internal requests:
func NewHandler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("/one", func(writer http.ResponseWriter, request *http.Request) {
        writer.Write([]byte("one"))
    })
    mux.HandleFunc("/two", func(writer http.ResponseWriter, request *http.Request) {
        writer.Write([]byte("two"))
    })
    return mux
}

This handler can be attached to a custom path:
package main

import (
    "net/http"

    "github.com/someuser/someproject"
)

func main() {
    http.Handle("/path", someproject.NewHandler())
    http.ListenAndServe(":8080", nil)
}

On request invocation to http://localhost:8080/path/one I get 404. What am I doing wrong?


text:
Q: Some examples of errors in ESL? I am reading the book The Elements of Statistical Learning (Hastie et al, chapter 7)  and I am confused about the different kinds of errors mentioned in the book

*

*Test error $$Err_\tau=E(L(y, \hat{f}(X)|\tau))$$

*Expected prediction error $$Err=E(L(y, \hat{f}(X)))=E[Err_\tau]$$

*Training error: $$\bar{err}=\frac{1}{N}\sum_{i=1}^{N}L(y_i,\hat{f}(x_i))$$

*In sample error: $$Err_{in}=\frac{1}{N}\sum_{i=1}^{N}E_{Y^0}[L(Y_i^0,\hat{f}(x_i))]$$

*Extra sample error: $$Err_\tau=E_{X^0,Y^0}(L(Y^0, \hat{f}(X^0)|\tau))$$

Can anyone give some idea to well understand these and some simple examples would be appreciated?


text:
Q: WPF XAML Grid- KeyBinding doesn't seem to work I am trying to add the functionality to allow the user to 'zoom in' on a web page displayed in a ChromiumWebBrowser on the GUI of my WPF application, by using the keyboard.
I have the following function in the code-behind for my XAML:
private void zoomInExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        Console.WriteLine("'zoomInExecuted() called. ");
        browser.ZoomLevel++;
    }

To enable this function to be called, I have added the following <Grid.InputBindings> tags to the <Grid> that I'm using to display the ChromiumWebBrowser:
 <Grid x:Name="grdBrowserHost" MinHeight="900" Height="Auto" MinWidth="1205" Width="Auto" Margin="5,0,0,0" DockPanel.Dock="Bottom" Grid.ColumnSpan="1" >
    <Grid.InputBindings>
        <KeyBinding Key="Add" Command="{Binding Path=zoomInExecuted}"></KeyBinding>
     </Grid.InputBindings>
    ...
</Grid>

As I understand, this should mean that the zoomInExecuted(...) function should be called when the + button is pressed on the keyboard, when the Grid displaying the browser has focus.
But, when I run my application, and click inside the browser to ensure it has focus, if I then press '+' on the keyboard, nothing happens, and I'm not even seeing the debug from my zoomInExecuted() function in the console, so it seems that pressing the '+' key is not actually calling that function. Have I done the KeyBinding correctly? Is there something I'm missing from my code here?
Edit
I have tried using an ICommand, as suggested in the answers:
public ICommand zoomInCommand
    {
        get
        {
            _zoomIn = new DelegateCommand(zoomInExecuted()); //CallZoomIn());
            return zoomIn;
        }
    }

and calling this in the KeyBinding in the XAML:
<KeyBinding Key="Add" Command="{Binding Path=zoomInCommand}"></KeyBinding>

but I'm getting a compile error in the C# which says:

The type or namespace name 'DelegateCommand' could not be found (are you missing a using directive or an assembly reference?)

Do I need to add a particular reference or using statement in order to be able to use this?
Edit
I have also tried adding the <KeyBinding ...> tags to both the <Grid> that's holding the browser object, and the browser itself in the XAML, i.e.
<Grid x:Name="grdBrowserHost" MinHeight="900" Height="Auto" MinWidth="1205" Width="Auto" Margin="5,0,0,0" DockPanel.Dock="Bottom" Grid.ColumnSpan="1" >
    <Grid.InputBindings>
        <KeyBinding Modifiers="Ctrl" Key="Add" Command="{Binding zoomInExecuted}"></KeyBinding>
    </Grid.InputBindings>
    ...
    <cefSharp:ChromiumWebBrowser Name="browser" Height="Auto" Width="Auto" Grid.Row="0" Address="https://web.riviam.com" Margin="25,35,-0.2,0" >
        <cefSharp:ChromiumWebBrowser.InputBindings>
            <KeyBinding Modifiers="Ctrl" Key="Add" Command="{Binding zoomInExecuted}"></KeyBinding>
        </cefSharp:ChromiumWebBrowser.InputBindings>
    </cefSharp:ChromiumWebBrowser>

But the zoomInExecuted(...) function never appears to be called (I never see the debug from this function displayed in the console)- it seems that pressing CTRL+ on the keyboard is never registered by the application...
Is there an EventHandler/ KeyboardListener or something similar that I need to add to the application?

A: You cannot bind to a function, you must use a Command:
<KeyBinding Key="Add" Command="{Binding ZoomInCommand}"></KeyBinding>

public ICommand ZoomInCommand
{
    get
    {
        _zoomIn = new DelegateCommand(CallZoomIn());
        return zoomIn;
    }
}

DelegateCommand is part of Microsoft.Practices.Prism. You can download it here
Most MVVM frameworks include it also.

A: Missing the Icommand to method linking part. Else all is correct. To execute method you need to have property of type ICommand. And then use that property to invoke the method you want. Please see the link. There is relay command created which can be used as generic command in which you can pass your method which you want to execute
Binding Button click to a method

A: You cant bind a function. You need to create an ICommand for the purpose of Binding.
Assuming that you have Implemented MVVM Pattern across the app , a RelayCommand needs to be implemented.


text:
Q: Leaflet markers do not open popup on click (with markerclusterer) I just started using Leaflet and Marker Clusterer to organize the markers.
Problem #1: When an unclustered marker is clicked, no popup appears.
Problem #2: When a cluster is clicked several times, all the markers within that cluster appears, and when one of this marker is clicked, its popup appears! However, after closing the popup by clicking on the map, clicking on any of these clustered markers again do not open any popups!
If I only have 3 unclustered markers, the popup works fine. However, as more markers are added, once a cluster forms, clicking on the marker within any cluster will not cause the popup to open!
Initializing markerclusterer
markers = new L.MarkerClusterGroup();
map.addLayer(markers);

All markers added to markercluster markers
A loop calls on the render function to create the marker and add it to the markerclusterer's array markers. (ignore the backbone.js code)
ListingMarkerView = Backbone.View.extend({
    template: _.template( $('#tpl_ListingMarkerView').html() ),

    render: function() {

        // Create marker
        var content = this.template( this.model.toJSON() );
        var marker = new L.marker(
            [this.model.get('lat'), this.model.get('lng')],
            {content: content});
        marker.bindPopup(content);

        // Add to markerclusterer
        markers.addLayer(marker);
    }
});

Without markerclusterer
If I add the marker directly to map instead of the markerclusterer array markers, the popups work fine, so I guess the problem has something to do with markerclusterer.
Did I do something wrong that resulted in such behavior of the popups? All help appreciated, thanks!


text:
Q: Android Kotlin RecyclerView in Fragment is not working I'm very new in Kotlin and Android programming. I tried to create a Fragment which populates a Recycler view, but somehow I get the following error: E/RecyclerView: No adapter attached; skipping layout
I don't really understand why I get this, since I binded everything. If somebody can explain what I'm doing wrong I would really appreciate it. My code is the following:
My class:
data class Movie(val id:Int, val posterPath:String, val vote:Double, val language:String,val releaseDate:String, val title:String) {}

My fragment:
class MovelistScreen : Fragment(R.layout.fragment_movelist_screen) {

    @ExperimentalStdlibApi
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

// View created, can be accessed
//        val args = arguments ?: throw IllegalArgumentException("Use new instance method")
//        val argValue = args.getString(ARG_NAME)

        val binding = FragmentMovelistScreenBinding.inflate(layoutInflater)
        val lst : List<Movie> = buildList {
            add(Movie(id=1,posterPath="/asdasd",vote=7.3,language="Eng",releaseDate="2017",title="Test1"))
            add(Movie(id=2,posterPath="/asdasd",vote=6.3,language="Hun",releaseDate="2013",title="Test2"))
        }

        val listAdapter = MovieListAdapter()
        binding.itemList.adapter=listAdapter
        listAdapter.submitList(lst)
    }
    companion object {
        private const val ARG_NAME = "test_argument"
        fun newInstance(testArg: String): DetailpageFragment = DetailpageFragment().apply {
            arguments = Bundle().apply { putString(ARG_NAME, testArg) }
        }
    }
}

My adapter
class MovieListAdapter : ListAdapter<Movie, MovieViewHolder>(diffUtil) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
        val layoutInflater: LayoutInflater = LayoutInflater.from(parent.context)
        return MovieViewHolder(MovieItemBinding.inflate(layoutInflater,parent,false))
    }

    override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
        val item:Movie=getItem(position)
        val binding:MovieItemBinding = holder.binding

        binding.movieTitle.text=item.title
        binding.releaseYear.text=item.releaseDate
        binding.language.text=item.language
        binding.ratingtext.text=item.vote.toString()
        binding.movieImage.load("https://i.postimg.cc/VLbN4hkz/the-hobbit-the-desolation-of-smaug.jpg")
    }
}

private val diffUtil : DiffUtil.ItemCallback<Movie> = object : DiffUtil.ItemCallback<Movie>() {
    override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean = oldItem.id == newItem.id
    override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean = oldItem == newItem
}

class MovieViewHolder(val binding: MovieItemBinding):RecyclerView.ViewHolder(binding.root)

fragment_movelist_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/item_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:orientation="vertical"
        android:padding="16dp">
    </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/fragmentmovielist"
        android:name="com.example.ubbassignment2.MovelistScreen"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/fragment_detailpage" />
</FrameLayout>

A: You're creating a new view and binding in onViewCreated and setting adapter to it (that view will be garbage collected) you should inflate your view in onCreateView and set the adapter to that recycler view instead of your temporary one.
Fragment:
override fun onCreateView(...): View {
    val binding = FragmentMovelistScreenBinding.inflate(layoutInflater)
    val lst : List<Movie> = buildList {
        add(Movie(id=1,posterPath="/asdasd",vote=7.3,language="Eng",releaseDate="2017",title="Test1"))
        add(Movie(id=2,posterPath="/asdasd",vote=6.3,language="Hun",releaseDate="2013",title="Test2"))
    }

    val listAdapter = MovieListAdapter()
    binding.itemList.adapter=listAdapter
    listAdapter.submitList(lst)

    return binding.root
}


text:
Q: How may multiple LAN connected users control a single Windows instance (or run multiple Windows instances) simultaneously? I am thinking of something like the combination of Synergy and TeamViewer but where multiple mouse pointers and keyboard inputs can work in parallel.
Does anything exist to achieve this?
Some context: I have a specific software running on a very powerful machine (Windows 8.1). I am hoping to be able to connect one or two lower-powered machines to it, so that multiple users can use the powerful machine remotely (via LAN, no need for non-local networking).


text:
Q: android app crashes unexpectedly every time i run it [This is my MainActivity.java file][1]
package com.example.socialmediaintegration;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
private LoginButton loginButton;
private CircleImageView circleImageView;
private TextView txtName, txtEmail;

private CallbackManager callbackManager;

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

   // private static final String EMAIL = "email";

    loginButton =  findViewById(R.id.login_button);
    circleImageView = findViewById(R.id.profile_pic);
    txtName = findViewById(R.id.profile_name);
    txtEmail = findViewById(R.id.profile_email);

    callbackManager = CallbackManager.Factory.create();
    loginButton.setPermissions(Arrays.asList("email", "public_profile"));
    checkLoginStatus();

    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}

AccessTokenTracker tokenTracker = new AccessTokenTracker() {
    @Override
    protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {

        if (currentAccessToken == null)
        {
            txtName.setText("");
            txtEmail.setText("");
            circleImageView.setImageResource(0);
            Toast.makeText(MainActivity.this, "User Logged out", Toast.LENGTH_LONG).show();
        }
        else {
            loadUserProfile(currentAccessToken);
        }
    }
};

private void loadUserProfile(AccessToken newAccessToken){
    GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
        @Override
        public void onCompleted(JSONObject object, GraphResponse response) {
            try {
                String first_name = object.getString("first_name");
                String last_name = object.getString("last_name");
                String email = object.getString("email");
                String id = object.getString("id");

                String image_url =  "http://graph.facebook.com/"+id+"/picture?type=normal";

                txtEmail.setText(email);
                txtName.setText(first_name + " " + last_name);
                RequestOptions requestOptions = new RequestOptions();
                requestOptions.dontAnimate();

                Glide.with( MainActivity.this).load(image_url).into(circleImageView);

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

        }
    });

    Bundle parameters = new Bundle();
    parameters.putString("fields", "first_name, last_name, email_id");
    request.setParameters(parameters);
    request.executeAsync();
}

private void checkLoginStatus(){

    if (AccessToken.getCurrentAccessToken()!=null)
    {
        loadUserProfile(AccessToken.getCurrentAccessToken());
    }
}

}
This is my error shown in Logcat-->>
2020-10-12 12:01:23.621 19597-19602/com.example.socialmediaintegration I/zygote: Increasing code cache capacity to 256KB
2020-10-12 12:01:27.373 19597-19623/com.example.socialmediaintegration E/GraphResponse: {HttpStatus: 400, errorCode: 100, subErrorCode: 33, errorType: GraphMethodException, errorMessage: Unsupported get request.
Object with ID '980066249173751' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api}
2020-10-12 12:01:32.329 19597-19623/com.example.socialmediaintegration E/GraphResponse: {HttpStatus: 400, errorCode: 100, subErrorCode: -1, errorType: OAuthException, errorMessage: (#100) Tried accessing nonexisting field (email_id) on node type (User)}
2020-10-12 12:01:32.329 19597-19597/com.example.socialmediaintegration D/AndroidRuntime: Shutting down VM
2020-10-12 12:01:32.332 19597-19597/com.example.socialmediaintegration E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.socialmediaintegration, PID: 19597
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
at com.example.socialmediaintegration.MainActivity$3.onCompleted(MainActivity.java:102)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:317)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1398)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6626)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)

A: In this error line
Attempt to invoke virtual method 'java.lang.String
org.json.JSONObject.getString(java.lang.String)' on a null object reference

It's said that your JSONObject instance is null and throw NullPointerException
Before reading data from JSONObject you need first to check if the request is successful or not
Check Handling Errors section
https://developers.facebook.com/docs/android/graph


text:
Q: Rails4 Strong Parameters, how permit associative array? view(haml):
- kind.apanages.each do |apanage|
  = number_field_tag "fact[apanage[#{apanage.id}]]", ''

controller:
1 . Don't use permit:
render :json => params

{"utf8":"✓","fact":{"entity_id":"27","apanage":{"1":"7","2":"13","3":"2","4":"1","6":"20","7":"23","8":"10",}},"commit":"End","action":"facts","controller":"entities"}

2 . Use permit (var 1):
render :json => params.require(:fact).permit(:entity_id, :apanage => [])

{"entity_id":"27"}

3 . Use permit (var 2):
render :json => params.require(:fact).permit(:entity_id, apanage: [:id, :content])

{"entity_id":"27","apanage":{}}

How I can permit array 'apanage'?

A: Try:
params.require(:fact).permit(:entity_id).permit!(:apanage)

Also look at this discussion.


text: Q: Book on measure theory for the layman Though unlikely for such a technical topic, is there a book on measure theory (and/or Lebesgue integration) for the casual learner? I am especially interested in the history: the motivation behind the theory, how it came to be, why mathematicians felt they needed some other tool, and how it was developed. Easy examples that would make a self-learner "tick" would be great.


text:
Q: How do I get the name of an SQLAlchemy object's primary key? I just want to programatically determine the name of an SQLalchemy model's primary key.

A: If class is "User", and there is just 1 primary key, do this*:
User.__mapper__.primary_key._list[0].name

*Moved from the question.

A: If using SQLAlchemy version 0.8 or later, you should use the runtime inspection API.
If the model class is User and the sole primary key is id,
>>> from sqlalchemy.inspection import inspect
>>> inspect(User).primary_key[0].name
'id'

If the model class is User and there are many primary keys,
>>> from sqlalchemy.inspection import inspect
>>> [key.name for key in inspect(User).primary_key]
['id', 'name']

If using SQLAlchemy version less than 0.8, you should use the class_mapper() function instead.
>>> from sqlalchemy.orm import class_mapper
>>> class_mapper(User).primary_key[0].name
'id'

In this case, the inspect() function and the class_mapper() function return the same object, but using inspect() is more future-proof.

A: Assuming the declarative model class is User,
>>> list(User.__table__.primary_key)[0].name
'id'

Or for Membership which has a composite primary key
>>> [pk.name for pk in Membership.__table__.primary_key]
['user_id', 'group_id']


text:
Q: Unknown Error - Array Adapter There is an error occurring in an app of mine when I set an Adapter to a ListView. Upon removing the 60/61 line of code (mainListViewTip/Hour.setAdapter(tip/hourAdapter);), the application runs perfectly, except since the adapter is never set, no data appears in the ListView. The goal is for the values of the EditText fields to become new values in the String to be displayed in a ListView along with previous entries also.
The TipBookActivity code:
public class TipBookActivity extends Activity {
/** Called when the activity is first created. */

TextView textTip,textHour,textWage;
EditText editHour,editTip;
float wage;
int precision = 100;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textTip = (TextView) findViewById(R.id.tvTip);
    textHour = (TextView) findViewById(R.id.tvHour);
    textWage = (TextView) findViewById(R.id.tvWage);
    editTip = (EditText) findViewById(R.id.etTip);
    editHour = (EditText) findViewById(R.id.etHour);
}

public void myClickHandler (View v){
    Button bSubmit = (Button) findViewById(R.id.bSubmit);
    bSubmit.isClickable();
    ListView mainListViewTip = (ListView) findViewById(R.id.mainListViewTip);
    ListView mainListViewHour = (ListView) findViewById(R.id.mainListViewHour);
    switch(v.getId()){
    case R.id.bSubmit:
        if(bSubmit.isPressed()){
            wage = Float.parseFloat(editTip.getText().toString()) / Float.parseFloat(editHour.getText().toString());
            String tip = String.format("$%.2f",wage);
            textWage.setText(String.valueOf(tip) + " an hour");
            textHour.setText(editHour.getText() + " Hour(s)");
            textTip.setText("$" + editTip.getText());
            String[] sTip = new String[] {editTip.getText().toString()};
            String[] sHour = new String[] {editHour.getText().toString()};
            ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
            ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);
            mainListViewTip.setAdapter(tipAdapter);
            mainListViewHour.setAdapter(hourAdapter);
            Toast displayWage = Toast.makeText(this, "$" + editTip.getText() + " over " + editHour.getText() + " hour(s) for a wage of $" + wage + " an hour.", Toast.LENGTH_LONG);
            displayWage.show();
        }
    }
}
public boolean onCreateOptionsMenu(Menu menu){
    super.onCreateOptionsMenu(menu);
    MenuInflater mMain = getMenuInflater();
    mMain.inflate(R.menu.main_menu,menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item){
    ViewFlipper vf = (ViewFlipper) findViewById(R.id.vfMain);
    switch (item.getItemId()){
    case R.id.menuHistory:
         vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
         vf.showNext();
         return true;
    case R.id.menuClear:
        //set up next tutorials
        Toast displayClear = Toast.makeText(this, "Clear History feature coming soon.", Toast.LENGTH_SHORT);
        displayClear.show();
        return true;
    case R.id.menuSettings:
        Toast displaySettings = Toast.makeText(this, "Settings Options coming soon.", Toast.LENGTH_SHORT);
        displaySettings.show();
        return true;
    }
    return false;
}

public void onBackPressed() {
    finish();
    }
}

The main xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/llMain" >

<ViewFlipper
    android:id="@+id/vfMain"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/rletbtv">

            <EditText
                android:id="@+id/etTip"
                android:layout_height="wrap_content"
                android:layout_width="140dp"
                android:hint="Tips"
                android:layout_margin="8dp"
                android:inputType="numberDecimal"
                android:layout_alignParentLeft="true"/>

            <EditText
                    android:id="@+id/etHour"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:hint="Hours"
                android:layout_margin="8dp"
                android:inputType="numberDecimal"
                android:layout_alignParentRight="true"
                android:layout_toRightOf="@id/etTip"/>

            <Button
                android:id="@+id/bSubmit"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:layout_margin="8dp"
                android:ems="10"
                android:text="Submit"
                android:textSize="22sp"
                android:layout_below="@id/etTip"
                android:onClick="myClickHandler"/>

            <TextView
                android:id="@+id/tvTip"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="Tips"
                android:textSize="22sp"
                android:layout_margin="8dp"
                android:layout_below="@id/bSubmit"/>

            <TextView
                android:id="@+id/tvHour"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="Hours"
                android:textSize="22sp"
                android:layout_margin="8dp"
                android:layout_below="@id/bSubmit"
                android:layout_toRightOf="@id/tvTip"/>

            <TextView
                android:id="@+id/tvWage"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="Wage"
                android:textSize="22sp"
                android:layout_margin="8dp"
                android:layout_below="@id/bSubmit"
                android:layout_toRightOf="@id/tvHour"/>

        </RelativeLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <ListView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="50"
            android:id="@+id/mainListViewTip"/>

        <ListView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="50"
            android:id="@+id/mainListViewHour"/>

</LinearLayout>
</ViewFlipper>
</LinearLayout>

The simplerow xml file:
<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" />

The logcat error report:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:353)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
at android.widget.ListView.onMeasure(ListView.java:1109)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

A: The problem is because the layout you are passing to the ArrayAdapter is R.layout.main. This is not the resource you want to pass; you want to pass the layout for each individual list item. The layout you pass must have a TextView with a certain ID in it, and obviously R.layout.main does not have this.
Try substituting R.layout.main in those two lines to be android.R.layout.simple_list_item_1, and removing your custom TextView ID. That should solve the error and allow your list to display properly.
Like so:
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sHour);

If you later want to use a custom layout for the list items, try this tutorial or this one.

A: yes eric is right change this two lines of arrayadapter  as shown below if you have not make layout for row item of listview
 ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
 ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);

by
 ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sTip);
 ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sHour);

A: I think adam want to use his own textview so that he can change the text size and color which is not possible with "android.R.layout.simple_list_item_1". Instead of that we can use adam's "simplerow xml" file. to get this we need to replace 2 lines of the code
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);

to
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.samplerow,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.samplerow,R.id.rowTextView,sHour);

Note: the change is "R.layout.main" to "R.layout.samplerow"


text:
Q: Ignore text marked as No Proofing language I have a word document with some text marked as Review/Language/Do not check spelling or grammar. Why is my code not considering "Proofing"?
Sub SentenceProofing()
    Dim iWords As Integer
    Dim Text As String
    Dim oRange As range

    Set oRange = ActiveDocument.range

    If Not ActiveDocument.Saved Then
        ActiveDocument.Save
    End If

    'Set number of words
    iWords = 15

    With oRange.Find
         .NoProofing = False
         For Each MySent In oRange.Sentences
            If MySent.Words.Count > iWords Then
               ActiveDocument.Comments.Add _
               range:=MySent, Text:="Sentence longer than 15 words"
            End If
         Next
    End With
End Sub

A: Try this instead:
Sub SentenceProofing()

    Const iWords As Long = 15 'use Const for fixed values

    Dim mySent

    With ActiveDocument

        If Not .Saved Then .Save

        For Each mySent In .Range.Sentences
            If Not mySent.NoProofing Then
                If mySent.Words.Count > iWords Then
                   .Comments.Add Range:=mySent, _
                       Text:="Sentence longer than 15 words"
                End If
            End If
        Next

    End With

End Sub


text:
Q: PHP - can't use function chroot I've installed Debian 6.0.6 x86 on a VPC with the least possible software packages and when the installation completes I take a backup of the VPC and put it aside for later use.
I have installed PHP 5 via aptitude install php5 and create a PHP script file with the following content and call it test.php:
    if ( function_exists("chroot") ) {
    echo "Function works !\n";
    } else {
    echo "Function does NOT work !\n";
    }

When I run the script via command line php -f test.php it shows me Function works ! Everything fine so far.
Since the PHP version within the php5 package is pretty old I would like to compile my own version - currently 5.4.13 - so I restore my back-upped VPC image and compile it with the following parameters:
    ./configure
    --with-apxs2=/usr/bin/apxs
    --with-config-file-path=/etc/php
    --with-zlib-dir=/usr/local/zlib
    --with-bz2=/usr/local/bzip2
    --with-openssl=/usr/local/ssl
    --with-curl=/usr/local/curl
    --enable-mbstring
    --enable-intl

Output shows me:
Running system checks
checking for chroot... yes

And the compile, make and make install completes flawlessly.
When I recreate and run the test.php script now I get the message Function does NOT work !.
What is going on here I ask myself, am i running the script the wrong way since the documentation says the following: This function is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Also, this function requires root privileges. or is there something not configured correctly ?
Update:
The reason why i try to get this chroot function to work is because i want to install Symfony2. When i run php composer.phar create-project symfony/framework-standard-edition /var/www/symfony2 from within the /root folder it throws me an error:
PHP Fatal error: require_once(): Failed opening required 'app/autoload.php' (include_path='.:/usr/local/lib/php') in /var/www/symfony2/vendor/sensio/distribution-bundle/Sensio/Bundle/DistributionBundle/Resources/bin/build_bootstrap.php on line 24

However when i install the php5 package via the apt-get manager and run the same composer command it works perfectly.
With the precompiled deb php5 package the script changes the current working directory to /var/www/symfony2 while my compiled php binary doesn't (i think).
Then i figured out my php version doesn't have any chroot function so i thought this could be the culprit.

A: Have you prepared a proper chroot for PHP to chroot into?
Simply setting an arbitrary directory is not enough - you actually need to build the chroot and ensure it includes all necessary libraries, devices and binaries.
Otherwise, basic things like DNS resolution will fail to work and you'll get random errors, hangs or app segfaults. It sounds like you are mistaking the simplicity of open_basedir with that of a chroot.
As a start, this script, once customized, should give you a basis for a chroot.
http://www.fuschlberger.net/programs/ssh-scp-sftp-chroot-jail/make_chroot_jail.sh
Dotdeb already includes pre-compiled binaries for PHP
The Dotdeb repo keeps up-to-date pre-compiled builds of the latest versions of PHP - and would be considerably easier and quicker to implement.
http://www.dotdeb.org/

A: First off, chroot() is NOT the solution to your problem. Please gain a thorough understanding of what chroot() is, and what it does before attempting to use it, or you will make yourself miserable for no good reason.
What you need to do to solve your problem is set the paths PHP looks under for require'd files (the include path).  There is a function for that, or you can set it in php.ini.
Alternatively, run your Symfony setup scripts *from the root directory of the Symfony installation (where you extracted the framework too) which is what you're expected to do...


text:
Q: The source of energy for movement of techtonic plates At about 7th grade we learn that the center of the earth is molten iron, and we learn about the movement of tectonic plates. That movement causes earth quakes, volcanos, mountain formations etc. All that activity expends energy, and it is all caused by the gravitational attraction of earth's mass. A naive understanding would say this will continue forever, but that sounds like perpetual motion. How is the paradox resolved?

A: The initial heat from the formation of Earth is slowly escaping into space. The interior of the Earth heated up by a combination of two mechanisms:

*

*Losing gravitational potential energy from parts that went from a high-energy configuration (cloud of dust) to a low-energy one (clump of matter)

*Decay of radioactive elements

This is ultimately the source of the energy for the movement of the plates. When it cools enough to make the interior solid (what happened e.g. with Mars), the plates will stop moving.
Since the interior of Earth is liquid, its cooling results in chaotic movement of the liquid (convection). The liquid interior of the Earth catches on the tectonic plates by friction and causes them to move.


text:
Q: yum install  not working I tried installing Ambari using the yum install process. But Ambari requires a few dependencies such as opens and postgresql-server.
When I try to install these packages using yum install openssl, I get the error:

No package openssl available. Nothing to do

I tried checking the repository list by:
yum repository all

No repos show up.
I am new at this and need help to setup my yum default repositories from scratch. Any help would be appreciated.
My system is Ubuntu 18.

A: If you are getting openssl error, try installing openssl first on your system and add its path to your env variable.
Then try running yum install

A: In ubuntu you need use apt
apt install openssl


text:
Q: Tomcat 10 Port 8443 (SSL) not working on local/external IP address but working on localhost I have been trying to configure Tomcat 10.0.4 alongside IntelliJ Idea for my Java Web project. However, I am unable to run the project using SSL on port 8443. I have also included the Tomcat Native Library dll in the tomcat bin folder. Under build configuration settings in IntelliJ, I have also included the port number for HTTPS.
Upon building and running the server, https://localhost:8443 works as expected. However, when I try to access the web server using the local ip address (192.168.1.2) or through my external IP address, chrome spits ERR_CONNECTION_REFUSED. Port 80 works perfectly fine through both means.
I have port forwarding enabled for the ports 80, 443 and 8443 (which works considering Port 80 works fine) but 8443 does not work. On Windows 10, I have also allowed inbound and outbound connection to 8443 in firewall settings.
The following is my server.xml
<?xml version="1.0" encoding="UTF-8"?>
<Server port="-1" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
 <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" useAprConnector="true" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
  <GlobalNamingResources>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
                executor="tomcatThreadPool"
               connectionTimeout="20000"
                redirectPort="8443"
                useIPVHosts="true"
                address="0.0.0.0"/>
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" URIEncoding="UTF-8"
               secure="true" SSLEngine="true" scheme="https"  clientAuth="false"
               sslProtocol="TLS">
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
                <Certificate
                        certificateKeyFile="conf/privkey1.pem"
                        certificateFile="conf/cert1.pem"
                        certificateChainFile="conf/chain1.pem"
                type="RSA" />
        </SSLHostConfig>
    </Connector>

    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b"
               resolveHosts="true"/>

      </Host>
    </Engine>
  </Service>
</Server>

Any assistance would be greatly appreciated!
Update (04/24/2021 @ 5:07 PM
The following is log messages upon startup:
NOTE: Picked up JDK_JAVA_OPTIONS:  --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
24-Apr-2021 17:00:26.698 WARNING [main] org.apache.tomcat.util.digester.SetPropertiesRule.begin Match [Server/Listener] failed to set property [useAprConnector] to [true]
24-Apr-2021 17:00:26.811 WARNING [main] org.apache.tomcat.util.digester.SetPropertiesRule.begin Match [Server/Service/Connector] failed to set property [SSLEngine] to [true]
24-Apr-2021 17:00:26.811 WARNING [main] org.apache.tomcat.util.digester.SetPropertiesRule.begin Match [Server/Service/Connector] failed to set property [clientAuth] to [false]
24-Apr-2021 17:00:26.812 WARNING [main] org.apache.tomcat.util.digester.SetPropertiesRule.begin Match [Server/Service/Connector] failed to set property [sslProtocol] to [TLS]
24-Apr-2021 17:00:26.868 WARNING [main] org.apache.tomcat.util.digester.SetPropertiesRule.begin Match [Server/Service/Engine/Host/Valve] failed to set property [resolveHosts] to [true]
24-Apr-2021 17:00:26.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version name:   Apache Tomcat/10.0.4
24-Apr-2021 17:00:26.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Mar 5 2021 11:07:15 UTC
24-Apr-2021 17:00:26.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version number: 10.0.4.0
24-Apr-2021 17:00:26.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Windows 10
24-Apr-2021 17:00:26.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            10.0
24-Apr-2021 17:00:26.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
24-Apr-2021 17:00:26.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             C:\Program Files\Java\jdk-11.0.10
24-Apr-2021 17:00:26.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           11.0.10+8-LTS-162
24-Apr-2021 17:00:26.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
24-Apr-2021 17:00:26.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         C:\Users\MicroTechTon\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat\6454be16-6e63-47f0-9175-b6e43d48845f
24-Apr-2021 17:00:26.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 10.0
24-Apr-2021 17:00:26.873 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.lang=ALL-UNNAMED
24-Apr-2021 17:00:26.873 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.io=ALL-UNNAMED
24-Apr-2021 17:00:26.873 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.util=ALL-UNNAMED
24-Apr-2021 17:00:26.873 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.util.concurrent=ALL-UNNAMED
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=C:\Users\MicroTechTon\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat\6454be16-6e63-47f0-9175-b6e43d48845f\conf\logging.properties
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote=
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.port=1099
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.ssl=false
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.password.file=C:\Users\MicroTechTon\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat\6454be16-6e63-47f0-9175-b6e43d48845f\jmxremote.password
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.access.file=C:\Users\MicroTechTon\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat\6454be16-6e63-47f0-9175-b6e43d48845f\jmxremote.access
24-Apr-2021 17:00:26.874 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.rmi.server.hostname=127.0.0.1
24-Apr-2021 17:00:26.875 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
24-Apr-2021 17:00:26.875 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
24-Apr-2021 17:00:26.875 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dignore.endorsed.dirs=
24-Apr-2021 17:00:26.875 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=C:\Users\MicroTechTon\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat\6454be16-6e63-47f0-9175-b6e43d48845f
24-Apr-2021 17:00:26.875 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 10.0
24-Apr-2021 17:00:26.875 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=C:\Program Files\Apache Software Foundation\Tomcat 10.0\temp
24-Apr-2021 17:00:26.879 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent Loaded Apache Tomcat Native library [1.2.28] using APR version [1.7.0].
24-Apr-2021 17:00:26.880 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true], UDS [true].
24-Apr-2021 17:00:26.884 INFO [main] org.apache.catalina.core.AprLifecycleListener.initializeSSL OpenSSL successfully initialized [OpenSSL 1.1.1k  25 Mar 2021]
24-Apr-2021 17:00:27.200 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-0.0.0.0-80"]
24-Apr-2021 17:00:27.228 INFO [main] org.apache.coyote.http11.AbstractHttp11Protocol.configureUpgradeProtocol The ["https-openssl-apr-8443"] connector has been configured to support negotiation to [h2] via ALPN
24-Apr-2021 17:00:27.228 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["https-openssl-apr-8443"]
24-Apr-2021 17:00:27.339 INFO [main] org.apache.catalina.startup.Catalina.load Server initialization in [783] milliseconds
24-Apr-2021 17:00:27.411 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
24-Apr-2021 17:00:27.411 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet engine: [Apache Tomcat/10.0.4]
24-Apr-2021 17:00:27.428 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-0.0.0.0-80"]
24-Apr-2021 17:00:27.449 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["https-openssl-apr-8443"]
24-Apr-2021 17:00:27.457 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [117] milliseconds
Connected to server


text:
Q: Laravel Spark: Creating a new Settings Tab and Vue Component In Laravel Spark, most settings panels have a corresponding Vue JS component, invoked via a custom tab
<spark-create-tests :user="user" inline-template>
    <div>
    </div>
</spark-create-tests>

I'm creating a new settings panel.  I'd like to follow the patterns used by core laravel code -- but I'm unsure how/where to create my vue component.  From what I've been able to gather, the public facing web application instantiates its components in this file
#File: public/js/app.js
Vue.component('spark-create-team', {
    mixins: [base]
});

This looks like its not human editable -- i.e. it's a file created by some sort of compilation process.  I assume that's webpack, but as a frozen caveman developer, I'm not sure.
Which brings me to my questions -- how do I

*

*Add a new component definition to my laravel spark project

*Recompile my project so that my component is included

Or, alternately, what about the above is incredibly wrongheaded, and I actually need to do this other thing?

A: You can create your own components in /resources/assets/js/components/ (or even in /spark-components if it's easier). It could either be JS files with component definitions (such as home.js) or .vue single file components with HTML, CSS, and JS meshed together (like Example.vue). Either way, you need to register each file in bootstrap.js like so:
require('./home'); // home.js -> <home>

or
Vue.component('example', require('./Example.vue')); // Example.vue -> <example>

Of course, if you include the file in a subdirectory under /components, you'd need to adjust the path. When you execute npm run dev, all JS assets under /resources are typically compiled into just one file -- app.js, but you can control this behavior from within your webpack.min.js file. Laravel Docs should help you with that if needed.

A: Think I tracked this one down myself.  The short version is you can build all your assets with either
npm run dev
npm run production

or, use an npm watch mode with either of the following (the later is a polling version with the usual polling tradeoffs for perf/sure-to-work)
npm run watch
npm run watch-poll

Higher level -- Laravel brands its npm based integrations.  In Laravel 5.3, these integrations where known as Laravel Elixer.  In Laravel 5.4, these integrations are known as Laravel Mix.
The source entry point for Laravel Spark's integration (at least in the 4.0 version) is
#File: resources/assets/js/app.js
require('spark-bootstrap');

require('./components/bootstrap');

var app = new Vue({
    mixins: [require('spark')]
});

The require statements pull in other javascript files (all this is resolved/compiled by web-pack when you use npm run).  For example, the two require statements above pull in
spark/resources/assets/js/spark-bootstrap.js
./resources/assets/js/components/bootstrap.js

each of which, in turn, pulls in a lot of other files.  PHP include/require o-rama -- reinvented for javascript!
Eventually, the require-graph will load the following file
#File: resources/assets/js/spark-components/settings/teams/create-team.js
var base = require('settings/teams/create-team');

Vue.component('spark-create-team', {
    mixins: [base]
});

This is what defines the spark-create-team component.  The base methods get defined in the require('settings/teams/create-team') file.
#File: spark/resources/assets/js/settings/teams/create-team.js
module.exports = {
    /*...*/
}

Given all that, there's no great place to drop your own components without interfering with core laravel spark code.  Unless someone convinces me otherwise in the comments, I'll be dropping mine in the resources/assets/js/app.js file -- if only to have them all in a central place.


text:
Q: How to configure IBM i Netserver share so that a new IFS file has its ccsid attribute set to a specified ccsid different from Netserver ccsid We use IBM i Netserver to provide access (internally within the company) to files on IFS.
Currently The CCSID configuration value at the Netserver server level I currently set to 0 and new IFS files created via Netsver (for example by using Windows Explorer) are having their ccsid attribute set to 1250 by Netserver upon creation.
We started to use UTF-8 encoded files for some application (ccsid 1208).
At the moment we can't simply create such files via Netserver share and use them straight away, because after creation we need to alter the ccsid attribute from 1250 to 1208.
Is it possible to configure IBM i Netserver share so that a new IFS file created on Windows workstation via this share will have it's ccsid attribute set to a specified ccsid (1208 in my case) which is different from the Netserver ccsid (1250 in my case)?
I did some documentation and internet searching. I've found only one note on the following web page,  that suggest that should be possible.
http://www-01.ibm.com/support/docview.wss?uid=nas8N1017350
It says : "... When a file is created through NetServer, the CCSID of the file is the CCSID of the share or, if not provided, the CCSID of the server....".  I am not quite sure what is meant by "CCSID of the share" in that text. I've been unable to find any other reference to that term.
Looking at the Netserver share configuration dialog in System i Navigator I asked my system admins to create a new Netserver share, that had the simple text conversion turned on and the CCSID set to 1208 - I was hoping that the CCSID that is set in the dialog is what was referred to as "CCSID of the share". I created a new IFS file using that new share but unfortunately it was created with CCSID attribute = 1250  - not 1208.

A: The CCSID for created files is the "NetServer CCSID", before a different share CCSID. The NetServer Properties dialog, Advanced tab, shows current settings. The 'Next start' button lets you change the NetServer CCSID. Stopping and restarting the NetServer server puts the new CCSID into effect.
Worse, when a file is copied into a NetServer share that has a share CCSID different from the NetServer CCSID and the extension matches one listed for 'Text conversion' for that share, the created file should have the share CCSID set for it. However, existing lines in the copied file won't necessarily be converted. You can easily end up with one CCSID set for the file while the data is still in the original CCSID.
Overall, a number of issues might show up. A major reason historically is that NetServer PTFs haven't always made it into cume packages, so individual PTFs needed to be located. It's much better in current releases, but ensuring (1) that a current cume package is installed and (2) that any relevant NetServer PTFs have been at least reviewed.
If behavior is not as documented, IBM Support should be contacted.


text:
Q: sqlite query for the best selling album in each genre I am using the basic chinook database, but i can't figure out how to write a SQLite query to create a view called BestSeller for the bestselling album in each genre with sales (based on the quantity of tracks sold, named as Sales) with the columns: Genre, Album, Artist, Sales.
The schema for the album table:
 [Title] NVARCHAR(160)  NOT NULL,
 [ArtistId] INTEGER  NOT NULL,
 FOREIGN KEY ([ArtistId]) REFERENCES "artists" ([ArtistId])

artists table :
[ArtistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)

tracks table schema:
 [TrackId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Name] NVARCHAR(200)  NOT NULL,
    [AlbumId] INTEGER,
    [MediaTypeId] INTEGER  NOT NULL,
    [GenreId] INTEGER,
    [Composer] NVARCHAR(220),
    [Milliseconds] INTEGER  NOT NULL,
    [Bytes] INTEGER,
    [UnitPrice] NUMERIC(10,2)  NOT NULL,
    FOREIGN KEY ([AlbumId]) REFERENCES "albums" ([AlbumId])
                ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY ([GenreId]) REFERENCES "genres" ([GenreId])
                ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY ([MediaTypeId]) REFERENCES "media_types" ([MediaTypeId])
                ON DELETE NO ACTION ON UPDATE NO ACTION

table invoice_items:

    [InvoiceLineId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [InvoiceId] INTEGER  NOT NULL,
    [TrackId] INTEGER  NOT NULL,
    [UnitPrice] NUMERIC(10,2)  NOT NULL,
    [Quantity] INTEGER  NOT NULL,
    FOREIGN KEY ([InvoiceId]) REFERENCES "invoices" ([InvoiceId])
                ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
                ON DELETE NO ACTION ON UPDATE NO ACTION

I have all these other tables as well.
albums          employees       invoices        playlists
artists         genres          media_types     tracks
customers       invoice_items   playlist_track

Any help is appreciated.

A: Join the relevant tables and group by genre and album to get the quantity of tracks sold of each album.
Then use FIRST_VALUE() and MAX() window functions to get the album with the most sales in each genre and the the number of sales:
CREATE VIEW BestSeller AS
SELECT DISTINCT
       g.Name Genre,
       FIRST_VALUE(a.Title) OVER (PARTITION BY g.GenreId ORDER BY COUNT(*) DESC) Album,
       FIRST_VALUE(r.Name) OVER (PARTITION BY g.GenreId ORDER BY COUNT(*) DESC) Artist,
       MAX(COUNT(*)) OVER (PARTITION BY g.GenreId) Sales
FROM genres g
INNER JOIN tracks t ON t.GenreId = g.GenreId
INNER JOIN albums a ON a.AlbumId = t.AlbumId
INNER JOIN artists r ON r.ArtistId = a.ArtistId
INNER JOIN invoice_items i ON i.TrackId = t.TrackId
GROUP BY g.GenreId, a.AlbumId;

See the demo


text:
Q: 960px is the correct width for website? is percentage better? With only percentage the website is responsive? I´m trying to develop my first website. And I´m a bit confuse about some points.
I´m developping the html & css and then I want to do my website responsive.
First, I did some research to choose the width for my website, and i found information that the 960px is the best width, So I´m developing my content in 960px! But I have a 17 inch laptop and I have too much white space around the content. Its better do with 1024px for example? Or 960px is better?
And if I do with percentage for example, instead 960px use 70% I´ll resolve the white space, right? This is correct to do?
Second, to my site be responsive I was searching information and I was studying about media queries, but if I use percentage, I dont need to use the media queries, because the site is already responsive, right, or not?
Sorry to bother with this question that may seem simple but I am a beginner and I have this doubt, and maybe with your exprience, you can help me understand better.

A: Using percentage, your site will be fluid. To be responsive, use media queries, so you have a site adapted to the screen size, not forcing the content.
A little about CSS Media Queries: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries


text:
Q: JDBC update query updating all columns, when actually I am updating only few columns I am trying to update only few columns with JDBC.
try (Session session = getSessionFactory().openSession(); Connection connection = SessionUtil.getDBConnection(session)){

    connection.setAutoCommit(false);

    String query = "UPDATE Employee SET fname=?, lname=? where id=?";
    prepareStatement = connection.prepareStatement(query);

    for (Employee employee : employeeList) {
        for(int i=1; i<=3; i++){
            if(i==1){
                prepareStatement.setString(i, employee.getFName());
            }
            else if(i==2){
                prepareStatement.setString(i, employee.getLName());
            }
            else if(i==3){
                prepareStatement.setString(i, employee.getID());
            }
        }
        prepareStatement.addBatch();
    }
    prepareStatement.executeBatch();
    connection.commit();
} catch (Exception e) {
    e.printStackTrace();
}

Here I am trying to update only fname and lname in the table Employee.
But when I check the SQL query generated(from show_sql logs), I can see the update query has all the columns in its set section.
Isn't there a way to limit the no of columns getting updated.
Also since I am updating only 2 columns in the query that I passed to PreparedStatement, shouldn't it do the same instead of trying to update all columns?

A: You have three setString calls with the same i, so you overwrite all the columns with getID(). Just drop the inner for loop and you should be OK:
for (Employee employee : employeeList) {
     prepareStatement.setString(1, employee.getFName());
     prepareStatement.setString(2, employee.getLName());
     prepareStatement.setString(3, employee.getID());
     prepareStatement.addBatch();
}
prepareStatement.executeBatch();