text:
Q: Dancer2 not writing anything to a log file or maybe not reading config file Here's the Dancer2 mini-app:
#!/usr/bin/env perl

use v5.14;

use Dancer2;
use File::Slurper qw(read_text);

set content_type => 'application/json';

my $path;
for my $p ( qw( hitos.json /data/hitos.json ./data/hitos.json ../data/hitos.json) ) {
  if ( -r $p ) {
    $path = $p;
  }
}

my $hitos = from_json read_text($path);

get '/status' => sub {
  return to_json { status => 'OK' };
};

get '/all' => sub {
  return to_json $hitos;
};

start;

with this configuration file:
logger : "File"
engines:
  logger:
    File:
      log_level: core
      log_dir: "/tmp"
      file_name: "p5hitos.log"

I have named it config.yml and config.yaml, and also tried to use the JSON configuration option. I have tried to set the port from it, and it does not "catch" the port setting, so could the problem be the configuration file failing silently? I have also tried to set the configuration on the same file:
set content_type => 'application/json';
set logger => "File";
set port => 31415;
set engines => { logger => { File => { log_level => "core",
                       log_dir => ".",
                       file_name => "p5hitos.log" }}};

In this case, the port and content-type are set correctly, but still no go, either with this log_dir or with /tmp. I have also tried code from this test and copied it verbatim (set logger after set engines and low-case file were the only differences). It does not change. config is still the same:
0  HASH(0x2a3d070)
   'appdir' => '/home/jmerelo/'
   'apphandler' => 'Standalone'
   'behind_proxy' => 0
   'charset' => ''
   'content_type' => 'application/json'
   'engines' => HASH(0x2947a58)
      'logger' => HASH(0x2947008)
         'File' => HASH(0xa438b0)
            'file_name' => 'p5hitos.log'
            'log_dir' => '/tmp'
   'environment' => 'development'
   'host' => '0.0.0.0'
   'logger' => Dancer2::Logger::File=HASH(0x2a7ef58)
      'app_name' => 'main'
      'config' => HASH(0x2a7f1b0)
           empty hash
      'environment' => 'development'
      'file_name' => 'p5hitos.log'
      'location' => '/home/jmerelo/'
      'log_dir' => '/tmp'
      'log_format' => '[%a:%P] %L @%T> %m in %f l. %l'
      'log_level' => 'debug'
   'no_server_tokens' => 0
   'port' => 31415
   'public_dir' => '/home/jmerelo/public'
   'route_handlers' => ARRAY(0x2779490)
      0  ARRAY(0x27791d8)
         0  'AutoPage'
         1  1
   'startup_info' => 1
   'static_handler' => undef
   'template' => 'Tiny'
   'traces' => 0
   'views' => '/home/jmerelo/views'

It starts up and returns the two routes correctly, but the log file is not created and obviously nothing is written on it. There's no error either on the console, and it's not logging to it either. It just shows the startup message: >> Dancer2 v0.204001 server 16427 listening on http://0.0.0.0:3000. The Log file object seems to have been created correctly, but it does not respond. Any idea?

A: app.psgi looks like this:
use v5.14;
use Dancer2;
set content_type => 'application/json';
get '/' => sub {
    debug "Hello World";
    return to_json config;
};
start;

In the same directory config.yml looks like this:
param: Foo
logger : "File"
engines:
  logger:
    File:
      log_level: core
      log_dir: "/tmp"
      file_name: "p5hitos.log"

I launch the application as plackup app.psgi and then access it from another window as curl http://0:5000/ | jq
The log entry is saved in the /tmp/p5hitos.log as expected and in the output on the command line I can see all the configuration values. Both the default ones and the ones I provided.

A: 1. Ensuring the configuration file is read
My only suggestions here are

*

*Ensure that you have the YAML module installed.

*Check the permissions on the configuration file - i.e. that the user running the script has read permissions.

*Check the location and name of the configuration file. It should be one of the the following: a) appdir/config.yml, b) appdir/environments/development.yml, or c) appdir/environments/production.yml (where appdir is where your Dancer application is located). See here for more info.

You also mentioned that you

tried to use the JSON configuration option.

I'm not sure what you mean by this. (The configuration file is written in YAML - not JSON.)
2. Logging configuration
You wrote above that

I have also tried code from this test and copied it verbatim (set logger after set engines and low-case file were the only differences)

I think this might be one of your problems. If you are setting the configuration programmatically (i.e. not in the configuration file), try placing
set logger => 'File';

after
set engines => { ...`

I.e., instead of
set logger => 'File';
set engines => {
    logger => {
        File => {
            log_dir => $log_dir,
            log_level => $log_level,
            file_name => $log_filename,
        }
    }
};

try the following.
set engines => {
    logger => {
        File => {
            log_dir => $log_dir,
            log_level => $log_level,
            file_name => $log_filename,
        }
    }
};
set logger => 'File';

The second approach works for me. The former doesn't.
1 https://metacpan.org/pod/Dancer2::Manual#CONFIGURATION .


text:
Q: Unpacking tuples variadic template arguments I would like to unpack a tuple of variadic types and forward the args to the correct class?
class IntegerField(){
  public:
    IntegerField(int i){}
};
class StringField(){
   public:
      StringField(std::string s){}
};
class Person{
 public:
    IntegerField id(){ return mId; }
    StringField name() { return mName; }
 private:
  IntegerField mId;
  StringField mName;
};

template<typename... Types>
  void createField(Types... args){
     // want to create IntegerField or StringField and pass the args "42" or "Joe" respectively
     // exand the line to something like
     // std::make_unique<IntegerField>(42)
     // ...
     auto uPtr = std::make_unique<Types...>(std::forward<Types...>(args)...);  // # ???
}

int main(){
   using IF = std::tuple<IntegerField, int>;
   using SF = std::tuple<StringField, std::string>;

   Person person;

   createField<IF, SF>({person.id(), 42},{person.name(), "Joe"});
}

A: Based very heavily on @arnes work:
#include <memory>
#include <type_traits>
#include <tuple>
#include <utility> // For std::index_sequence_for

class IntegerField{
  public:
    IntegerField(int i){}
};
class StringField{
   public:
      StringField(std::string s){}
};
class Person{
 public:
    Person() : mId { 5 } , mName { "empty" } {}
    IntegerField id(){ return mId; }
    StringField name() { return mName; }
 private:
    IntegerField mId;
    StringField mName;
};

namespace detail {
    template<class Field, class... Args, std::size_t... Indices>
    auto create(const std::tuple<Field, Args...>& t, std::index_sequence<Indices...> seq) {
        return std::make_unique<Field>(std::get<Indices + 1>(t)...);
    }
}

template<class Field, class... Args>
auto create(const std::tuple<Field, Args...>& t) -> std::enable_if_t<std::is_constructible_v<Field, Args...>, std::unique_ptr<Field>> {
    return detail::create(t, std::index_sequence_for<Args...>{});
}

template<typename... Types>
void createField(Types... args){
    auto res = std::make_tuple( create( std::forward<Types>( args ) )... );
}

int main(){
   using IF = std::tuple<IntegerField, int>;
   using SF = std::tuple<StringField, std::string>;

   Person person;

   createField<IF, SF>({person.id(), 42},{person.name(), "Joe"});
}

godbolt

redpajama_set_name: RedPajamaStackExchange


text:
Q: Make the google's crawler crawl my website correctly If the main functions of my website only can be used after users log in. How can the google's crawler crawl the main functions in my site, then judge the search ranking of my website according to these functions? I have already set up the sitemap including these functions' url, but I thought maybe the crawler will not crawl these functions correctly. Is there any way to rescue the situation without modifying the original authority setting? Or I only can solve this problem by changing the authority setting? Gratefully thanks for the answer.

A: The answer from google's forum:
If the content is behind a login screen, then there's nothing for Google to crawl. Google can't rank these pages in Search because there's no content available to Searchers.
You can't show content to Google but not show content to people who aren't logged in.


text:
Q: Combine multiple .pptx files into one file in R I'd like to combine all powerpoint files into one file using R:
> list.files("/src/dev/export_performance/slides/")
 [1] "slide-1.pptx"  "slide-11.pptx" "slide-12.pptx" "slide-13.pptx" "slide-14.pptx" "slide-15.pptx" "slide-2.pptx"
 [8] "slide-3.pptx"  "slide-4.pptx"  "slide-5.pptx"  "slide-6.pptx"  "slide-7.pptx"  "slide-8.pptx"  "slide-9.pptx"

Is there any tool to do it?


text:
Q: How to add a custom CA-Certificate on an extended (node.js) docker image I'm extending the node-red docker image which (currently) bases itself on the node:6docker image.
I would like to add a custom SSL-Certificate into the docker-image's certificate store. Up to now I did this as follow:
FROM nodered/node-red-docker

ADD DigiCertCA.crt /usr/local/share/ca-certificates/
RUN update-ca-certificates

ADD settings.js /data/settings.js

RUN npm install node-red-contrib-ttn
RUN npm install node-red-contrib-influxdb
RUN npm install node-red-admin
RUN npm install node-red-node-geohash

CMD ["npm", "start", "--", "--userDir", "/data"]

Building this image fails, because the RUN is executed as non-root user node.
Updating certificates in /etc/ssl/certs... ln: failed to create symbolic link '/etc/ssl/certs/DigiCertCA.pem': Permission denied
The command '/bin/sh -c update-ca-certificates' returned a non-zero code: 1

I'm aware that as non-root such an operation is not possible. But what's the valid concept to extend existing images with custom CA-Certificates?

A: Why not just switch user to root to run the command to add the cert then switch back?
FROM nodered/node-red-docker

ADD DigiCertCA.crt /usr/local/share/ca-certificates/
USER root
RUN update-ca-certificates
USER node-red

ADD settings.js /data/settings.js

RUN npm install node-red-contrib-ttn
RUN npm install node-red-contrib-influxdb
RUN npm install node-red-admin
RUN npm install node-red-node-geohash

CMD ["npm", "start", "--", "--userDir", "/data"]

A: This is a complete example with proxy and certificate.
Use npm config set cafile
Dockerfile:
FROM node:10.15.3-jessie

# HTTP Proxy
ARG http_proxy
ARG https_proxy
ENV http_proxy ${http_proxy}
ENV https_proxy ${https_proxy}

# Certicate
ENV CERT_HOME=/usr/local/share/ca-certificates
ENV CERT_FILE_PATH=${CERT_HOME}/my.crt
RUN mkdir -p ${CERT_HOME}
ADD my.crt ${CERT_FILE_PATH}
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*

# npm settings
RUN npm config set cafile ${CERT_FILE_PATH}
RUN npm config set proxy ${http_proxy}
RUN npm config set https-proxy ${https_proxy}

# Check
RUN npm config get proxy
RUN npm config get https-proxy
RUN npm config get registry

And run:
docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --tag mynode .


text:
Q: Correct substitute in "If america wins this match, it/they will win the series" If I consider it as a team that will win the series collectively as a unit  then we should use   "it" rather "they"

A: This is a difference in British and American english. "Team" is a collective noun, that is, a singular noun (team, not teams) that refers to more than one entity (multiple players). In general, in British English you can use either singular verb forms (or it in your example) or plural verb forms (or they in your example) depending on if you are referring to the team or the team members. In American English collective nouns nearly always take the singular form, except for sports teams which, with few exceptions, take the plural.
In American English I would certainly say "If America wins the match, they will win the series" and I believe this would be the most likely usage in British English a well.
See the wiki articles on AmE/BrE differences § Subject-verb agreement and collective noun § Agreement in different forms of English for more information.

A: There's no hard-and-fast rule about which one you should use, but someone focusing either on the team as a unit --or on the country itself-- is more likely to choose "it", and someone focusing on the individual team members would be more likely choose "they".


text:
Q: how to redraw non-visible UICollectionViewCell's after rotation ready for when reuse occurs? How to redraw non-visible UICollectionViewCell's ready for when reuse occurs???
One approach I thought of was per the code in the Layout Cell prepareForReuse function, however whilst it works it non-optimal as it causes more re-drawing then required.
Background: Need to trigger drawRect for cells after an orientation change that are not current visible, but pop up to be used and haven't been redraw, so so far I can only see that prepareForReuse would be appropriate.  Issue is I'm re-drawing all "reuse" cells, whereas I really only want to redraw those that initially pop up that were created during the previous orientation position of the device.
ADDITIONAL INFO: So currently I'm doing this:
In ViewController:
override func viewWillLayoutSubviews() {
    // Clear cached layout attributes (to ensure new positions are calculated)
    (self.cal.collectionViewLayout as! GCCalendarLayout).resetCache()
    self.cal.collectionViewLayout.invalidateLayout()

    // Trigger cells to redraw themselves (to get new widths etc)
    for cell in self.cal?.visibleCells() as! [GCCalendarCell] {
        cell.setNeedsDisplay()
    }

    // Not sure how to "setNeedsDisplay" on non visible cells here?
}

In Layout Cell class:
override func prepareForReuse() {
    super.prepareForReuse()
    // Ensure "drawRect" is called (only way I could see to handle change in orientation
    self.setNeedsDisplay()
    // ISSUE: It does this also for subsequent "prepareForReuse" after all
    // non-visible cells have been re-used and re-drawn, so really
    // not optimal
}

Example of what happens without the code in prepareForReuse above.  Snapshot taken after an orientation change, and just after scrolling up a little bit:

A: I think I have it now here:
import UIKit

@IBDesignable class GCCalendarCell: UICollectionViewCell {
    var prevBounds : CGRect?

    override func layoutSubviews() {
        if let prevBounds = prevBounds {
            if !( (prevBounds.width == bounds.width) && (prevBounds.height == bounds.height) ) {
                self.setNeedsDisplay()
            }
        }
    }

    override func drawRect(rect: CGRect) {
        // Do Stuff
        self.prevBounds = self.bounds
    }

}

Noted this check didn't work in "prepareForReuse" as at this time the cell had not had the rotation applied.  Seems to work in "layoutSubviews" however.

A: You can implement some kind of communication between the cells and the view controller holding the collection view ( protocol and delegate or passed block or even direct reference to the VC ). Then You can ask the view controller for rotation changes.
Its a bit messy, but if You have some kind of rotation tracking in Your view controller You can filter the setNeedsDisplay with a simple if statement.

A: I had similar challenged updating cells that were already displayed and off the screen. While cycling through ALLL cells may not be possible -  refreshing / looping through non-visible ones is.
IF this is your use case - then read on. Pre - Warning - if you're adding this sort of code - explain why you're doing it. It's kind of anti pattern - but can help fix that bug and help ship your app albeit adding needless complexity. Don't use this in multiple spots in app.
Any collectionviewcell that's de-initialized (off the screen and being recylced) should be unsubscribed automatically.
Notification Pattern
let kUpdateButtonBarCell = NSNotification.Name("kUpdateButtonBarCell")

class Notificator {
     static func fireNotification(notificationName: NSNotification.Name) {
          NotificationCenter.default.post(name: notificationName, object: nil)
     }
}

extension UICollectionViewCell{
    func listenForBackgroundChanges(){
         NotificationCenter.default.removeObserver(self, name: kUpdateButtonBarCell, object: nil)
        NotificationCenter.default.addObserver(forName:kUpdateButtonBarCell, object: nil, queue: OperationQueue.main, using: { (note) in

            print( " contentView: ",self.contentView)

        })
    }
}

override func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
    let cell =  collectionView.dequeueReusableCellWithReuseIdentifier("die", forIndexPath: indexPath) as UICollectionViewCell
    cell.listenForBackgroundChanges()
    return cell
}

 // Where appropriate broadcast notification to hook into all cells past and present
 Notificator.fireNotification(notificationName: kUpdateButtonBarCell)

Delegate Pattern
It's possible to simplify this.... an exercise for the reader. just do not retain the cells (use a weak link) - otherwise you'll have memory leaks.


text:
Q: Implementing a simple version of Prolog findall without using the built-in findall I am trying to implement a simple version of findall in Prolog without using the built-in findall or similar built-in predicates -- just as a learning exercise.
For example, suppose there is a relation a/1 in my database,
a(1).
a(11).
a(13).

and I want a relation like find_the_as(List) to give me List = [1,11,13].
I can do this with a "fail" based loop using assert and retract, but I am thinking there must be a recursive way to do this using an accumulator (and I am just not seeing it).
Thanks in advance!
for example:
a(1).
a(11).
a(13).
%
% collect all the N such that a(N)
% into a List
%
collect_n_such_that_a_of_n(List) :-
   retractall(the_n_such_that_a_of_n(_)),
   assert(the_n_such_that_a_of_n([])),
   (
      a(N),
      the_n_such_that_a_of_n(As),
      retractall(the_n_such_that_a_of_n(_)),
      assert(the_n_such_that_a_of_n([N|As])),
      fail
   ) ; true,
   the_n_such_that_a_of_n(List).

A: Using this example:
a(1).
a(11).
a(13).

find(Input,Input) :- \+ (a(X), \+ memberchk(X,Input)).
find(Input,Output) :- a(X), \+ memberchk(X,Input), !, find([X|Input],Output).

find_the_as(List) :- find([], List).

then the query:
find_the_as(List).

returns:
List = [13, 11, 1]

The example uses:

*

*memberchk/2 - True if the first argument is a member of the list represented by the second argument.

*\+/1 - True if the goal represented by its argument cannot be proven.

Unlike with findall, the resulting list does not contain duplicates. eg. if you add an extra a(11) then the resulting list will still only contain one 11.
Unlike with findall, the elements in the resulting list are in reverse order to which they were found (i.e. [13, 11, 1] rather than [1, 11, 13]).

A: Using call_nth/2 (beware of procedures which have side effects):
findall_recursive(Template, Goal, Bag):-
  findall_recursive(Template, Goal, Bag, 1).

findall_recursive(Template, Goal, Bag, N) :-
    copy_term(Goal-Template, CGoal-CTemplate),
    (   call_nth(CGoal, N)
    ->  succ(N, N1),
        Bag=[CTemplate|Bag1],
        findall_recursive(Template, Goal, Bag1, N1)
    ;   Bag=[]
    ).

Sample run having these facts:
a(1).
a(11).
a(13).
a(11).

?- findall_recursive(X, a(X), Bag).
Bag = [1, 11, 13, 11].


text:
Q: "A JNI error has occurred" exception when running .jar file I'm running a java application by this command :
java -cp < FileName> < package name>
however, it shows
A JNI error has occurred...
Exception ... NoClassDefFoundError: ...
this result is right below

I've surveyed the post
Adding external library to artifact jar in IntelliJ IDEA
but still not sure how to solve it.
Here is my Project Structure page, but have no clue to extract the dependencies into the artifact.

What should I do to fix this?

A: Done.
I've created a .jar before, and I kept that setting.
After delete & re-add a new .jar file with "extract to the target JAR" option chosen, the .jar file produced could work. Thanks!


text:
Q: Get specific values from controller function I started learning Laravel and I am trying to achieve the following:
Get data from database and display specific field.
Here is my code in the controller:
public function show()
{
    $students = DB::select('select * from students', [1]);
    return $students;
}

Here is my route code:
Route::get('', "StudentController@show");

That all works for me and I get the following displayed:
[{"id":1,"firstname":"StudentFirstName","lastname":"StudentLastName"}]

How can I get only the "lastname" field displayed?
Thanks in advance!

A: $students[0]['lastname'] will return the last name field, the [0] will get the first student in the array.
I would recommend creating a model for Students, which would make your controller something like this:
$student = Students::first(); // to get first student
$student->lastname; // get last names

A: DB::select('select * from students')

is a raw query that returns an array of stdClass objects, meaning you have  to loop through the array and access properties:
$students[0]->lastname

You can also use the query builder to return a collection of objects:
$collection = DB::table('students')->get();
$student = $collection->first();
$student->lastname;

Lastly, using the query builder, you can use pluck or value to get just the last name.  If you only have one user, you can use value to just get the first value of a field:
DB::table('students')->where('id', 1)->value('lastname');

I strongly advise you to read the Database section of the Laravel docs.

A: If you only want the one column returned, you can use pluck()
public function show()
{
    $last_names= DB::table('students')->pluck('lastname');
    return $last_names;
}

This will return an array of all the students' lastname values.
If you want just one, you can access it with $last_names[0]
As a side note, your show() method usually takes a parameter to identify which student you want to show. This would most likely be the student's id.

A: There are several ways you can accomplish this task. Firstly, I advise you to use the model of your table (probably Students, in your case).
Thus, for example,to view this in the controller itself, you can do something like this using dd helper:
$student = Students::find(1);
dd($student->lastname);

or, using pluck method
$students = Students::all()->pluck('lastname');
foreach($students as $lastName) {
  echo $lastName;
}

or, using selects
$students = DB::table('students')->select('lastname');
dd($students);

Anyway, what I want to say is that there are several ways of doing this, you just need to clarify if you want to debug the controller, display on the blade...
I hope this helps, regards!


text:
Q: Backup: How to mirror/clone LVM LVs (or VGs) on demand? So far, I have a semi-automated backup approach for the whole system installed in different LVs, using LVM (CoW) snapshots (which can be created upon boot to avoid data corruption).  That is, if I feel like I need to create a backup, I will run a script to mount those snapshot LVs (in the same way the live system is mounted) to some location in read-only mode and then run another script to perform a compressed backup of that location, what finally produces a compressed backup of the whole system as a single archive file.  Neat...
Now, I have a new use case for which I'm trying to find a good solution.  Say, I got an external HDD, which purpose is to store stuff.  Well, you know, it is encrypted, also has its own VG and LVs on it, each of which is dedicated for storing different types of data, e.g. pictures, videos, documents, and even those system backup archives.  This gives flexibility of choosing file systems depending on a type of data and all the cool features of LVM.  That is from time to time, I plug in this beast and copy more stuff to either of these LVs depending on what I want to store.  Next, I have yet another external HDD, which I would like (in the ideal world) to act as a mirror of the first external HDD.  Furthermore, ideally that mirroring should happen automagically when both devices are plugged in and I explicitly copy stuff only onto the first one (i.e. something like CoW, maybe we should call it incremental mirroring, though I'm not sure it's possible).  The situations when, for example, the first device is connected and being written, while the second one is not, should also be handled.  That is when the second device is connected next time, it should not only mirror the data that is being written to the first one this time, but also the one that was missed last time.  I guess this is why I refer to mirroring, which is probably not possible to perform incrementally in such situations and a complete clone overwrite is required.
Up until now, I considered the following solutions:

*

*LVM snapshots seem useless here:

*

*they are CoW, i.e. they don't actually maintain a complete mirror on a snapshot LV (unless all of that data changes after writing to the first device);

*they would require to span one VG not only over separate and independent PVs but also over separate and, technically speaking, independent physical devices (I don't like such coupling and would like to avoid it).

*sector cloning via dd:

*

*looks solid in terms of producing the exact clone on the second device;

*according to LVM and cloning HDs, is dangerous because LVM configurations are obviously duplicated in this case and, as a result, may result in data corruption if some renaming black magic is not done (I don't want to script that renaming unless we will not find another solution in this thread as it looks fragile to me);

*smells like an overkill to overwrite the whole second device every time I copy a couple of files into one of the LVs on the first device, just to maintain a mirror;

*not really automated as it does not detect what was changed where and copy it transparently just based on the fact that both are plugged in and the first one was written (this is what I call "on demand").

*rsync of files between corresponding LVs of the two devices:

*

*the good thing is that it will synchronize only the changes and will satisfy even the case when we missed to plug the second device once or twice (and that's a big plus);

*looks convoluted;

*requires scripting for simultaneous mounting of corresponding LVs;

*not automated (has to be triggered manually), thus error-prone;

*requires manual recreation of the same partitioning scheme and LVM on the second device based on the first device (yes, this could be automated, but still).

*LVM RAID1?  I have no idea how reliable and/or possible it is to set up with two plug-and-play devices which may or may not be plugged in and/or mounted simultaneously, and, thus, how it will compare to the above options.  Any experiences shared are much appreciated.

*Some other solution, maybe utilizing vgimportclone?

I appreciate any inputs on this and especially already tested/used solutions which either self-designed and customized by you or existing adopted tools to manage this scenario.  The goal is to make it as simple/least error-prone/automated as possible.  Thank you!


text:
Q: Auto start glassfish with RESTless service I've been looking for instructions on how to automatically start my GlassFish server with my RESTful application on top of it.  I have it installed via the NetBeans IDE and I normally control it through NetBeans but I need to transition away from the dev environment to a test environment.  Links to tutorials would be appriciated.

A: Create a WAR or EAR and put it in the autodeploy folder in the domain.
Then it will start every time Glassfish is started.
Additionally under Windows you can use the asadmin create-service facility to create a service (.NET required).

A: How to start a Glassfish instance when the server starts: that's operating system dependent, on Windows it involves registering Glassfish as a service, for Linux you can follow this tutorial.
How to start an application with Glassfish, or how to migrate an application from the instance embedded in Netbeans to a production server: two easy ways

*

*register your production server in Netbeans, in project properties change the Run target to that newly registered server and deploy via right click on the project in the Projects view, option Deploy.

*When you Build a project in Netbeans, a dist subdirectory will be created in the project directory - switch to the Files tab to see it.  That directory will contain the compiled and packaged projet (jar, war or ear depending on the project type).  Point your browser to the administrative interface of the production Glassfish (in most installations http://yourproductionserver:4848 ), select the correct application type in the tree on the left, click Deploy and upload the file from the dist subdirectory.

Personally I prefer option 2 but that may be a matter of taste. Thorbjørn already explained yet another possibility, via the autodeploy folder.  Whichever you choose, the application will start once deployed and will automatically start every time the Glassfish server starts.


text:
Q: Cannot convert physical disk to vhdx (Hyper-V) I have used Hyper-V Manager for more than two years to backup my two-partition external HDD to my computer (~600 GB [BitLocker encrypted] + ~100GB [unencrypted]). Here is a step-by step tutorial, on how to do it. This method was very convenient, since you are saving whole structure with full encryption and saving it to a single, expandable file (if used space is less than 700GB, the backup image will also take less space). Plus, if you want, you can attach it to your PC and use it as a virtual disk.
However, starting about two months ago, I could not copy the physical drive during the same method, always ending up with the following error:
[Window Title]
New Virtual Hard Disk Wizard

[Main Instruction]
The server encountered an error trying to create the virtual hard disk.

[Content]
Failed to convert the virtual disk.

The system failed to convert '\\?\scsi#disk&ven_st<some-ID>'.

[Expanded Information]
Failed to convert the virtual disk.

The system failed to convert '\\?\scsi#disk&ven_st<some-ID>': The request is not supported. (0x80070032).

[^] Hide details  [Close]

I have tried it on another Windows 10 machine - same error.
I have also tried Disk2vhd utility from Microsoft - also getting an "Error snapshotting volumes".
I have no clue, why this happens, since the disk is the same, with the same partitions. But it does not work anymore.
P.S.: if you are using some other method for backing up the whole physical disk/partition, please share! :)

A: Partial answer, for the Disk2vhd utility getting the error of
"Error snapshotting volumes" :
Disabling the Disk2vhd option of "Use Volume Shadow Copy" allows to clone the drive.


text:
Q: Add ArrayList to another ArrayList in java I am having the following java code, in which I am trying to copy the ArrayList to another ArrayList.
ArrayList<String> nodes = new ArrayList<String>();
ArrayList NodeList = new ArrayList();
ArrayList list = new ArrayList();

for (int i = 0; i < PropertyNode.getLength() - 1; i++) {
    Node childNode = PropertyNode.item(i);
    NodeList Children = childNode.getChildNodes();

    if (Children != null) {
        nodes.clear();
        nodes.add("PropertyStart");
        nodes.add(Children.item(3).getTextContent());
        nodes.add(Children.item(7).getTextContent());
        nodes.add(Children.item(9).getTextContent());
        nodes.add(Children.item(11).getTextContent());
        nodes.add(Children.item(13).getTextContent());
        nodes.add("PropertyEnd");
    }
    NodeList.addAll(nodes);
    list.add(NodeList);
}

I want the "list" array to be in this format:
[[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,d,e,f,PropertyEnd],[PropertyStart,......]]

But from the above code, the "list" array output is seen like this:
[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,....PropertyEnd]

I think you might have noticed the difference. I am not able to achieve the result in expected format.

A: Then you need a ArrayList of ArrayLists:
ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();
nodes.add(nodeList);

Note that NodeList has been changed to nodeList. In Java Naming Conventions variables start with a lower case. Classes start with an upper case.

A: Wouldn't it just be a case of:
ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.
This should return you a list in the format you specified.

A: Your Problem
Mainly, you've got 2 major problems:
You are using adding a List of Strings. You want a List containing Lists of Strings.
Note as well that when you invoke this:
NodeList.addAll(nodes);

... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList, which is using Objects and thus adds only the strings inside. Which leads me to the next point.
You seem to be confused between your nodes and NodeList. Your NodeList keeps growing over time, and that's what you add to your list.
So, even if doing things right, if we were to look at the end of each iteration at your nodes, nodeList and list, we'd see:

*

*i = 0
nodes: [PropertyStart,a,b,c,PropertyEnd]
nodeList: [PropertyStart,a,b,c,PropertyEnd]
list: [[PropertyStart,a,b,c,PropertyEnd]]

*i = 1
nodes: [PropertyStart,d,e,f,PropertyEnd]
nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]
list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]

*i = 2
nodes: [PropertyStart,g,h,i,PropertyEnd]
nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]
list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]

*and so on...
Some Other Corrections
Follow the Java Naming Conventions
Don't use variable names starting with uppercase letters. So here, replace NodeList with nodeList).
Learn a Bit More About Types
You say "I want the "list" array [...]". This is confusing for whoever you will be communicating with: It's not an array. It's an implementation of List backed by an array.
There's a difference between a type, an interface, and an implementation.
Use Generics for Stronger Typing in Collections
Use generic types, because static typing really helps with these errors. Also, use interfaces where possible, except if you have a good reason to use the concrete type.
So your code becomes:
List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();

Remove Unnecessary Code
You could do away with the nodeList entirely, and write the following once you've fixed your types:
list.add(nodes);

Use the Right Scope
Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.
Here you could then move List<String> nodes to be declared within the loop (and then forget the nodes.clear() invocation).
A reason not to do this could be performance, as you might want to avoid recreating an ArrayList on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code).
SSCCE
Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example.
Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list). And you confused a lot of people, as I think the output you give us is not what you actually got.

A: The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.

*

*After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))

*After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))
To get you expectations you must replace
NodeList.addAll(nodes);
list.add(NodeList)

by
List childrenList = new ArrayList(nodes);
list.add(childrenList);

PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object

A: Initiate the NodeList inside the for loop and you will get the desired output.
ArrayList<String> nodes = new ArrayList<String>();
 ArrayList list=new ArrayList();

        for(int i=0;i<PropertyNode.getLength()-1;i++){
            ArrayList NodeList=new ArrayList();
            Node childNode =  PropertyNode.item(i);
                NodeList Children = childNode.getChildNodes();

                if(Children!=null){
                    nodes.clear();
                    nodes.add("PropertyStart");
                    nodes.add(Children.item(3).getTextContent());
                    nodes.add(Children.item(7).getTextContent());
                    nodes.add(Children.item(9).getTextContent());
                    nodes.add(Children.item(11).getTextContent());
                    nodes.add(Children.item(13).getTextContent());
                    nodes.add("PropertyEnd");

                }
                NodeList.addAll(nodes);
                list.add(NodeList);
        }

Explanation:
NodeList is an object which remains same throughout the loop so adding same variable to list in a loop will actually add it only once. The loop is only adding its variables in single NodeList array hence you must be seeing
[/*list*/    [  /*NodeList*/   ]   ]

and NodeList contains [prostart, a,b,c,proend,prostart,d,e,f,proend ...]

A: Very first will declare outer Arraylist which will contain another inner Arraylist inside it
ArrayList> CompletesystemStatusArrayList;
ArrayList systemStatusArrayList
CompletesystemStatusArrayList=new ArrayList

systemStatusArrayList=new ArrayList();
    systemStatusArrayList.add("1");
    systemStatusArrayList.add("2");
    systemStatusArrayList.add("3");
    systemStatusArrayList.add("4");
    systemStatusArrayList.add("5");
    systemStatusArrayList.add("6");
    systemStatusArrayList.add("7");
    systemStatusArrayList.add("8");

    CompletesystemStatusArrayList.add(systemStatusArrayList);


text:
Q: I'm trying to use backgroundworker with webBrowser to download images but getting exception. What should i do? using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using mshtml;
using System.Text.RegularExpressions;

namespace Extract_Images
{
    public partial class Form1 : Form
    {
        private string[] linkstoextract;
        private int numberoflinks;
        private int currentLinkNumber = 0;
        private string mainlink;
        private WebClient client;
        private WebBrowser webBrowser1;
        private string htmlCode;
        private bool pagesorimages = false;

        public Form1()
        {
            InitializeComponent();

            webBrowser1 = new WebBrowser();
            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
            label1.Text = "Number of links: ";
            mainlink = "http://www.test.com/";
            numberoflinks = 13;
            backgroundWorker1.RunWorkerAsync();

        }

        private void ProcessNextLink()
        {
            if (currentLinkNumber < numberoflinks)
            {
                currentLinkNumber++;
                string linktonav = mainlink + "index"+currentLinkNumber.ToString() + ".html";
                pagesorimages = false;
                backgroundWorker1.ReportProgress(0,currentLinkNumber);
                webBrowser1.Navigate(linktonav);

            }
        }

        int count = 0;
        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            mshtml.HTMLDocument objHtmlDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
            string pageSource = objHtmlDoc.documentElement.innerHTML;

            List<string> links = new List<string>();

            string[] hrefs = this.webBrowser1.Document.Links.Cast<HtmlElement>()
             .Select(a => a.GetAttribute("href")).Where(h => h.Contains(".jpg")).ToArray();

            foreach(string a in hrefs)
            {
                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(a, @"C:\Images\file" + count + ".jpg");
                }
                count ++;

                pagesorimages = true;
                backgroundWorker1.ReportProgress(0, count);
            }
            //ProcessNextLink();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
                ProcessNextLink();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (pagesorimages == false)
            {
                label1.Text = e.UserState.ToString();
            }
            if (pagesorimages == true)
            {
                label2.Text = e.UserState.ToString();
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }
    }
}

The exception is on the second ReportProgress:
backgroundWorker1.ReportProgress(0, count);

This operation has already had OperationCompleted called on it and further calls are illegal
What i want to do is to report first the current page number in this case it's 1 to label1.
And then to report the number of downloaded images in this page to label2.
Then to move to the next page with the method ProcessNextLink(); and again report the page number it should be 2 and then to report the number of images downloaded in page 2.
But i'm getting this exception already on the first page.
It was working fine without the backgroundworker in the event webBrowser1_DocumentCompleted i called ProcessNextLink(); in the bottom and it was working fine. But with the backgroundworker it's not working.


text:
Q: Jar does not open up (runs fine in Eclipse) So I have run into a problem: I have a little GUI-project I'm doing for fun's sake and it runs fine in Eclipse with no bugs and everything working as it should.
But when I export it to a runnable Jar then it won't work anymore. Basically nothing shows up at all, not even the JFrame.
I tried to make jars from other projects and they run fine so there shouldn't be any problem with my Java(Java JRE 8v40).
Here is the relevant code for you guys (comments are in German, so if there is something unknown, please ask):
My Main-Method
package paket;

import javax.swing.JFrame;

public class PokeMain {
    static int breite = 500;
    static int hoehe = 500;
    static PokeGui fenster;

    public static void main(String[] args) {
        fenster = new PokeGui();
        fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fenster.setResizable(true);
        fenster.setSize(breite, hoehe);
        fenster.setLocationRelativeTo(null);
        PokeGui.fight.requestFocus();//Fokus am Anfang
        fenster.requestFocusInWindow();//Fenster soll fokussierbar sein
        fenster.addKeyListener(new KeyHandler());
        fenster.setVisible(true);
    }

    public static void getFocus() {//sorgt dafuer, dass der Fokus auch nach Buttonklicks wieder im Fenster landen kann
        fenster.requestFocus();
    }
}

My whole GUI-class
package paket;
import java.awt .*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing .*;

public class PokeGui extends JFrame {
    static JPanel gesamtPanel, unteresPanel, aktionPanel, infoPanel, attackenPanel;//Container
    static JButton fight, bag, team, run;//Aktionen waehrend eines Kampfes
    static JButton attacke1, attacke2, attacke3, attacke4;
    BufferedReader br;//zum Lesen/Schreiben von Dateien
    static JProgressBar hpBar1, hpBar2;
    static JTextArea infoAnzeige;//einziges Element im infoPanel
    JLabel hp;
    Font schrift;
    PaintKampf pk;//Objekt der Klasse
    static int hp1 = 20, hp2 = 20;//1 = Spieler, 2 = Gegner

    public PokeGui() {
        super("Pokemon Java");

        Menueleiste ml = new Menueleiste();
        setJMenuBar(ml.actual_menu_bar);

        schrift = new Font("Calibri", Font.BOLD, 19);

        gesamtPanel = new JPanel();
        gesamtPanel.setLayout(new BorderLayout());
        gesamtPanel.setFocusable(true);
        gesamtPanel.setBounds(0, 0, PokeMain.breite, PokeMain.hoehe);
        add(gesamtPanel);

        pk = new PaintKampf();//Objekt der Klasse PaintKampf(JLabel)
        pk.setBounds(0, 0, 300, 300);
        gesamtPanel.add(pk);

        hpBar1 = new JProgressBar(0, hp1);//Meine HP
        hpBar1.setValue(hp1);
        hpBar1.setFont(schrift);
        hpBar1.setString("HP: " + hp1);
        hpBar1.setStringPainted(true);
        hpBar1.setForeground(Color.GREEN);
        hpBar1.setBackground(Color.WHITE);
        //      gesamtPanel.add(hpBar1,BorderLayout.NORTH);

        hpBar2 = new JProgressBar(0, hp2);//Gegner HP
        hpBar2.setValue(hp2);
        hpBar2.setString("HP: " + hp2);
        hpBar2.setStringPainted(true);
        hpBar2.setForeground(Color.GREEN);
        hpBar2.setBackground(Color.WHITE);
        //      gesamtPanel.add(hpBar2,BorderLayout.EAST);

        unteresPanel = new JPanel();//enthaelt Aktionen wahrend eines Kampfes sowie Textanzeige waehrenddessen
        unteresPanel.setLayout(new GridLayout(1, 0));
        gesamtPanel.add(unteresPanel, BorderLayout.SOUTH);

        infoAnzeige = new JTextArea("What should your POKéMON\ndo?");
        infoAnzeige.setLineWrap(false);
        infoAnzeige.setOpaque(false);//durchsichtig
        infoAnzeige.setEditable(false);
        infoAnzeige.setFocusable(false);
        infoAnzeige.setForeground(new Color(30, 60, 240));
        infoAnzeige.setFont(schrift);

        infoPanel = new JPanel();//ganz unten links
        infoPanel.add(infoAnzeige);//fuegt das JTextArea zum Panel hinzu
        infoPanel.setBackground(new Color(240, 255, 255));
        unteresPanel.add(infoPanel);

        aktionPanel = new JPanel();//ganz unten rechts
        aktionPanel.setLayout(new GridLayout(2, 0));
        aktionPanel.setFocusable(true);
        unteresPanel.add(aktionPanel);//fuegt es dem "uebergeordneten" Panel hinzu
        aktionPanel.addKeyListener(new KeyHandler());

        attackenPanel = new JPanel();//ganz unten rechts
        attackenPanel.setLayout(new GridLayout(2, 2));
        attackenPanel.setVisible(false);

        //Initialisierung der Buttons sowie Auslesen der Attackennamen
        try {
            br = new BufferedReader(new FileReader("src/Player_Attacken.txt"));
            attacke1 = new JButton(br.readLine());//liest aus der Datei die jeweilige Zeile aus und geht dann zur naechsten Zeile
            attacke2 = new JButton(br.readLine());
            attacke3 = new JButton(br.readLine());
            attacke4 = new JButton(br.readLine());
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException io) {
        }

        attacke1.setContentAreaFilled(false);//macht alles ausser dem Inhalt unsichtbar
        attacke1.setFont(schrift);
        attackenPanel.add(attacke1);
        attacke1.addKeyListener(new KeyHandler());
        attacke1.addActionListener(new ActionHandler_Kampf());

        attacke2.setContentAreaFilled(false);//macht alles ausser dem Inhalt unsichtbar
        attacke2.setFont(schrift);
        attackenPanel.add(attacke2);
        attacke2.addKeyListener(new KeyHandler());
        attacke2.addActionListener(new ActionHandler_Kampf());

        attacke3.setContentAreaFilled(false);//macht alles ausser dem Inhalt unsichtbar
        attacke3.setFont(schrift);
        attackenPanel.add(attacke3);
        attacke3.addKeyListener(new KeyHandler());
        attacke3.addActionListener(new ActionHandler_Kampf());

        attacke4.setContentAreaFilled(false);//macht alles ausser dem Inhalt unsichtbar
        attacke4.setFont(schrift);
        attackenPanel.add(attacke4);
        attacke4.addKeyListener(new KeyHandler());
        attacke4.addActionListener(new ActionHandler_Kampf());

        fight = new JButton("FIGHT");
        fight.setBorderPainted(false);//macht die Raender unsichtbar
        //      fight.setContentAreaFilled(false);//macht alles ausser dem Inhalt unsichtbar
        fight.setBackground(Color.RED);
        fight.setFont(schrift);
        aktionPanel.add(fight);
        fight.addKeyListener(new KeyHandler());
        fight.addActionListener(new ActionHandler_Kampf());

        bag = new JButton("BAG");
        bag.setFont(schrift);
        bag.setBorderPainted(false);
        bag.setBackground(new Color(218, 165, 32));
        aktionPanel.add(bag);
        bag.addKeyListener(new KeyHandler());
        bag.addActionListener(new ActionHandler_Kampf());

        team = new JButton("POKéMON");
        team.setFont(schrift);
        team.setBorderPainted(false);
        team.setBackground(new Color(50, 205, 50));
        aktionPanel.add(team);
        team.addKeyListener(new KeyHandler());
        team.addActionListener(new ActionHandler_Kampf());

        run = new JButton("RUN");
        run.setFont(schrift);
        run.setBorderPainted(false);
        run.setBackground(new Color(30, 144, 255));
        aktionPanel.add(run);
        run.addKeyListener(new KeyHandler());
        run.addActionListener(new ActionHandler_Kampf());

        //      gesamtPanel.setVisible(false);
    }
}

And here is my paintComponent-Method where I draw the images.
package paket;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JLabel;

public class PaintKampf extends JLabel {
    Image kampf_hintergrund, P1, P2;//Hintergrund
    URL link, linkP1, linkP2;//URL des Bildes

    @Override
    public void paintComponent(Graphics g) {//paint-Methode
        super.paintComponent(g);
        try {
            link = new URL("http://i.imgur.com/pwkzzgv.png");
        }//holt sich das Bild von diesem Link
        catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            kampf_hintergrund = ImageIO.read(link);
        }//setzt das Bild gleich der URL
        catch (IOException e) {
            e.printStackTrace();
        }

        try {
            linkP1 = new URL("http://i.imgur.com/dg5xRUy.png");
        }//holt sich das Bild von diesem Link
        catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            P1 = ImageIO.read(linkP1);
        }//Spieler 1
        catch (IOException e) {
            e.printStackTrace();
        }

        try {
            linkP2 = new URL("http://i.imgur.com/fdZyPbr.png");
        }//holt sich das Bild von diesem Link
        catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            P2 = ImageIO.read(linkP2);
        }//Spieler 2
        catch (IOException e) {
            e.printStackTrace();
        }

        g.drawImage(kampf_hintergrund, 0, 0, null);//zeichnet das Hintergrundbild
        g.drawImage(P1, 0, 200, null);
        g.drawImage(P2, 350, 90, null);
    }
}

I can't post any images yet but as I said, in Eclipse there appears to be no problem with the program itself.


text:
Q: Get duplicates from C# List I have the following List definition:
class ListItem
{
    public int accountNumber { get; set; }
    public Guid locationGuid { get; set; }
    public DateTime createdon { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        List<ListItem> entitiesList = new List<ListItem>();
        // Some code to fill the entitiesList
    }
}

There are duplicates in the accountNumbers of the entitiesList. I want to find the duplicate accountNumbers, do an action on the locationGuids with a createdon date that is not the most recent createdon date of the duplicates. How can I manipulate the list to get only for the duplicates the accountNumber, most recently created locationGuid and the (older) locationGuids?

A: List<ListItem> entitiesList = new List<ListItem>();
//some code to fill the list
var duplicates = entitiesList.OrderByDescending(e => e.createdon)
                    .GroupBy(e => e.accountNumber)
                    .Where(e => e.Count() > 1)
                    .Select(g => new
                    {
                        MostRecent = g.FirstOrDefault(),
                        Others = g.Skip(1).ToList()
                    });

foreach (var item in duplicates)
{
    ListItem mostRecent = item.MostRecent;
    List<ListItem> others = item.Others;
    //do stuff with others
}

A: duplicates = entitiesList.GroupBy(e => e.accountNumber)
                         .Where(g => g.Count() > 1)
                         .Select(g => g.OrderByDescending(x => x.createdon));

A:     List<ListItem> entitiesList = new List<ListItem>();
    var filtered = entitiesList.GroupBy(x => x.accountNumber).Where(g => g.Count() > 1).ToList().OrderByDescending(x => x.createdon);


text:
Q: Initializing a child CCNode onto a parent CCNode I am working with SpriteBuilder and Cocos2d to build a simple game, and I want to display an error message inside an if statement.
My problem is trying to initialize the CCNode I created in SpriteBuilder to show up on-screen.
I tried creating a CCNode layer and just creating all the objects via SpriteBuilder, but wasn't exactly sure how I was supposed to get that to show up on-screen as what I tried did not work correctly. I tried just using [self addChild:errorLayer] in the if statement and it crashed my app with the error message Argument must be non-nil, so I set up a breakpoint and errorLayer is nil, but I'm not sure how to make it non-nil.
I also tried creating a CCNode programmatically, but when the if-statement was run it didn't display anything on-screen. Here is the code I tried:
    CCNode *errorLayer = [[CCNode alloc] init];
    [errorLayer setContentSize:CGSizeMake(50, 100)];
    [errorLayer setColor:[CCColor redColor]];
    [self addChild:errorLayer];

Could anyone give me some tips on getting this to work? Thanks.
MainScene, which is the scene that the above code is called in, is initialized in AppController like this
- (CCScene*) startScene
{
    return [CCBReader loadAsScene:@"MainScene"];
}


text:
Q: Can't telnet to mysql on 3306 from other vps My vps system verion is Ubuntu 16.04.1 x64.
Mysql version is 5.5.48
I have tried various methods to support 3306.
I have updated "etc/my.cnf" file to commented "'skip-networking" and have the "bind-address" to be 0.0.0.0;
and I use "netstat -an | grep 3306" to check the port status, I got the result:
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:35498 127.0.0.1:3306 TIME_WAIT

I had shut down my firewall, when I type "ufw status", I got:
Status: Inactive

But after all the step and reboot my vps, I type "telnet 128.XXX.XXX.27 3306" on other vps, I got:
telnet: connect to address 128.XXX.XXX.27: Operation timed out

But the strange thing is when I type "telnet localhost 3306" on the local vps, it works fine.
So What could be possible problems? I could provide more details you want.
Thanks a lot!

A: I solved it.
It was a problem with the firewall.
Although I turned off the firewall, but the rule of the iptables are still affect all network requests, and use "iptables -L", I found that:
DROP     tcp  --  anywhere             anywhere             tcp dpt:mysql
The beginning is "DROP", and the end is "mysql".
After I removed this line, everything is fine.


text:
Q: Does buying Fulfillment at level 100 just do a hard reset on your game? After about 12 hours of grinding it out, I reached level 100, having bought all other upgrades. I bought Fulfillment, assuming that that would be what unlocks Box Quest 2 and the prestige system. But instead, it just said thanks for playing; and when I reloaded the page, it was at a brand new game. Do I have to start all over from scratch and do something different when I reach level 100 instead?

A: After playing more and reading some other information found on the internet, I believe I found the answer.
Buying Fulfillment does completely end the game, but it's more like "beating the game" than it is like "doing a hard reset". If you want to see all the content that the game has to offer, you need to keep playing after you hit level 100, but there isn't a lot more content to be had. At most you can get to level 101, learn a couple extra recipes, and start a new game with Box Quest 2 instead. But it's not really a prestige system; playing again with Box Quest 2 isn't a different or faster game (other than being able to use your recipe knowledge from before).


text:
Q: How to change row height for pandas export .to_excel() after wrapping texts in DataFrame? I'm wrapping texts in a Pandas DataFrame with this code:
        for column in dataframe:
          if column != '':
            dataframe[column] = dataframe[column].str.wrap(len(column) + 20)

and export the DataFrame to an excel document with .to_excel('filename'). And the result is (LibreOffice on Linux) shown in the image below:

How can I change the row height to get following result:
 ?
I want to also mention that when I remove above code and wrap text manually in LibreOffice - it works. Maybe it's not possible from code side?

A: How can I change the row height of the row with the wrapped text in order to see the entire text in Libre Office Calc as shown  in the image?
The 'problem' you experience is a result of the wrong expectation that the from pandas dataframe with .to_excel() exported .xls file will auto-magically contain beside the content of the cells and the row/column names also the data about the appropriate formatting of the spreadsheet columns/rows (width/height/font size/etc) so that you can see all of the content in the viewed spreadsheet.
Such expectation does not consider beside other things for example the fact that you haven't along with the export of pandas dataframe to excel file neither specified the font size for displaying the cells nor the widths/heights of the columns and rows which are given in pixels. This makes it impossible to infer the optimal row heights and column widths from the available cell data and store this formatting information along with the content.
In other words there can't be any specific, data-depending formatting information stored in the exported file and if the file is loaded in LibreOffice Calc it is displayed using the standard formatting.
The image  shows that after loading the file
you see only the last line of the wrapped text because the used standard row height with the standard font size can display only one line of the string content of the cell.
When I remove above code and wrap text manually in LibreOffice - it works. Maybe it's not possible from code side?
Is it possible on the script side to specify what I achieved by manually change?
If you specify in addition to the spreadsheet cell values also the information about formatting of the rows, columns and cells it is possible to achieve any result you want using Python script code.
Look here (Improving Pandas Excel Output)  for more explanations as these ones provided in the comments in the following code which will accomplish what you want to achieve:
row_number =   5 # row number of the cell as shown in the Calc spreadsheet
row_height = 100 # choose appropriate one to show all wrapped text

# get the writer object in order to be able to specify formatting:
writer = pd.ExcelWriter("wrapping_column.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer, index=False, sheet_name='Cell With Wrapped Text')

# get the sheet of the spreadsheet to work on:
workbook  = writer.book
worksheet = writer.sheets['Cell With Wrapped Text']

# adjust the height of the row:
worksheet.set_row(row_number-1, row_height)

# save the data along with the formatting changes to file:
writer.save()


text:
Q: The min-length of input is not working properly in this code The min-length of input is not working properly in this code. Sometimes it works and sometimes it doesn't. Why is this? I tried to input 3 characters using the 'if' statement of JavaScript, but I want to make an error message appear in the input window of html if I input less than 3 characters. Why doesn't the attribute value of the html input tag work properly?

const numberOfPeople = document.querySelector(".number-of-people");
const previousWord = document.querySelector(".previous-word");
const inputWord = document.querySelector("#input-word");
const submitButton = document.querySelector("#submit-button");

let number = parseInt(prompt("How many people are participating in the game?"));
let word;
let flag = true;
let flag2 = true;

(function() {
    while (flag) {
        flag = false;
        if(number) {
            numberOfPeople.textContent = number;

            const onClickSubmitButton = (e) => {
                e.preventDefault();
                word = inputWord.value;

                if (inputWord.value.length < 3) {
                    alert("Please enter 3 characters.")
                } else if ((previousWord.textContent === "") || (previousWord.textContent[previousWord.textContent.length - 1] === word[0])) {
                    previousWord.textContent = word;
                    inputWord.value = "";
                    inputWord.focus();
                    flag = true;
                } else {
                    alert("GAME_OVER");
                    inputWord.value = "";
                    previousWord.textContent = "";
                    numberOfPeople.textContent = "";
                    number = null;
                    submitButton.removeEventListener("click", onClickSubmitButton);
                    return;
                }
            }

            submitButton.addEventListener("click", onClickSubmitButton);
        } else {
            number = parseInt(prompt("Please enter a number."));
            if (number && flag2) {
                numberOfPeople.textContent = number;
                flag = true;
                flag2 = false;
            }
        }
    }
})()
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>word-chain game</title>

number-of-people :

previous-word :

        <form>
            enter a word
            <input name="input-word" id="input-word" type="text" required minlength="3" maxlength="3" placeholder="Please enter a word.">
            <input id="submit-button" type="submit" value="input"></input>
        </form>

A: You can apply style on input based on the required minlength attribute or you can attach an invalid event handler on input.
input:invalid{
 color:red;
 border-color:red;
}

<input type="text" oninvalid="alert('Please enter atleast 3 charcater in name field');"  required minlength="3">


text:
Q: Android: play custom notification sound, even if phone is muted and/or in DND mode I've created a personal (not public!) application long ago which receives notifications. Now I'm rewriting this application and I'm using notification channels. I already implemented a custom vibration pattern and all the things I need, but one thing is still missing:
The app should bypass DND mode. As far as I came, this works now. But if the phone is silent (STREAM_* levels 0), the sound is not played - but it should. Is there any possibility, to set the Volume for this notification to MAX? And yes, it's not a problem if the notification is received in foreground, but it also should play the sound in the background.
What I've got so far:
My NotificationUtils.java class which creates the Notification channel(s). This is the one that should bypass DND:
SharedPreferences mSharedPreferences = this.getSharedPreferences(Constants.PREFERENCES_NAME, Context.MODE_PRIVATE);
Boolean prefVibration = mSharedPreferences.getBoolean(Constants.PREFERENCES_NOTIFICATION_VIBRATE, false);
Boolean prefSound = mSharedPreferences.getBoolean(Constants.PREFERENCES_NOTIFICATION_WITH_SOUND, false);
String prefSoundfile = mSharedPreferences.getString(Constants.PREFERENCES_NOTIFICATION_SOUNDFILE, "not");

String channelId = getString(R.string.default_notification_channel_id);
NotificationChannel alarmsChannel = new NotificationChannel(channelId, getString(R.string.channel_title_alarms), NotificationManager.IMPORTANCE_HIGH);
        alarmsChannel.enableLights(true);
        alarmsChannel.enableVibration(true);
        alarmsChannel.setLightColor(Color.RED);
        alarmsChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        alarmsChannel.setBypassDnd(true);
        alarmsChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
        alarmsChannel.shouldShowLights();
        alarmsChannel.canBypassDnd();
if (prefVibration) {
        alarmsChannel.setVibrationPattern(mVibratePattern);
        alarmsChannel.shouldVibrate();
}

if (prefSound) {
        Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + this.getPackageName() + "/" + getResId(prefSoundfile, R.raw.class));
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
        alarmsChannel.setSound(soundUri, audioAttributes);
}

getManager().createNotificationChannel(alarmsChannel);

When a user enables the Constants.PREFERENCES_NOTIFICATION_WITH_SOUND preference, he is asked for the correct permissions:
ActivateDndAllowance mDndAllowance = new ActivateDndAllowance(this.getContext());
mDndAllowance.check();

In the notification receiver class, where I use the NotificationCompat.Builder,  I can just use a MediaPlayer instance and AudioManager to set the volumes. But this only works in foreground... or did I miss something?
How is it possible to adjust the volume (just for this notification), even in background?
Thanks a lot!


text:
Q: Sample Appium Framework This might be a big ask.  Can anyone point to the direction of a to a page or a blog with a sample appium framework that (for iOS and android)  I can take a look at?
Any frameworks that use page mode factory or BDD would be perfect.

A: I write AppiumBoot to use yaml to run Appium auto test. It makes using Appium very simple, and no need to write java or python code.
demo video
demo code
some code like
# AppiumBoot/example/material/comp5.yml
# home page: click 5th cell
- click_by:
    xpath: /hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/androidx.recyclerview.widget.RecyclerView/android.widget.FrameLayout[5]/android.widget.LinearLayout # 按钮的xpath路径
  sleep: 1
# second page: click 3th demo
- click_by:
    xpath: /hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.ScrollView/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.RelativeLayout[2]
# thirth page: drag and move
  move_track: '360,1100;360,600;800,600;800,1600;100,1600;100,600'
# back to second page: click 4th demo
- back:
  click_by:
    xpath: /hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.ScrollView/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.RelativeLayout[4]
  swipe_up:

A: Appium sample project link here
Appium with bdd sample project link here
Appium with Grid sample project link here


text:
Q: MacOS different database from phpmyadmin using command line I'm trying to use "mysql" from command line on macos, which works fine. But when i use "show databases" i'm getting only 2 databases, not all the databases that were used with xampp (phpmyadmin).
i add this to the PATH to use mysql :
export PATH="/opt/local/bin:/opt/local/sbin:/Applications/xampp/xamppfiles/bin:$PATH"

And when i'm doing this /Applications/xampp/xamppfiles/bin/mysql -u root -p instead of "mysql" it actually worked fine. (i'm getting all the databases).
Is there any way i can get all the databases that are on phpmyadmin using commandline on mac os if that make sense


text:
Q: Stop XML::Smart from interpreting CDATA I'm trying to parse an xml file that has entries like:
<ANNOTATION_VALUE><unk></ANNOTATION_VALUE>
<TIER LINGUISTIC_TYPE_REF="default-lt" TIER_ID="<Target>"/>

Unfortunately, XML::Smart sees these and thinks they are CDATA tags. When I save the xml data, it turns into this:
<ANNOTATION_VALUE><![CDATA[<unk>]]></ANNOTATION_VALUE>
<TIER LINGUISTIC_TYPE_REF="default-lt">
<TIER_ID><![CDATA[<Target>]]></TIER_ID>
</TIER>

I tried to stop this by setting set_cdata(false) on all the nodes, but it doesn't seem to change anything:
$xml->{TIER}{TIER_ID}->set_cdata(0);
$xml->{ANNOTATION_VALUE}->set_cdata(0);

How can I get XML::Smart to stop reading these as CDATA?


text:
Q: Cannot add or insert the item in more than one place - ListView Error I keep getting an error while attempting to add a range of items into my list view.
Error: "Cannot add or insert the item in more than one place"
Do keep in mind I have column headers.
Here is the example code:
private void OtherFunction()
    {
        // pulls info and had foreach loop
        Add_To_List(Event_Date, Acc_Name, Client_IP, Event_DC, Failure_Code);
    }

    private void Add_To_List(string date, string user, string ip, string domain, string lockedout)
    {
        listView1.ListViewItemSorter = null;

        // Add item to list view.
        ListView.ListViewItemCollection new_row = new ListView.ListViewItemCollection(listView1);
        new_row.Add(date);
        new_row.Add(user);
        new_row.Add(ip);
        new_row.Add(domain);
        new_row.Add(lockedout);
        listView1.Items.AddRange(new_row);

        // Clear data
        new_row.Clear();
    }

This was the code I was using before which worked but it wasn't quite how I wanted it.
string[] new_row = { user, ip, domain, lockedout };
listView1.Items.Add(date).SubItems.AddRange(new_row);

I was looking for an upgrade in speed.

A: I ended up using this:
string[] row = { Event_Date, Acc_Name, Client_IP, Event_DC, Failure_Code };

var NewListViewItem = new ListViewItem(row);
listView1.Items.Add(NewListViewItem);


text:
Q: Ubuntu 18.04 loop at login, and Ctl-Alt-F1 cannot stop it! I upgraded from 16.04 to 17.10 and got a login loop.
But when I started a terminal session, and did some apt update commands, it suggested I upgrade to 18.04.
I did the upgrade, but on 18.04, the same login loop appeared.
As suggested by some thread in another forum, I tried to delete and reinstall lightdm (I now see that lightdm may not even be used in 18.04!)
Now the system is in a login loop that does not appear to be stoppable
A Ctrl-Alt-F1 will bring up my login, but before I have a chance to type in my complete ID, it starts all over again.
Is there some other keyboard command I can use to stop this loop, and get control of the terminal?

A: You can get to the root command prompt by using Ubuntu advance boot option on booting up. Tap the down arrow key during booting if the boot menu doesn't stay up long enough. From the boot menu, select advance boot option, then select the recovery boot option, usually the second one from the top.
In recovery mode you are presented with a few menu choices, select the root shell prompt and from the console you could try to repair your setup by reinstalling gdm3.
apt-get install gdm3

And if it is already installed, try
dpkg-reconfigure gdm3


text:
Q: Socket io and android not connecting I am trying to connect an android app to Socket.io server on MEAN Stack.
I am emitting a test string on socketTesting and listening on the server side.
MainActivity.java
public class MainActivity extends ActionBarActivity {

    TextView tv;
    private Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        try {
            socket = IO.socket("http://"+IP_ADDRESS+":"+PORT_NO);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        socket.connect();
        socket.emit("socketTesting","hiiii");

        setContentView(R.layout.test_xml);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        socket.disconnect();
    }
}

This is the server side code:
 socket.on('socketTesting', function(message) {

                console.log(JSON.stringify(message));

                });

Nothing is displayed on the server side. I know this is a very basic question but i've looked around much without any success. There's no exception thrown and neither does it connect.

A: 1) check the socket.io version matches. Because of socket.io mismatch between server and client i received transport error(spent 2 days to realize).
2) If your socket is listening on port 80, Then open browser and enter http://your-server-ip:80 which will give json reply if the server socket is open for connection.
3) ppl use DEBUG=* node your-file.js to get the current status , It prints out everything .(check google for more info)


text:
Q: possible? Typedef enum in C without members, add members in another file Problem
For a library im writing the user has to define different input values, as in
enum {
    A_VALUE1,
    A_VALUE2
};
enum {
    B_VALUE1,
    B_VALUE2
};

These values can then be used as params for library functions, e.g.:
library_function( context_handle_1, A_VALUE1 );
library_function( context_handle_2, B_VALUE1 );

What i would like to do is:

*

*typedef the enum (more clear, better readability, compiler warnings) but

*have dont want multiple implementations of library_function and therefore just one type for the enum, while

*the library user creates the actual values for the enums and can use

*multiple enums for different library instances.

Tried A
typedef enum my_enum_type;

my_enum_type {
   IDENTIFIER_SET_A
}

my_enum_type {
   IDENTIFIER_SET_B
}

error: must use 'enum' tag to refer to type 'my_type'.

Tried B
Use preprocessor macros to create a unique variable type for each enum:
#define MY_ENUM(name, ...) \
typedef enum name##_enum_type {
    __VA_ARGS__,
    name##_COUNT
};

This will require a separate library function for each name or a type conversion on a function call. The additional name##_COUNT could come in handy, but then i need to know name to access it.

Tried C
Using preprocessor macros to create multiple datatypes, then wrap the function call in a #define to typecast it back, like
#define VALUES(...) typedef enum __FILE__##__LINE__## { __VA_ARGS__ } __FILE__##__LINE__##_t
#define lib_run(func, value) func((my_enum_type)value)

typedef int my_enum_type;

func(my_enum_type value) {
   do_something();
}

I tried using something like __FILE__ or __LINE__ to create an automated name that is both unique and does not need to be given by the user. But the qoutes in __FILE__ kill this approach, as it generates invalid variable names.

Question
What could be a valid way to

*

*create an enum type with typedef for a library

*do not add any identifiers to this type yet, but

*allow a library user to create enums with identifiers using this type

*pass any value of these enum to the same function (bonus: without type conversion)

A: You could create a forward declaration of the type using
enum tag_name;

then create a typedef using this incomplete definition with
typedef enum tag_name my_enum_type;

and expose those in a header file, and then complete the definition in a .c file using
enum tag_name { ... };

What you cannot do is define the type as
enum tag_name { ENUM1, ENUM2 };

and then later on add
enum tag_name { ENUM3 };

The type is complete after the closing } of the first definition - you can't add any more enumeration constants after that point.  C just doesn't work like that.
I'm not fond of using typedef just to create a new name - the user of the type still needs to know it's an enum type (or at least that it's an integral value).  The abstraction is "leaky" and just adds clutter.  Either create a complete abstraction where the user of the type does not have to be aware of how it's implemented, or don't use an abstraction at all.

A: enums are for readability and for the compiler.
An easy way is for the header file for the library to contain the enum definition (the code calling the library also needs to know the enum definition.)
By having the enum definition in the header file (note, not an instance of the enum, just the definition.)  any file that includes that header file can access the library function and pass valid enum parameters
Strongly suggest to NOT turn that enum definition into a typedef name
Do notice the difference between a enum definition and an instance of that enum
Instance:
enum myEnum enumInstance;

Definition:
enum myEnum { ... };

Anonymous:
enum { ... };

All where the ... is the list of name=value pairs. separated by commas.
for flexibility, do NOT combine the definition with an instance, I.E.
enum myEnum { ... } enumInstance;

or
enum { ... } enumInstance;


text:
Q: window.opener.document.getElementById not working In my asp.net web app, I create a popup window with a button.  When that button is clicked, I want to set the value of an asp:TextBox (id=TextBox1) contained in the parent window.  However, it doesn't work like all the examples I've read indicate.
I've tried the following lines of code in my javascript onclick handler:

*

*window.opener.document.getElementById('<%= TextBox1.ClientID %>').value = "abc";

*window.opener.document.getElementById("TextBox1").value = "abc";

*window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox1").value = "abc";

Only example 3 works.  All the stuff I've read indicates that #1 is the preferred method, but I can't seem to make it work at all.  Does anyone have any ideas what I'm doing wrong?
I've tried this in Firefox, Chrome and IE.
Thanks

A: you need to change a bit when calling your popup code , you have to pass your textbox client id and then you can set its value from popup page without any hard codding.
here is the way :
var txtNameClientObject = '<%= txtName.ClientID %>';
window.open('Child.aspx?txtName='+txtNameClientObject);

and then in popup page you  can do it as
opener.document.getElementById('<%= Request["txtName"] %>').value = 'from child';

hope this will be helpful for you.
Thanks

A: Is this line of JavaScript contained in the markup for the popup window itself? If so, the server-side code for that won't be aware that TextBox1 exists on the server-side code for the parent window, and won't be able to determine its ClientID property. You either need to pass that client ID to the popup window somehow (querystring, cookie, session, whatever) or hard code it. Alternatively, you may be able to put this line of JavaScript in a function on your parent page, and then call something along the lines of window.opener.functionName().


text:
Q: Deploy a smart contract with constructor in Truffle I want to deploy my contract which contain a constructor (2 account address and a value P), in Remix, I put manually the address of both account and P value, but in truffle, I edited manually the 2_deploy_contracts.js file as follow:
Contract:
constructor(address payable _account1, address payable _account2, uint _P) public {account1 = _account1;account2 = _account2; P = _P;}
2_deploy_contracts.js:
var contract = artifacts.require("contract");
module.exports = function(deployer)  {
deployer.deploy(contract, account1, account2, P);};

Thanks in advance for help.

A: You have to declare and initialize these parameters :
var account1='0x...';
var account2='0x...';
var P=...;
deployer.deploy(contract, account1, account2, P);

A: so i was facing the similar problem. And there are few things to be noted.

*

*In your contract, you should declare the contracts, constructer something like this:
Here Coin and Reward are my contracts.

constructor(Coin _coinContractsAddress, Reward _rewardContractAddress){
    coin_ = _coinContractsAddress;
    reward_ = _rewardContractAddress;
}

*Now this was for the contract.
Changes in Deployment file should be made like this:

deploy-contracts.js
module.exports = async function() {
    await deployer.deploy(Coin);
    const coin_ = await Coin.deployed();

    await deployer.deploy(Reward);
    const reward_ = await Reward.deployed();
    //Now we are going to deploy these contracts, address in the 3rd Contract address named Bank.
    await deployer.deploy(Bank, coin_.address, reward_.address);
    //Point to note is we are deploying the Bank contract and in its constructor at same time we are passing the coin_.address which is the deployed contract address and reward_.address.
}

*Now run truffle migrations and it will be successfully deployed. truffle migrate --reset


text:
Q: Convert structure to PHP array The horrible system we use in my company gives me the following output:
{
    party:"bases",
    number:"1",
    id:"xx_3039366",
    url:"systen01-ny.com",
    target:"_self",
    address:"Ch\u00e3o as Alminhas-Medas,Uteiros de Gatos e Fontes Longaq
64320-761 ANHADOS LdA",
    coordinate:{
        x:90.995262145996094,
        y:-1.3394836426
    },
    contactDetails:{
        id:"366",
        phone:"xxxxxx",
        mobile:"",
        fax:"xxxx 777 235",
        c2c:!0
    },
    parameters:"Flex Am\u00e1vel Silva,hal,,EN_30336,S,786657,1,0,",
    text:"Vila Nova de Loz C\u00f4a,os melhores vinhos, v\u00e1rias. Produtor/exportador/com\u00e9rcio",
    website:null,
    mail:"",
    listing:"paid",
    pCode:"64",
    name:"xpto Am\u00e1vel Costa",
    logo:{src:"http://ny.test.gif",
    altname:"xpto Am\u00e1vel Costa"},
    bookingUrl:"",
    ipUrl:"",
    ipLabel:"",
    customerId:"7657",
    addressId:"98760",
    combined:null,
    showReviews:!0
}

I would like to know if there is a way to convert the output to array, as if it were a json, or even some other format that I can manipulate this data in PHP. Json_decode does not work.

A: Just like I said I would, here your very own Json Object parser.
One word of warning, these kind of things can be more art then science so if your inputs vary from what was in your example, it could have issues.  Given the small sample size (1 document) I make no guarantees on it's functionality outside that one example.
I would try to explain how this works, but I fear it would be lost on mere mortals.
Seriously, this was fun, enjoyed the challenge for once.
<?php
function parseJson($subject, $tokens)
{
    $types = array_keys($tokens);
    $patterns = [];
    $lexer_stream = [];

    $result = false;

    foreach ($tokens as $k=>$v){
        $patterns[] = "(?P<$k>$v)";
    }
    $pattern = "/".implode('|', $patterns)."/i";

    if (preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE)) {
        //print_r($matches);
        foreach ($matches[0] as $key => $value) {
            $match = [];
            foreach ($types as $type) {
                $match = $matches[$type][$key];
                if (is_array($match) && $match[1] != -1) {
                    break;
                }
            }

            $tok  = [
                'content' => $match[0],
                'type' => $type,
                'offset' => $match[1]
            ];

            $lexer_stream[] = $tok;
        }

       $result = parseJsonTokens( $lexer_stream );
    }
    return $result;
}

function parseJsonTokens( array &$lexer_stream ){

    $result = [];

    next($lexer_stream); //advnace one
    $mode = 'key'; //items start in key mode  ( key => value )

    $key = '';
    $value = '';

    while($current = current($lexer_stream)){
        $content = $current['content'];
        $type = $current['type'];

        switch($type){
            case 'T_WHITESPACE'://ignore whitespace
                next($lexer_stream);
            break;
            case 'T_STRING':
                //keys are always strings, but strings are not always keys
                if( $mode == 'key')
                    $key .= $content;
                else
                    $value .= $content;
                next($lexer_stream); //consume a token
            break;
            case 'T_COLON':
                $mode = 'value'; //change mode key :
                next($lexer_stream);//consume a token
            break;
            case 'T_ENCAP_STRING':
                $value .= trim(unicode_decode($content),'"'); //encapsulated strings are always content
                next($lexer_stream);//consume a token
            break;
            case 'T_NULL':
                 $value = null; //encapsulated strings are always content
                 next($lexer_stream);//consume a token
            break;
            case 'T_COMMA':  //comma ends an item
                //store
                $result[$key] = $value;
                //reset
                $mode = 'key'; //items start in key mode  ( key => value )
                $key = '';
                $value = '';
                next($lexer_stream);//consume a token
            break;
            case 'T_OPEN_BRACE': //start of a sub-block
                $value = parseJsonTokens($lexer_stream); //recursive
            break;
            case 'T_CLOSE_BRACE': //start of a sub-block
                //store
                $result[$key] = $value;
                next($lexer_stream);//consume a token
                return $result;
            break;
            default:
                print_r($current);
                trigger_error("Unknown token $type value $content", E_USER_ERROR);
        }

    }

    if( !$current ) return;
    print_r($current);
    trigger_error("Unclosed item $mode for $type value $content", E_USER_ERROR);
}

//@see https://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha
function replace_unicode_escape_sequence($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}

function unicode_decode($str) {
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $str);
}

$str = '{
    party:"bases",
    number:"1",
    id:"xx_3039366",
    url:"systen01-ny.com",
    target:"_self",
    address:"Ch\u00e3o as Alminhas-Medas,Uteiros de Gatos e Fontes Longaq
64320-761 ANHADOS LdA",
    coordinate:{
        x:90.995262145996094,
        y:-1.3394836426
    },
    contactDetails:{
        id:"366",
        phone:"xxxxxx",
        mobile:"",
        fax:"xxxx 777 235",
        c2c:!0
    },
    parameters:"Flex Am\u00e1vel Silva,hal,,EN_30336,S,786657,1,0,",
    text:"Vila Nova de Loz C\u00f4a,os melhores vinhos, v\u00e1rias. Produtor/exportador/com\u00e9rcio",
    website:null,
    mail:"",
    listing:"paid",
    pCode:"64",
    name:"xpto Am\u00e1vel Costa",
    logo:{src:"http://ny.test.gif",
    altname:"xpto Am\u00e1vel Costa"},
    bookingUrl:"",
    ipUrl:"",
    ipLabel:"",
    customerId:"7657",
    addressId:"98760",
    combined:null,
    showReviews:!0
}';

$tokens = [
    'T_OPEN_BRACE'      => '\{',
    'T_CLOSE_BRACE'     => '\}',
    'T_NULL'            => '\bnull\b',
    'T_ENCAP_STRING'    => '\".*?(?<!\\\\)\"',
    'T_COLON'           => ':',
    'T_COMMA'           => ',',
    'T_STRING'          => '[-a-z0-9_.!]+',
    'T_WHITESPACE'      => '[\r\n\s\t]+',
    'T_UNKNOWN'         => '.+?'
];

var_export( parseJson($str, $tokens) );

Outputs ( this is what everyone wants )
array (
  'party' => 'bases',
  'number' => '1',
  'id' => 'xx_3039366',
  'url' => 'systen01-ny.com',
  'target' => '_self',
  'address' => 'Chão as Alminhas-Medas,Uteiros de Gatos e Fontes Longaq
64320-761 ANHADOS LdA',
  'coordinate' =>
  array (
    'x' => '90.995262145996094',
    'y' => '-1.3394836426',
  ),
  'contactDetails' =>
  array (
    'id' => '366',
    'phone' => 'xxxxxx',
    'mobile' => '',
    'fax' => 'xxxx 777 235',
    'c2c' => '!0',
  ),
  'parameters' => 'Flex Amável Silva,hal,,EN_30336,S,786657,1,0,',
  'text' => 'Vila Nova de Loz Côa,os melhores vinhos, várias. Produtor/exportador/comércio',
  'website' => NULL,
  'mail' => '',
  'listing' => 'paid',
  'pCode' => '64',
  'name' => 'xpto Amável Costa',
  'logo' =>
  array (
    'src' => 'http://ny.test.gif',
    'altname' => 'xpto Amável Costa',
  ),
  'bookingUrl' => '',
  'ipUrl' => '',
  'ipLabel' => '',
  'customerId' => '7657',
  'addressId' => '98760',
  'combined' => NULL,
  'showReviews' => '!0',
)

And you can even test it here ( because I am a nice guy )
http://sandbox.onlinephpfunctions.com/code/3c1dcafb59abbf19f7f3209724dbdd4a46546c57
I was able to fix the encoding issues \u00e etc with help of this SO post, so a shout out to them, because I hate character encoding.
http://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-char
Man I just love a beautiful piece of code, just umm.
Cheers!


text:
Q: copy multiple files in storage bucket using list The gsutil cp command hast the -I option to copy multiple files using a list of file names from stdin. Is there a way to do the same in python, preferable using a library like the official google storage client or gcfs/fsspec? Or is it only possible to iterate over all the file names and copy each one?

A: Using the version currently in gcsfs master (to be released soon), you can copy files to GCS from memory or local files with a list:
gcs.pipe({path1: content1, path2, content2})  # for in-memory bytes

gcs.put([local_path1, local_path2], [remote_path1, remote_path2])  # files

For the latter, you can give just one remote path, which will be assumed to be a directory, and the remote files will get the same basenames as local.
The calls will be processed concurrently, which may be much faster than sequential uploads, especially for small transfers.


text:
Q: Select multiple columns with linq to sql I am trying to select multiple columns by using LinqToSql, but I am having a hard time with it. I am quite new in LinqToSql.
When I am selecting 1 column I do it like this:
string[] name = mycontext.Users.SingleorDefault(p => p.UserId == 1).UserName;

Is there anything similar for multiple columns?
I actually want to assign Name and Surname in a ListBox control

A: Use Anonymous Types:
var result = mycontext.Users.Where(p => p.UserId == 1)
                            .Select(c => new {c.UserName , c.Family ,...})
                            .SingleOrDefault();

A: You current request will query the whole user (select *).
In most cases, it is enough and you can access to each column separately :
var user = mycontext.Users.SingleorDefault(p => p.UserId == 1);

var userName = user.Username;
var password = user.Password;
// etc...

If you only need one (or several columns) but not the whole user, you can do it like this:
var userInfo = mycontext.Users.Where(p => p.UserId == 1).Select(p => new {p.UserName, p.Password}).SingleOrDefault();

var userName = userInfo.UserName;
var password = userInfo.Password;

If you prefer a collection of string in result, you can do it this way:
List<string> userInfo = mycontext.Users.Where(p => p.UserId == 1).Select(p => new List<string> { p.UserName, p.Password }).SingleOrDefault();

var username = userInfo[0];
var password = userInfo[1];

This way, the generated query will looks like Select UserName, Password From UserTable. Its usefull only if your table has a lots of columns or a heavy one (blob for example).
How it works: by calling the Where extension methods firstly, you tell .NET to not run the query immediately. It will be executed on the SingleOrDefault call. But at this moment, the query has been completed and the whole part is done in SQL.

A: Can't you return User object?
var user = mycontext.Users.SingleorDefault(p => p.UserId == 1)

After that you can get all properties of User without creating dynamic types


text:
Q: Fasten building a dict from a dataframe with pandas
def dict_trunkated(collection, df):
    dict_all = {}
    #collection = shorten_string(collection)

    collection = list(collection)
    for element in collection:
        #counter_el += 1
        #print("num dupless", counter_el)
        dict_all[element] = {"id_ja" : None, "id_nein" : None ,"ZUW_ja": set(), "ZUW_nein": set(), "missing_ZUW_ja" : set(), "missing_ZUW_nein" : set()}

    for rownum in range(0,df.shape[0]):
        #counter_zuw += 1
        #print("num zuwlist", counter_zuw)
        #print(df.iloc[rownum][6][-5:])
        if "_Ja" in df.iloc[rownum][6][-5:]:
            dict_all[df.iloc[rownum][6][0:-3]]["id_ja"] = df.iloc[rownum][5]
            dict_all[df.iloc[rownum][6][0:-3]]["ZUW_ja"].add(df.iloc[rownum][1])

        if "_Nein" in df.iloc[rownum][6][-5:]:
            dict_all[df.iloc[rownum][6][0:-5]]["id_nein"] = df.iloc[rownum][5]
            dict_all[df.iloc[rownum][6][0:-5]]["ZUW_nein"].add(df.iloc[rownum][1])
    return dict_all

Right now it takes more than three minutes to analyze my dataframe and put all the information i need into my dict.
I'm wondering if its better to change Arrays I use before to Pandas Series (inside the functions before where I prepare the collection which is used in this function)?
And are there ways to fasten my loops? I know these one liners, but can't figure out how to use these in my context..
Especially my second lop seems to be very inefficient.
Inspire me ;-)
My DataFrame Input looks like: *(Sorry don't know how to present it in a better way)*

Relation ID(INT that becomes `ZUW_ja` or `ZUW_no`) ; TERM-ID (INT that becomes `id_ja` or `id_no`) ;
NAME (str which gets stemmed and is used as key for the dict)

My dict Output should look like:
dict_all[key] = {'id_ja': 6176144, 'id_nein': 6176145, 'ZUW_ja': {3842, 1283}, 'ZUW_nein': {3842, 3300753}, 'missing_ZUW_ja': set(), 'missing_ZUW_nein': {3300610, }}


text:
Q: How can I loop through my table to display contents side by side in MVC Razor View? Hi i want help in putting contents side by side.
Right now i can display content separately in left side and right side. But i need to display records from database. For this i am using foreach loop. So how i need to display is 1st records on left side and 2nd record on right side and 3rd on left and so on. How can i loop through like this.
I am stucked here.I need help..
I am using this code but all the contents are displaying as i told earlier.

   @foreach (var item in Model)

        {

  APP

             @item.ID

    }

A: Instead of
@foreach (var item in Model)

use
@for (var i=0; i < Model.Count; i+=2)
{

}

and access properties of model like
 @Model[i].ID

In order to determine which should go to right which should  go left you can use
@Model[i].ID for left

and
@if(i+1 < Model.Count)
{
  Model[i+1].ID for right
}

Just make sure that i+1 is never more than Model.Count

A: Using this pattern you can make as many columns as you like. If you're using an html table you need to also test if you need blank cells when the total collection size is not divisible by columns.
@{
    int columns = 3;
}

@for (int i = 0; i < Model.Count; i++)
{
    var currentModel = Model[i];

    int col = i % columns;

    if (col == 0)
    {
        // left
    }
    else if (col == 1)
    {
        // middle
    }
    else  // col == 2
    {
        // right
    }
}


text:
Q: What is proper way to wire some logic for built-in models User is built-in model.
Where to put
models.User.on('deleted', function(id) {
 // some logic here
})

common/models/user.js is not called for built-in User model.

A: You can extend the built-in models to add properties, relationships, ACLs, and other model features.  You can use the LoopBack model generator or do it programmatically.
Detailed steps are provided in the docs http://docs.strongloop.com/display/LB/Extending+built-in+models