text:
Q: can't find class in separated files This is my first time doing java codes, and I am confused on this. I supposed to compile 2 files, the first is Lingkaran.java which contains class lingkaran, and the second is MLingkaran.java which is the main file. The Lingkaran.java compiles just fine, but when I tried to compile the MLingkaran.java, these errors came out.

C:\Users\LENOVO PC>javac F:\SchoolSums-Praktikum\Semester4\PemrogramanBerbasisObjek\14.03.17\2\MLingkaran.java
         F:\SchoolSums-Praktikum\Semester4\PemrogramanBerbasisObjek\14.03.17\2\MLingkaran.java:11: error: cannot find symbol
            lingkaran l = new lingkaran();
            ^
            symbol:   class lingkaran
            location: class mLingkaran
          F:\SchoolSums-Praktikum\Semester4\PemrogramanBerbasisObjek\14.03.17\2\MLingkaran.java:11: error: cannot find symbol
                  lingkaran l = new lingkaran();
                                    ^
            symbol:   class lingkaran
            location: class mLingkaran
        2 errors

The following are the source code:
Lingkaran.java:
class lingkaran {
    private double jari;
    private double luas;
    private double keliling;
    private double phi;

    public lingkaran(){
        this.phi = 3.14;
        this.jari = 10;
        this.keliling =  this.jari*2*this.phi;
        this.luas = this.phi * this.jari * this.jari ;
    }

    public double getLuas() {
        return this.luas;
    }

    public double getKeliling() {
        return this.keliling;
    }
}

and the MLingkaran.java:
class mLingkaran {
    public static void main (String [] args) {

        lingkaran l = new lingkaran();

        System.out.println("keliling = " +l.getLuas());
        System.out.println("luas = " +l.getKeliling());
    }
}

A: You need to import the other files to be able to use anything in them.
import <package>.Lingkaran;

If the file isn't in a package (it should be though), then you can leave the first part out.
Let's take the following project structure:
package1
    MLingkaran
    package2
        Lingkaran

Then in MLingkaran you need to use
import package1.package2.Lingkaran;


text:
Q: Sorting array with MPI in C++ I want to sort array of random numbers using MPI library. The idea is to chop array with MPI_Scatterv and send it to the processes. Every process should localy sort its amount of data and send it back to the main process (MPI_Gatherv). Main process should sort partly sorted table(merge). If have problems with last step. I just cannot merge the table corectly.
Any ideas?
Here is the code:
    #include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "math.h"
#include "mpi.h"
#include <time.h>

#define N 20

int numOfProc, idproc;

int compare(const void * a, const void * b) {
   const int *ia = (const int *)a;
    const int *ib = (const int *)b;
    return *ia  - *ib;
}

int main(int argc,char ** argv) {

   MPI_Init(&argc, &argv);
   MPI_Comm_size(MPI_COMM_WORLD, &numOfProc );
   MPI_Comm_rank(MPI_COMM_WORLD, &idproc);

   int * buf, * send_buf, * receive_buf, * sorted_buf, *displ, *sendcnts, *recvcnts;
   int count = N/numOfProc;
   int size, i;
   int temp, index;

   displ=(int*)malloc(numOfProc*sizeof(int));

   sendcnts=(int*)malloc(numOfProc*sizeof(int));

   recvcnts=(int*)malloc(numOfProc*sizeof(int));

   buf=(int*)malloc(count*sizeof(int));

   for(i=0; i<numOfProc; i++){
       displ[i]=i*count;
       sendcnts[i]=count;
       recvcnts[i]=count;
   }

   if(idproc == 0) {
      size=N;
      send_buf=(int*)malloc(size*sizeof(int));
      receive_buf=(int*)malloc(size*sizeof(int));

      for (i=0;i<size;i++) {
         send_buf[i] = rand();
      }
      printf("\n\n");
      fflush(stdout);
   }

   MPI_Scatterv(send_buf, sendcnts, displ, MPI_INT, buf, count, MPI_INT, 0, MPI_COMM_WORLD);

   printf("proces %d: ", idproc);
   qsort(buf, count, sizeof(int), compare);
   for (int i = 0; i < count; i++) printf("%d ", buf[i]);
   printf("\n\n");
   fflush(stdout);

   MPI_Gatherv(buf, count, MPI_INT, receive_buf, recvcnts, displ, MPI_INT, 0, MPI_COMM_WORLD);

   if (idproc == 0) {
       //merge
       temp=INT_MAX;
       for(i=0; i<size; i++){
           for(int j=0; j<numOfProc; j++){

               if(temp>receive_buf[displ[j]]){
                   temp=receive_buf[displ[j]];
                   receive_buf[displ[j]]=receive_buf[i];
                   receive_buf[i]=temp;
               }

           }

           printf("%d ", receive_buf[i]);
       }

      printf("\n");
      fflush(stdout);
   }
   wait(100);
   MPI_Finalize();
}

Thanks in advance, Igor

A: The individual processes will sort the sub set of the parent array. But after the Master process gathers all these sub sets there has to be one sorting done for the parent array.
e.g.
original array = {1,7,2,3, 10,4,8,0, 11,5,9,6}
after scatter  process 1 : {1,7,2,3} process 2 : {10,4,8,0} process 3 : {11,5,9,6}
and individual process sorting : {1,2,3,7}  , {0,4,8,10}  , { 5,6,9,11}
thus after gathering you have the original array as {1,2,3,7  , 0,4,8,10  ,  5,6,9,11}
Thus there has to be one more sorting pass done.
Edit :
One of the solutions would be (This can be further optimized):
instead of using mpi scatter and gather use a plain mpi send and mpi receive.

The master process/node would give the data to the dummy master process/node which will further divide it to rest of the nodes. The last line of nodes can sort the sub set of data and return the sorted subsets to their parents.

after the parents receive the individually sorted sub sets they will sort the sorted subsets and provide their sets to their parents.
This approach can be further optimized.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Cloudant support TLS1.2 connections? I'm looking to make TLSv1.2 connections to Cloudant server. From the cloudant java client can we make TLSv1.2 connections?

A: Providing your JVM support making such connections, it can make TLSv1.2 connections to cloudant.


text:
Q: How to use SKSceneDelegate (and abuse) Normally I set up my delegates like normal:
@interface CAKGameViewController : UIViewController <CAKGameSceneDelegate>

then follow up in the CAKGameScene.h with
@protocol CAKGameSceneDelegate;

@interface CAKGameScene : SKScene <SKPhysicsContactDelegate>
...(properties, etc)
@protocol CAKGameSceneDelegate <NSObject>

@optional
- (void)getStarted;
@end

But as most of us know as a property you have to setup shop like this:
@property (nonatomic, weak, readwrite) id<CAKGameSceneDelegate> myDelegate;

My question is, I want to use the actual SKSceneDelegate (self.delegate, not (self.myDelegate) and go like this:
@interface CAKGameViewController : UIViewController <SKSceneDelegate>

Now this is fine and I can use self.delegate to reference the controller, but the problem is I can't seem to figure out how to customize the CAKGameViewController, i.e. setup the protocol further, or customize the protocol, for my methods and/or properties. :(
Any assistance would be helpful.
Thanks

A: I finally found a suitable workaround to use and assign the SKScene delegate.  The trick is to cast (of course right)!?
You interface the GameViewController and conform to protocols
in CAKGameViewController.h
@interface CAKGameViewController : UIViewController
<SKSceneDelegate, CAKGameSceneDelegate>

in CAKGameScene.h
@protocol CAKGameSceneDelegate <NSObject>
// any @property;
// or - (void)methods;
@end

in CAKGameViewController.m you assign the delegate using self:
self.scene.delegate = self;  //this is the Apple delegate property

then whenever you want to use
something = self.delegate.property; // <or>
[self.delegate method]; // from the CAKGameSceneDelegate protocol

you cast
something = ((id<CAKGameSceneDelegate>)self.delegate).property; // <or>
[((id<CAKGameSceneDelegate>)self.delegate) method];  // from non-apple protocol

what I did was just make a #define
#define delegateHelper ((id<CAKGameSceneDelegate>)self.delegate)

then I can:
something = delegateHelper.property;
[delegateHelper method];

I just figure if you are going to have a property called delegate, like most cocoa/objective-c objects do, to make things work, the delegate should be the delegate, you shouldn't have to use myDelegate, or something silly.   delegateHelper may not be much better, but for me I can live with this workaround.

A: You can extend the original delegate in the protocol definition:
@protocol CAKGameSceneDelegate <SKSceneDelegate>
    //extend SKSceneDelegate with new functions here
@end

Or in Swift:
protocol CAKGameSceneDelegate: SKSceneDelegate
{
    //extend SKSceneDelegate with new functions here
}

You do not have to redefine delegate if you do it this way.


text:
Q: Google Slides triggers not available I'm trying to script a Google Slides presentation but the 'from Slides' installable trigger isn't showing up, only timed and calendar.
I've tried using several different accounts, on shared and unshared projects alike. No luck.
Ideas?

A: Such triggers doesn't exists. Ref. https://developers.google.com/apps-script/guides/triggers/installable


text:
Q: Rails Tutorial: SQLite3::ConstraintException: UNIQUE constraint failed: users.email I'm following along with the rails tutorial. I'm on ch. 6 and I'm getting a strange error with SQLite3 (for the record, I'm using sqlite version 1.3.10 and the tutorial uses 1.3.9)
I don't get an error when I run rake db:migrate, but when I run the migration for the test environment, here's what I get:
$ bundle exec rake test:models

rake aborted!
ActiveRecord::PendingMigrationError:

Migrations are pending. To resolve this issue, run:

    bin/rake db:migrate RAILS_ENV=test

sample_app/test/test_helper.rb:3:in `<top (required)>'
sample_app/test/models/user_test.rb:1:in `require'
sample_app/test/models/user_test.rb:1:in `<top (required)>'
Tasks: TOP => test:models
(See full trace by running task with --trace)

$ bundle exec rake db:migrate RAILS_ENV=test

== 20150628011937 AddIndexToUsersEmail: migrating ===========================
==
    -- add_index(:users, :email, {:unique=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::ConstraintException: UNIQUE constraint failed: users.email: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constrain
t failed: users.email: CREATE UNIQUE INDEX "index_users_on_email" ON "users"
("email")
sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
SQLite3::ConstraintException: UNIQUE constraint failed: users.email
sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Here is my user.rb model:
class User < ActiveRecord::Base
  before_save { self.email = email.downcase }
  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
end

Here is my most recent migration
  class AddIndexToUsersEmail < ActiveRecord::Migration
    def change
      add_index :users, :email, unique: true
    end
  end

I can post any other files if those are relevant. Thanks in advance for the help!

A: I experienced it for a bit different reason and here is the solution.
For me the error was
Minitest::UnexpectedError: ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2018-05-09 18:23:59.827561', '2018-05-09 18:23:59.827561', 298486374)

Notice the INTO "users" ("created_at", "updated_at", "id"). It was caused by test/fixtures/users.yml was not filled, so then there was duplicate values in columns which has unique key constraint.
test/fixtures/users.yml:
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value

A: if you can't reset:db you should try to delete it by hand go to db folder and delete the "development.sqlite3" and the "test.sqlite3" files
then run
rails db:migrate
and bin/rails db:migrate RAILS_ENV=TEST
worked for me, anyway...

A: The problem was that I had users in the database with the same email before the migration.
db:reset solved everything

A: If this happens to you when running tests:
Make sure there are no users fixtures, unless you explicitly define those users with unique attributes.
test/fixtures/users.yml

When you generate a model, for example:
rails g model User

Rails automatically creates that file and it looks like:
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value

This can mess up your tests.

A: Just use rake db:test:prepare and it will copy the dev database to test so you don't need to run the migrations.

A: I had to delete my development.db to resolve the issue.


text:
Q: WstxEOFException: Unexpected EOF in Prolog on JBoss only The error I am getting are in a few forum posts, but all the scenarios seem slightly different than mine.
I am writing a JAX-WS web service client to communicate to a soap-based web service that uses basic authentication (http level only). I generated the client using wsimport on the wsdl.
There are two versions of the web service available to me for testing:

*

*Port 8080 - no authentication

*Port 80 - requires basic http level authentication

What the web service does:

*

*This is just a simple web service that lets me send an base64 encoded xml payload into it.

I verified the following:

*

*I can correctly send both web services (80/8080) using SOAPUI from my localhost

*I can correctly send both web services using a test JAVA application from my localhost

What fails:

*

*As soon as I try to deploy my web service client as a .war on jboss5.1... only the port 8080 web service works. When I try the web service on port 80, I get this error.

10:36:51,467 ERROR [CommonClient] Exception caught while (preparing for) performing the invocation:
javax.xml.ws.soap.SOAPFaultException: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]
    at org.jboss.ws.core.jaxws.SOAPFaultHelperJAXWS.getSOAPFaultException(SOAPFaultHelperJAXWS.java:84)
    at org.jboss.ws.core.jaxws.binding.SOAP11BindingJAXWS.throwFaultException(SOAP11BindingJAXWS.java:107)
The Core Code for my test client:
        Service service = Service.create(url, qname);
        ImportLoan port = service.getPort(ImportLoan.class);
        BindingProvider bp = (BindingProvider) port;
        bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,  properties.getProperty("username"));
        bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,  properties.getProperty("password"));
        ImportLoanRequestType requestType = new ImportLoanRequestType();
        requestType.setData(strEncodedPayload);
        ImportLoanResponseType responseType = port.importLoanApp(requestType);

What I'm Hoping For
I just need some ideas to triage here. I assume I am getting some invalid SOAP response back that cannot be parsed correctly. I just find it odd that it only happens when sending the service from JBoss (my app server), so it must be something on my end. SOAPUI works fine. The exact same code written in a standalone test.java file works fine as well.
Update... later in the evening
Of course I would find the answer the same day I ended up posting the question. I watched the http traffic and realized the HTTP500 error response (with the soap eof prolog error) came back after half the data was sent. Apparently JBoss chunks the data. That worked fine against the 8080 service, but the port 80 service didn't support chunking for some reason. I assumed it was an authentication error, but appears to be that the web service doesn't support chunking. I modified the standard-jaxws-client-config.xml (jbossws.deployer/META-INF folder) on my server. Set the chunksize from 2048 to 0, and voila... problem solved. Hope this helps somebody else out there someday.


text:
Q: Ho to generate random code and insert into mysql table I have the following insert query, I am unable to put the random code in this. Please help me out.
("insert into users (UserName,UserType,AgencyID,Email,Password,Cpassword,CityID,Address,Mobile,OTP,Approval)    values
    ('$users->UserName','$users->UserType',$users->AgencyID,'$users->Email','$users->Password','$users->Cpassword',$users->CityID,'$users->Address','$users->Mobile','$users->OTP','$users->Approval')");

A: You can do this with RAND().
Please refer this

A:
function createRandomPassword() {

    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= 7) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }

    return $pass;

}

$random_code = createRandomPassword();

("insert into users (UserName,UserType,AgencyID,Email,Password,Cpassword,CityID,Address,Mobile,OTP,Approval)    values
    ('$users->UserName','$users->UserType',$users->AgencyID,'$users->Email','$users->Password','$users->Cpassword',$users->CityID,'$users->Address','$users->Mobile','$random_code','$users->Approval')");


text:
Q: BOOTSTRAP NAVBAR AND CAROUSEL I have a problem when using Boostrap's navbar and carousel since in PC view it hides the image behind the navbar and when you put mobile view it hides the carousel images even more. some help?
Thanks for the support!
enter image description here


text:
Q: How to add SWRL rules to an Ontology using Java or pellet? Instead of using Protégé to add rules to my ontology, I want to use Java or pellet to add SWRL rule to the ontology.
For example, this is the rule that I want to import into my ontology:

[Course(?x),teacherOf(?y,?x),worksFor(?y,?z)] =>
  [coursePresentedInUniversity(?x,?z)]

I want to add the following code into the ontology:
<swrl:Imp rdf:about="#CoursePresentedInUniversityRule">
    <swrl:head rdf:parseType="Collection">
        <swrl:IndividualPropertyAtom>
                <swrl:propertyPredicate rdf:resource="#coursePresentedInUniversity" />
                <swrl:argument1 rdf:resource="#x" />
                <swrl:argument2 rdf:resource="#z" />
        </swrl:IndividualPropertyAtom>
    </swrl:head>
    <swrl:body rdf:parseType="Collection">
        <swrl:ClassAtom>
            <swrl:classPredicate rdf:resource="#Course" />
            <swrl:argument1 rdf:resource="#x" />
        </swrl:ClassAtom>

        <swrl:IndividualPropertyAtom>
            <swrl:propertyPredicate rdf:resource="#teacherOf" />
            <swrl:argument1 rdf:resource="#y" />
            <swrl:argument2 rdf:resource="#x" />
        </swrl:IndividualPropertyAtom>
        <swrl:IndividualPropertyAtom>
            <swrl:propertyPredicate rdf:resource="#worksFor" />
            <swrl:argument1 rdf:resource="#y" />
            <swrl:argument2 rdf:resource="#z" />
        </swrl:IndividualPropertyAtom>

    </swrl:body>
</swrl:Imp>

Could anybody point me out to a sample code to do that?
Actually, I wrote the following code, but it didn't work!
    Rule mynewRule=new Rule(ruleHead,ruleBody);
    PelletReasoner pelletReasoner =com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory.getInstance().createReasoner(testOntology );
    KnowledgeBase knowledgeBase=pelletReasoner.getKB();
    knowledgeBase.addRule(mynewRule);

A: One way with Java code is through the OWL API - the OWLDataFactory class has methods for creating SWRL rules, and the resulting rules can be added to an ontology and saved - it is the same process used by Protege 4 and 5.
Documentation is available here


text:
Q: How should I safely change cygwin's installation directory on win 7? Forgive me if I'm missing something obvious, but most of the FAQ for cygwin seems outdated.  I installed it to c:/cygwin64, but inanely listened to a few forum posts that recommended installing every package since it was 'so small'.  Its 41.9 GB on my disk...  So, I'd like to move it to an external.
https://cygwin.com/ml/cygwin/1998-11/msg00649.html  -- here I found,

Is it possible to change the root directory from c:\
    to some other directory or drive (for e.g. j:)?

Yes, of course. Easiest way is to change it in the registry directly:
  Goto [HKEY_CURRENT_USER\Software\Cygnus Solutions\CYGWIN.DLL
  setup\b15.0\mounts] There are a few mount points from 00 to 0x; find
  the one with the following values:  "native"="C:"  "unix"="/"
  "fbinary"=dword:00000001  "fsilent"=dword:00000000  and change native=
  to whatever you want.

This seems to suggest that moving is as easy picking up all the files and then changing a registry key.  This is obviously not for windows 7 however and I am wary of ever touching my registry.  The corresponding key seems to be
HKEY_LOCAL_MACHINE\SOFTWARE\Cygwin\setup as it has rootdir with C:\cygwin64 as its value.
There is also a seemingly random string with the value \??\C:\cygwin64 in HKEY_LOCAL_MACHINE\SOFTWARE\Cygwin\Installations as well as
HKEY_CURRENT_USER\SOFTWARE\Cygwin\Installations.
So, more pointedly, my questions:

*

*Is it correct to move the cygwin64 folder from c: to e: and change the C:'s to E:'s in the registry?

*Can you reassure me this won't affect the voodoo of the registry and break cygwin?

*If not, is there another, more sensible way?

A: What i've already done and you can do, is to make a tar.gz of your cygwin install (with by example cygwin 32bits if you want to move the 64), and untar it where you want. You may have to modify the short link, the bat, and "maybe" some environment variable. Note: installing all the packages is unnecessary.

A: You could also create a symbolic link to the new location:
mklink /J c:\cygwin64 d:\cygwin

where d: is representing your external drive letter. See also
https://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/


text:
Q: Create a trigger annually in mysql I need to create a trigger annually and updates profit using mysql..
The table related to these question is ,
create table annual_document(
  documment_id int not null AUTO_INCREMENT,
  income decimal(4,2),
  expence decimal(4,2),
  PRIMARY KEY(documment_id)
);

I try this one using different method.but i'm unable to create trigger which is execute annually.most of the documents describes execute event annually.not the trigger.but I need a trigger.
Can someone help to me..

A: That may what you are looking for:
CREATE EVENT myevent
ON SCHEDULE
  EVERY 1 year
DO
  call dd

where dd is a PROCEDURE  written in it a code to create a trigger...


text:
Q: notation confusion in C when variable is a pointer I am confused about a notation in C when I have a pointer variable f pointing to a struct X defined as:
struct Y {
    int d;
    struct X *e;
};

struct X {
    int *a;
    int b[4];
    struct Y c;
};

Then I have this:
f->c.e->c.e[0].a[0]

The thing I don't understand is the part c.e[0].a[0].
I am not sure what is c.e[0] and then also what is c.e[0].a[0]. (also not sure whether c.e[0] is 20-offset from the starting address of a struct X). Assuming here pointer is 4 bytes, integer is 4 bytes. So int *a + int b[4] + int d = 20 offset?
is it the meaning of f->c.e->c.e[0]? is there f->c.e->c.e[3]?  f->c.e->c.e[4]? f->c.e->c.e[5]?
I am confused because usually for a pointer variable say k, I always see k->x, k->y, k->l  to refer to the variables within a struct when the variable k is pointing to the struct variable. However in this case, I see the notation of c.e->c.e[0].a[0]. Is e[0].a[0] valid? I guess e[0] is not a pointer then, since if it is a pointer e[0] must always use the -> notation to refer to a variable within a struct it pointing to, but since it uses (dot .) instead of (arrow ->), e[0].a[0] so I guess e[0] in this case is not a pointer right?
then I am little confused as to what is the meaning of c.e[0].a[0] in my given struct X, struct Y, and the given pointer variable f here.

A: c.e is a pointer to a struct X, so c.e[0] is the struct X pointed to by c.e.
If c.e is a pointer to the first element of an array of 4 struct Y, the 4 elements of this array could be referred to as c.e[0], c.e[1], c.e[2] and c.e[3].
For all pointers p, p[0] is equivalent to *p or *(p + 0) (or even 0[p]).
In this case, f->c.e->c.e[0].a[0] is equivalent to f->c.e->c.e->a[0] and *f->c.e->c.e->a. Which syntax is used is a question of style and readability. The array syntax using [] is usually more readable when the index is or can be different from zero, in case of pointers to single objects, the -> syntax is preferred.
The actual implementation details, such as pointer and integer sizes is irrelevant here, but bear in mind that the offset of a member in a structure may be affected by alignment constraints: for example in most current 64-bit systems, an int still has 4 bytes but a pointer uses 8 bytes, so the offset of e in struct Y must be aligned on a multiple of 8, hence is 8, not 4. 4 padding bytes are inserted between d and e. Note also that if d is meant to store the number of elements in the array pointed to by e, it should probably be defined with type size_t.

A: The confusion comes from the multiple ways of using pointers in C.
Declaring a simple array goes as follow:
<type> <name>[<size>];
// More concretely
int array_of_ints[5];
// Accessing its elements is straightforward
array_of_ints[0] = 42;

But what if you can't know the size in advance? You'd have to allocate memory with e.g. malloc which gives you a pointer to the beginning of the array:
int * array_of_ints = malloc(sizeof(int) * 5);
// Access its elements the same way as arrays declared on the stack
array_of_ints[0] = 42;

How come the same syntax can be used for both types (int[5] vs. int *)?
This is because under the hood the compiler treats it the exact same way. The name of the array is actually a pointer to its first element, as we can see here:
void foo(int * array)
{
    printf("%d\n", *array); // *array and array[0] are interchangeable
}

int bar()
{
    int array[5];
    array[0] = 42;
    foo(array);
}

So an array can be decayed into a pointer. And the language lets you use the [] operator because the compiler actually translates it using pointer arithmetic:

array[0] is the same as *array but, more precisely, the same as *(array + 0).

So how do you know if you have a pointer to a single value or a pointer to a value that's the first value of an array? Well, without context, you can't. From an isolated function's perspective, you can't know if taking a char * parameter means it is a string argument or a pointer to a single char variable. It's up to the developers to make it clear, either by passing the size of the array along with it, or naming the variable correctly (char * str vs. char * c for instance), writing documentation, etc.


text:
Q: Showing $\cos(t^2)$ is not a Characteristic Function Usually when we try to show a function is not a characteristic function, we would prove it is not uniformly continuous. I am wondering if there is any other way to show $\cos(t^2)$ is not a characteristic function.
$%fooling edit check$

A: Introduce the notation $c(t)=\cos(t^2)$. By Bochner's theorem, every determinant $D(t)$ should be nonnegative, where
$$
D(t)=\text{det}\begin{pmatrix}c(0) & c(t) & c(2t)\\ c(-t) & c(0) & c(t)\\ c(-2t) & c(-t) & c(0)\end{pmatrix}.
$$
Since $c(t)=c(-t)$ for every $t$, $D(t)=(1-c(2t))E(t)$ with $E(t)=1-2\cos(t^2)^2+\cos(4t^2)$.
For $t=1$, $E(1)=1-2\cos(1)^2+\cos(4)=-0.24...$ hence $D(1)<0$.
Alternatively, $E(t)=-6t^4+O(t^8)$ when $t\to0$. Or, $E(t)=-2\sin^2(t^2)(1+2\cos(2t^2))$.

A: Hint: Put $\varphi(t)=\cos(t^2)$.
If $X$ is a random variable with this "characteristic function", we'd have
$$\mathbb{E}(X^2)=-\varphi^{\prime\prime}(t)|_{t=0}=0.$$


text:
Q: Rewriting this Line from Objective C to Swift I know this is a little trivial but for the life of me I can't seem to get this line of Objective-C Code right in Swift.
Any Ideas?
Obj C Code:
CardView *view = (CardView *)draggableView;

I tried:
let view : CardView = draggableView(CardView)

I'm probably forgetting something small.

A: Try -
let view = draggableView as! CardView

A: let view = draggableView as CardView

See type casting https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html

A: Try
let view = draggableView as! CardView

That should cast it to a CardView.


text:
Q: Can I write "the model due to X et al"? Until ten minutes ago I thought sentences like "The model due to X et al. (2016) explains Y and Z" were common in academic writing.  Our post-doc raised doubt about the phrase's correctness, and Googling it I find very few uses. None of them I can confirm were written by a native speaker.
So, is that a common/correct way of saying X et al. proposed the model in their paper from 2016, and if not, what are alternatives?

A: Due to in this sense is ordinarily used to express the cause of an event or state:

Our success was due to our superior model.
  Icecap melting due to global warming will have far-reaching consequences.

I have seen this use of due to to express the origin or creator of an entity, but it grates on my ear. We certainly do not say that Hamlet is "due to" Shakespeare or that the General Theory of Relativity is "due to" Einstein, and your example seems similar to me. I advise you to avoid this and say something like what Stephen Kolassa suggests:

The model proposed by X et al. (2016) ...

—or "proposed in" or "put forward by/in" or "described by/in" or whatever is most appropriate to the circumstances.
By the way, this has nothing to do with the controversial question, discussed here, of whether due to phrases and clauses may be employed adverbially.

A: My grammar is not great, but I believe in your example "X et al. (2016)" is a noun phrase. If we replace it with another noun phrase "the incredible John Doe"  we get "The model due to the incredible John Doe explains Y and Z." This does not seem as nice as "The incredible John Doe model explains Y and Z".


text:
Q: Missing $ in citation I'm using jabref and the apacite package to create my citation. In my term paper I'd like to cite a Eurostat website, and attempt to add this as a "misc" citation, which I will put in in below. However, when running the code I get the error "! Missing $ inserted.<inserted text>$ ...plained/index.php?title=Asylum_statistics}. I've attempted to put in $ at the point it refers to and around all the numbers in the citation, but the same error still persist. I've also attempted to create the citation simply in notepad rather than using jabref, without any luck. Any clue as to how to solve this?
Citation:
@Misc{EuroStatImg,
author = {Eurostat},
title  = {{Number of asylum applicants (non-EU-27 citizens), EU-27, 2008-2019}},
url    = {{https://ec.europa.eu/eurostat/statistics-explained/index.php?title=Asylum_statistics}},
}

Code in latex (TexMaker)
    \documentclass{report}
    \title{The EU's common asylum policy, and the end of the Dublin Agreement}
    \author{Put in Candidat Number}
    \usepackage{apacite}
    \begin{document}
    \maketitle
    \newpage
    Lorem Ipsum \cite{EuroStatImg}

    \bibliography{KilderTermPaper}
    \bibliographystyle{apacite}
    \end{document}


text:
Q: Twisted will not send data back only if I use async DB ops After struggling with inlineCallbacks and yield of twisted/txredisapi, I can save my data into redis. Thanks to author of txredisapi. Now I met a new issue, socket server will not send back to client before/after saving into DB.
Twisted offers simple socket server as following:
from twisted.internet import protocol, reactor

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data) ### write back

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

reactor.listenTCP(8000, EchoFactory)
recctor.run()

My code is similiar, only with additional DB ops.
#!/usr/bin/env python

import time
import binascii
import txredisapi

from twisted.internet import defer
from twisted.internet import protocol, reactor
from twisted.internet.protocol import Factory
from twisted.enterprise import adbapi
from twisted.python import log

from dmpack import Dmpack
from dmdb import Dmdb
from dmconfig import DmConf

dm = Dmpack()
conf = DmConf().loadConf()
rcs = txredisapi.lazyConnection(password=conf['RedisPassword'])
dbpool = adbapi.ConnectionPool("MySQLdb",db=conf['DbName'],user=conf['DbAccount'],\
    passwd=conf['DbPassword'],host=conf['DbHost'],\
    use_unicode=True,charset=conf['DbCharset'])

def getDataParsed(data):
    realtime = None
    period = None
    self.snrCode = dm.snrToAscii(data[2:7])
    realtime = data[7:167] # save it into redis
    period = data[167:-2] # save it into SQL
    return (snrCode, realtime, period)

class PlainTCP(protocol.Protocol):
    def __init__(self, factory):
        self.factory = factory
        self.factory.numConnections = 0
        self.snrCode = None
        self.rData = None
        self.pData = None
        self.err = None

    def connectionMade(self):
        self.factory.numConnections += 1
        print "Nr. of connections: %d\n" %(self.factory.numConnections)
        self.transport.write("Hello remote\r\n") # it only prints very 5 connections.

    def connectionLost(self, reason):
        self.factory.numConnections -= 1
        print "Nr. of connections: %d\n" %(self.factory.numConnections)

    @defer.inlineCallbacks
    def dataReceived(self, data):
        global dbpool, rcs
        (self.snrCode,rDat,pDat) = getDataParsed(data)

        if self.snrCode == None or rDat == None or pDat == None:
            err = "Bad format"
        else:
            err = "OK"
        print "err:%s"%(err) # debug print to show flow control
        self.err = err

        self.transport.write(self.snrCode)
        self.transport.write(self.err)
        self.transport.write(rDat)
        self.transport.write(pDat)
        self.transport.loseConnection()

        if self.snrCode != None and rDat != None and pDat != None:
            res = yield self.saveRealTimeData(rcs, rDat)
            res = yield self.savePeriodData(dbpool, pDat, conf)

        print "err2:%s"%(err)  # debug print to show flow control

    @defer.inlineCallbacks
    def saveRealTimeData(self, rc, dat):
        key = "somekey"
        val = "somedata"
        yield rc.set(key,val)
        yield rc.expire(key,30)

    @defer.inlineCallbacks
    def savePeriodData(self,rc,dat,conf):
        query = "some SQL statement"
        yield rc.runQuery(query)

class PlainTCPFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return PlainTCP(self)

def main():
    dmdb = Dmdb()
    if not dmdb.detectDb():
        print "Please run MySQL RDBS first."
        sys.exit()

    log.startLogging(sys.stdout)

    reactor.listenTCP(8080, PlainTCPFactory())
    reactor.run()

if __name__ == "__main__":
    main()

And clip of my client, which is a simple client:
def connectSend(host="127.0.0.1",port=8080):
    global packet
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, port))
        s.sendall(''.join(packet))
        data = s.recv(1024)
        s.close()
        print 'Received', repr(data)
    except socket.error, err:
        print "Remote socket is not available: %s"%str(err)
        sys.exit(1)

The current status is:

*

*If disable @defer.inlineCallbacks and yield opertions of dataReceived(), both self.transport.write() inside of connectionMode() and dataReceived() can output data to clients.

*If we enabled @defer.inlineCallbacks and two yield DB ops of SQL/Redis, then self.transport.write() inside of connectionMode() prints every 5 connections, and dataReceived() will not output any data to clients.

*the debug print statements will print on log regardless of @defer.inlineCallbacks anyway.

I was told that dataReceived() should not be @defer.inlineCallbacks. But it doesn't change anything if I removed that decoration.
I am thinking if gevent can help me out of this unpredicted behavior. I am twisted into an endless tornado, cyclone .....
Anyone who has similiar experience, please help me. Thanks.

A: By changing function as following, the code works.
#COMMENT OUT decorator of @defer.inlineCallbacks

def dataReceived(self, data):
    global dbpool, rcs
    (self.snrCode,rDat,pDat) = getDataParsed(data)

    if self.snrCode == None or rDat == None or pDat == None:
        err = "Bad format"
    else:
        err = "OK"
    print "err:%s"%(err) # debug print to show flow control
    self.err = err

    self.transport.write(self.snrCode)
    self.transport.write(self.err)
    self.transport.write(rDat)
    self.transport.write(pDat)
    self.transport.loseConnection()

    if self.snrCode != None and rDat != None and pDat != None:
        self.saveRealTimeData(rcs, rDat)
        self.savePeriodData(dbpool, pDat, conf)
        # Removing yield before DB ops

    print "err2:%s"%(err)  # debug print to show flow control

@defer.inlineCallbacks
def saveRealTimeData(self, rc, dat):
    print "saveRedis"
    key = "somekey"
    val = "somedata"
    yield rc.set(key,val)
    yield rc.expire(key,30)

@defer.inlineCallbacks
def savePeriodData(self,rc,dat,conf):
    print "save SQL"
    query = "some SQL statement"
    yield rc.runQuery(query)

If we keep @defer.inlineCallbacks and yield in dataReceived. The connection is closed before second DB op. Therefore no data is output to connection. Maybe is caused by inlineCallbacks decorator.
By removing this, the flow control is simple and straightforward.
However, I still can get why I can not add inlineCallbacks if there are two deferred DB ops. This time they don't need deferred?


text:
Q: How can I set an envariable for all apps *permanently* in MacOS? I would like to set an envariable that will be referenced by an application that's not invoked via the command line, but rather by double-clicking its icon somewhere. The only way I know to do this is with
launchctl setenv VARIABLE value

which does the job, but whose effect terminates on reboot. Is there any way I can get this effect permanently, i.e., so that people don't have to remember to do it again whenever the machine reboots?
(In days of yore I could get the effect I need by putting the above statement in ~/launchd.conf, but that feature "was removed for security considerations". And note that it's not enough to put a launchctl command in .bashrc or the like, because my target users may never start a shell.)


text:
Q: Android autocomplete matching options I am using an AutoCompleteTextView in my app which gives countries names suggestions. My autocomplete is matching the entered text with every word in the suggestions list. For example, if I enter the two letters "ar", I get "Saudi Arabia" as one of the suggestions.
Is there any way to make the AutoCompleteTextView tries to match only starting from the first word? i.e. the suggestion must start with entered text, in case of my previous example, I get suggestions like "Armenia", "Argentina" & "Aruba" only.

A: The problem is the Filter implementation within ArrayAdapter first checks if the string starts with the search constraint, and then splits the string and checks each individual word.
From ArrayAdapter.java:
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
    newValues.add(value);
} else {
    final String[] words = valueText.split(" ");
    final int wordCount = words.length;

    // Start at index 0, in case valueText starts with space(s)
    for (int k = 0; k < wordCount; k++) {
        if (words[k].startsWith(prefixString)) {
            newValues.add(value);
            break;
        }
    }
}

As Daniel mentioned, you will need to implement your own adapter that implements Filterable. I've created an example that achieves the behavior you're looking for. You can find it here. It reuses most of the code within ArrayAdapter, but omits the part that splits the strings.

A: You need to write an adapter, which supplies the items, and implements the Filterable interface.
For using the Filterable in the adapter, see this gist.
Basically you need to do a check with abc.startsWith(xyz), and filter the results based on that.


text:
Q: Emacs php-mode and paredit I would like to use paredit in combination with php-mode, but it doesn't add a closing curly bracket "}". Might this have something todo with the fact that an electric brace is bound to "{"? And how could I overwrite this?
Thanks.

A: Some time ago, I wrote such a thing for C, but you can easily use it for PHP as well:
(define-minor-mode c-helpers-minor-mode
  "This mode contains little helpers for C developement"
  nil
  ""
  '(((kbd "{") . insert-c-block-parentheses))
)

(defun insert-c-block-parentheses ()
  (interactive)
  (insert "{")
  (newline)
  (newline)
  (insert "}")
  (indent-for-tab-command)
  (previous-line)
  (indent-for-tab-command)
  )

(add-hook 'php-mode-hook 'c-helpers-minor-mode)

A: Using paredit is php-mode is a bad idea - it's mostly suited for Lisp code editing. There is a very nice alternative for general purpose development though - autopair-mode. It's very easy to use and inserts braces, brackets and quotes in a manner similar to the one present in most IDEs.

A: In my experience, autopair-mode felt extremely sluggish when a large number of buffers were open (plus, paredit-mode ensures that delimiters are never unbalanced, unlike autopair-mode). So if, like me, you absolutely want to use paredit-mode and nothing else will do, have a look at this answer. In the elisp snippet given there, just replace slime-repl-mode-map and slime-repl-mode-hook with the corresponding variables for php (most likely php-mode-map and php-mode-hook)


text:
Q: Rails Javascript compression/minification on respond_to javascript response? Greetings Rails and Javascript Gurus!
I have a project where I am returning a large javascript file in a
respond_to do |format|
   format.js
end

block.
I am trying to figure out how I can minify or compress the .js response since the .js.erb view is full of comments and varies in size based on the results from the controller.
Anyone have any ideas?

A: well, maybe I have a solution:
respond_to do |format|
  format.js { self.response_body = minify(render_to_string) }
end

This perfectly works. Of course that the key is the minify method. You will find a lot of JS minifiers around. For example you can use this one (well if license permits): http://github.com/thumblemonks/smurf/raw/master/lib/smurf/javascript.rb - it is based on Crockford's jsmin.c.
If you put this file into your lib, require it, your minify method can look like this:
def minify(content)
  min = Smurf::Javascript.new(content)
  min.minified
end

Hope that it helped you.
If you plan to do minifying automatically then you probably should go for a piece of middleware. Surprisingly I was not able to find any (there are many aimed to the CSS/JS but it's about static assets not dynamic content) but it would not be such a problem to write it.

A: For rails 3 using the built in Uglifier method (the default for the assets pipeline)
See Radek's code above and just swap this in.
  def minify(content)
    Uglifier.new.compile(content)
  end

A: For Rails 4:
render js: Uglifier.new.compile(render_to_string)


text:
Q: How to stop Infinity showing during input I have created a form which works out a sum depending on the users input, this works fine but during the input stage i get the infinity property displayed in the total. Is there anyway of avoiding this?
I'm by no means a Javascript expecrt so any help would be appreciated. Here is the code.

    <form id="convert">
        <input type="text" name="child"  onkeyup="formChanged()" onchange="formChanged()"/>
        <input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>

    </form>

A: Don't divide by zero.
What you want to do when second is zero is up to you. But probably the easiest way to handle it is to just not do the calculation and not write anything in final unless you have a non-zero value from second.
In addition, you might want to check for NaN as well. If somebody writes a something in either textbox that is not actually a number, you will end up with NaN% in your output. (here you can use isNaN or you can compare the results of parsing your values with NaN).
So you could do something like:
var first = parseFloat(document.getElementsByName("child")[0].value);
var second = parseFloat(document.getElementsByName("parent")[0].value);
if (first !== NaN && second) {    // note NaN and 0 are both falsy
    // do your calculation here
}

A: You're going to need to do some validation on your values first. Your calculation only makes sense with numeric values and you're going to have to ensure that you don't try to calculate it if your second variable == 0.

A: I think that will work for you.

        <form id="convert">
           <input type="text" name="child"  onkeyup="formChanged()" onchange="formChanged()"/>
           <input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>

     </form>

Thanks

A: In this case, I wouldn't try to parse/validate the inputs. Do as few as possible, and assume valid inputs.
Just test wether you get a valid output, before showing the result.
function isValidNumber(v){
    //!NaN && !Infinity
    return v===v && v !== Infinity && v !== -Infinity;
}

//cast the inputs to a valid number
function number(v){
    //return +String(v).replace(",", ".");
    return +v;
    //return +v || 0;
}

function formChanged() {
    var first = document.getElementsByName("child")[0].value;
    var second = document.getElementsByName("parent")[0].value;

    var result = 100 * number(first) / number(second);

    document.getElementById("final").innerHTML = isValidNumber(result)?
        Math.floor(result) + "%": //I have a valid result
        "";     //values have changed, but sth. went wrong
}


text:
Q: VBA Split data by new line word I am trying to split data using VBA within word.
I have got the data using the following method
d = ActiveDocument.Tables(1).Cell(1, 1).Range.Text

This works and gets the correct data. Data for this example is
This
is
a
test

However, when I need to split the string into a list of strings using the delimiter as \n
Here is an example of the desired output
This,is,a,test

I am currently using
Dim dataTesting() As String
dataTesting() = Split(d, vbLf)
Debug.Print dataTesting(0)

However, this returns all the data and not just the first line.
Here is what I have tried within the Split function

*

*\n

*\n\r

*\r

*vbNewLine

*vbLf

*vbCr

*vbCrLf

A: Word uses vbCr (ANSI 13) to write a "new" paragraph (created when you press ENTER) - represented in the Word UI by ¶ if the display of non-printing characters is activated.
In this case, the table cell content you show would look like this
This¶
is¶
a¶
test¶

The correct way to split an array delimited by a pilcro in Word is:
Dim d as String
d = ActiveDocument.Tables(1).Cell(1, 1).Range.Text
Dim dataTesting() As String
dataTesting() = Split(d, vbCr)
Debug.Print dataTesting(0)  'result is "This"

A: You can try this (regex splitter from this thread)
Sub fff()
    Dim d As String
    Dim dataTesting() As String

    d = ActiveDocument.Tables(1).Cell(1, 1).Range.Text
    dataTesting() = SplitRe(d, "\s+")

    Debug.Print "1:" & dataTesting(0)
    Debug.Print "2:" & dataTesting(1)
    Debug.Print "3:" & dataTesting(2)
    Debug.Print "4:" & dataTesting(3)
End Sub

Public Function SplitRe(Text As String, Pattern As String, Optional IgnoreCase As Boolean) As String()
    Static re As Object

    If re Is Nothing Then
        Set re = CreateObject("VBScript.RegExp")
        re.Global = True
        re.MultiLine = True
    End If

    re.IgnoreCase = IgnoreCase
    re.Pattern = Pattern
    SplitRe = Strings.Split(re.Replace(Text, ChrW(-1)), ChrW(-1))
End Function

If this doesn't work, there may be strange unicode/Wprd characters in your Word doc. It may be soft breaks, for instance. You could try to not split with "\W+" in stead of "\s+". I cannot test this without your document.

A: Dim dataTesting() As String
dataTesting() = Split(d, vbLf)
Debug.Print dataTesting(0)

works fine and thank you very much for your example,
for why it have returned a whole array is because you have used 0 as index, in many programming languages 0 is the whole array, so the first element is ,
so in my case counting from 1 this perfectly split a string that I had troubles with.
To be more exact this is how it was used in my case
Dim dataTesting() As String
    dataTesting() = Split(Document.LatheMachineSetup.Heads.Item(1).Comment, vbCrLf)
    MsgBox (dataTesting(1))

And that comment is a multiline string.
Image
So this msg box returned exactly first line.


text:
Q: CryptoJS using actual key, not password Trying to encrypt a string using CryptoJS and an actual key (not passphrase).
Documentation says:

For the key, when you pass a string, it's treated as a passphrase and
used to derive an actual key and IV. Or you can pass a WordArray that
represents the actual key. If you pass the actual key, you must also
pass the actual IV.

But I could not find any examples on how to pass a WordArray and IV.
I need it to be a key because it will be pre-shared. I'm trying to validate by decrypting using https://www.devglan.com/online-tools/aes-encryption-decryption


text:
Q: SQL query not returning expected amount of subscribers I've been trying variations of this SQL query:
SELECT
  c.Id
, c.Email
, c.RecordTypeId
, o.CreatedDate
, o.Name
, o.StageName as Stage
, ca.Subject
, ca.Status
FROM Contact_Salesforce c
JOIN Opportunity_Salesforce o ON c.ID = o.agent__c
JOIN Case_Salesforce ca ON c.ID = ca.contactid

to join data from 3 separate synchronized DEs. When I filter the DEs on the fields I'm targeting I return records that are closer to expected but when I'm using the SQL I'm only returning a fraction of that amount.
I'm using the contact as my ID and sendable Email address and the opportunities and Case to filter further. Am I missing something? Any workarounds for combining 3 synced DEs and then filtering from there?

A: When you use a JOIN clause, it is using an INNER JOIN where it will only return records that have matching values in both synchronized data extensions.
When you filter a synchronized data extension, you are only filtering on one data extension without matching any values from any other data extension. This will return a larger record size.
In your case, you are only returning matching values from Contact and Opportunity on ContactId = Agent__c (which is a custom field in Opportunity). Also doing returning matching values on Case and Contact on ContactId.
It could be very possible that not all of your Contacts are in the Opportunity and Case objects.
See the diagram below on JOIN statements.


text:
Q: Undefined propery i'm getting the following error.
i cant figure it out what is wrong with this code.
there is something that i missed or forget.
can anybody please help me? i'm stuck at the moment.
he keeps saying there something with the array.
Notice: Undefined property: Cms::$contant_types in C:\xampp\htdocs\PassieCMS\app\cms\models\m_cms.php on line 34

Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\PassieCMS\app\cms\models\m_cms.php on line 34

<?php

/*
    CMS Class
    Handle CMS task, allowing admins to view/edit content
*/

class Cms
{
    private $content_types = array('wysiwyg', 'textarea', 'oneline');
    private $FP;

    function __construct()
    {
        global $FP;
        $this->FP = &$FP;
    }

    function clean_block_id($id)
    {
        $id = str_replace(' ', '_', $id);
        $id = str_replace('-', '_', $id);
        $id = preg_replace("/[^a-zA-Z0-9_]/", '',$id);
        return strtolower($id);
    }

    function display_block($id, $type = 'wysiwyg')
    {
        // clean id
        $id = $this->clean_block_id($id);

        // check for valid type
        $type = strtolower(htmlentities($type, ENT_QUOTES));
        if (in_array($type, $this->contant_types) == FALSE)
        {
            echo "";
            return;
        }

        // get content
        $content = "content here...";

        // check login status
        if ($this->FP->Auth-checkLoginStatus())
        {
            if($type == 'wysiwyg') { $type2 = 'WYSIWYG';}
            if($type == 'textarea') { $type2 = 'Textarea';}
            if($type == 'oneline') { $type2 = 'One Line';}

            $edit_start = '
';
            $edit_type = '' . $type2 . '';
            $edit_link = 'Bewerken';
            $edit_end = '
';

            echo $edit_start . $edit_type;
            echo $edit_link . $content . $edit_end;
        }
        else
        {
            echo $content;
        }
    }
}

and the index file is
<?php include ("app/init.php");?>
<!doctype html>

<meta charset="utf-8">
<title>PassieCMS</title>
<link href="resources/css/style.css" rel="stylesheet" type="text/css">
<?php $FP->head(); ?>

<body class="home <?php $FP->body_class(); ?>">

    <?php $FP->toolbar(); ?>

Website

Home

Test link

Longer Text Link

Contact us

<?php $FP->Cms->display_block('content-header','oneline'); ?>

                <?php $FP->Cms->display_block('content-maincontent'); ?>

                <?php $FP->Cms->display_block('content-quote'); ?>
                <?php $FP->Cms->display_block('content-attribution'); ?>

            Copyright 2014 PassieCMS | <?php $FP->login_link();?> Login optie 2

Thank you all for your time

A: if (in_array($type, $this->contant_types) == FALSE)

You have a typo, you have declared it as content_types above. This should work:
if (in_array($type, $this->content_types) == FALSE)


text:
Q: Function to retrieve the header destination address from a packet in windows XP I am interested in retrieving the destination address that an inbound packet is sent to. For example on Linux you can utilize recvmsg:
res = recvmsg(socket, &msghdr, 0);
get_cmsg = CMSG_FIRSTHDR(msghdr);
struct in_pktinfo *get_pktinfo = (struct in_pktinfo *)CMSG_DATA(get_cmsg);
printf(" - Header destination address (get_pktinfo.ipi_addr)=%s\n", inet_ntoa(pktinfo.ipi_addr));

Steps have been skipped to save many many lines
The key here is that recvmsg is easy to use. Similar functions are implemented for Windows XP like recvfrom but Windows does not seem to implement the recvmsg function.
Similarly named functions exist, like the WSARevcMsg function, but according to the linked documentation it is only included in Windows Vista and above.
Is there a way I can get the header destination address from a packet in Windows XP?

I know that using XP is bad and old, unfortunately we are attempting to fix a bug on a legacy product, so at this time we are unable to simply upgrade.

A:
windows does not seem to implement the recvmsg function.

Actually, it does (well, an equivalent, anyway):
WSARecvMsg function

Similar functions have been revamped like the WSArevcMsg but these are only included in windows vista and above.

You can't always trust MSDN documentation.  When Microsoft officially drops support for a Windows version (like XP), it tends to remove references to that version from MSDN, including "Minimum supported ..." requirements of API functions (which annoys many programmers).  The key point is supported.  Microsoft does not support older Windows versions.
WSARecvMsg() was first introduced in XP, which was EOL'ed in 2014 and many references to it were stricken from MSDN documentation (here is proof from 2013 when the WSARecvMsg() documentation stated XP and not Vista was the "Minimum supported client").

As stated in the WSARecvFrom() documentation:

Note The function pointer for the WSARecvMsg function must be obtained at run time by making a call to the WSAIoctl() function with the SIO_GET_EXTENSION_FUNCTION_POINTER opcode specified. The input buffer passed to the WSAIoctl function must contain WSAID_WSARECVMSG, a globally unique identifier (GUID) whose value identifies the WSARecvMsg extension function. On success, the output returned by the WSAIoctl function contains a pointer to the WSARecvMsg function. The WSAID_WSARECVMSG GUID is defined in the Mswsock.h header file.

WSAID_WSARECVMSG is defined as:
#define WSAID_WSARECVMSG \
    {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}

aka {F689D7C8-6F1F-436B-8A53-E54FE351C322} in text format.
For example:
SOCKET sckt = ...;
LPFN_WSARECVMSG lpWSARecvMsg = NULL;

GUID g = WSAID_WSARECVMSG;
DWORD dwBytesReturned = 0;
if (WSAIoctl(sckt, SIO_GET_EXTENSION_FUNCTION_POINTER, &g, sizeof(g), &lpWSARecvMsg, sizeof(lpWSARecvMsg), &dwBytesReturned, NULL, NULL) != 0)
{
    // WSARecvMsg is not available...
}

Then, to use it:
BYTE buffer[...];
DWORD dwBytesRecv;

WSABUF msgbuf;
memset(&msgbuf, 0, sizeof(msgbuf));
msgbuf.len = sizeof(buffer);
msgbuf.buf = (char *) buffer;

// call WSA_CMSG_SPACE() once for each option you enable
// on the socket that can return data in WSARecvMsg()...
int size = 0;
if (... IP_PKTINFO is enabled ...)
    size += WSA_CMSG_SPACE(sizeof(struct in_pktinfo));
if (... IPV6_PKTINFO is enabled ...)
    size += WSA_CMSG_SPACE(sizeof(struct in6_pktinfo));
// other packet options as needed...

BYTE *controlbuf = (BYTE *) malloc(size);

SOCKADDR_STORAGE *addrbuf = (SOCKADDR_STORAGE *) malloc(sizeof(SOCKADDR_STORAGE));

WSAMSG msg;
memset(&msg, 0, sizeof(msg));
msg.name = (struct sockaddr *) addrbuf;
msg.namelen = sizeof(SOCKADDR_STORAGE);
msg.lpBuffers = &msgbuf;
msg.dwBufferCount = 1;
msg.Control.len = size;
msg.Control.buf = (char *) controlbuf;

if (lpWSARecvMsg(sckt, &msg, &dwBytesRecv, NULL, NULL) == 0)
{
    // addrbuf contains the sender's IP and port...
    switch (addrbuf->ss_family)
    {
        case AF_INET:
        {
            struct sockaddr_in *addr = (struct sockaddr_in*) addrbuf;
            // use addr as needed...
            break;
        }

        case AF_INET6:
        {
            struct sockaddr_in6 *addr = (struct sockaddr_in6*) addrbuf;
            // use addr as needed...
            break;
        }
    }

    WSACMSGHDR *msghdr = WSA_CMSG_FIRSTHDR(&msg);
    while (msghdr)
    {
        switch (msghdr->cmsg_type)
        {
            case IP_PKTINFO: // also IPV6_PKTINF
            {
                // must call setsockopt(sckt, IPPROTO_IP, IP_PKTINFO, TRUE) beforehand to receive this for IPv4
                // must call setsockopt(sckt, IPPROTO_IPV6, IPV6_PKTINFO, TRUE) beforehand to receive this for IPv6

                switch (addrbuf->ss_family)
                {
                    case AF_INET:
                    {
                        struct in_pktinfo *pktinfo = (struct in_pktinfo *) WSA_CMSG_DATA(msghdr);
                        // use pktinfo as needed...
                        break;
                    }

                    case AF_INET6:
                    {
                        struct in6_pktinfo *pktinfo = (struct in6_pktinfo *) WSA_CMSG_DATA(msghdr);
                        // use pktinfo as needed...
                        break;
                    }
                }

                break;
            }

            // other packet options as needed...
        }

        msghdr = WSA_CMSG_NXTHDR(&msg, msghdr);
    }
}

free(addrbuf);
free(controlbuf);


text:
Q: CSS positioning breaks mouse events I made a barebones example of this here.
What causes this?  By just applying a z-index to a div (in the example, .spread), mouse events are completely gone.  In the plugin I'm working on, I need to use z-index for positioning, and I'd rather not make the user using my plugin try to work around this themselves in the future.
Basically, by simply applying
position:relative;
z-index:*anything less than 0)

Any and all mouse events will be nulled.  Even if I try to add a positive z-index to just the as, it still doesn't work.
How can I fix this so I can put negative z-indexes on divs while still allowing the contents of them to be clickable/hoverable/whateverable?
Edit:  Well I'm dumb.  I didn't know body had it's own z-index, I just figured it'd be under everything (because why would you want anything beneath the entire page, just display:none it) Thanks everyone!

A: I believe a negative z-index positions the element behind the document's <body>.
Try this instead:
.spread { z-index: 1; }
header  { z-index: 2; }

http://jsfiddle.net/uW9jk/3/

A: Don't use negative z-indexes. Changing the -2 in your example to a 0 or a 1 or anything else positive fixed the problem. Proof.

A: By setting a negative z-index your div element will be behind the body element, which by default have z-index: 0
This is confirmed by setting the z-index of the body. http://jsfiddle.net/uW9jk/5/
body{
    z-index: -3;
    position: relative;
}

Accordingly to docs.webplatform

Positive z-index values are positioned above a negative (or lesser value) z-index. Two objects with the same z-index are stacked
  according to source order. A positive value positions the element
  above text that has no defined z-index, and a negative value positions
  it below. Set this parameter to null to remove the attribute. The
  z-index property only applies to objects that have the position
  property set to relative or absolute. The property does not apply to
  windowed controls, such as select objects. Input from pointing
  devices, such as a mouse, does not penetrate through overlapping
  elements even if the elements are not visible. This is also true for
  positioned elements with a negative z-index unless:
The parent is a scrolling container (that is, its overflow property is
  set to auto or scroll). The parent is positioned (that is, its
  position property is set to absolute, relative, or fixed).

Correction: the body element have z-index: auto by default, but make sense to interpret auto being a 0 or positive index since everything below 0 will be behind it.

Note: Negative z-index values are CSS2.1 behavior, not allowed in CSS2 and earlier.
Negative z-index Support: Webkit 1.0 | Gecko(FF) 3.0 | IE 4.0 | Opera 4.0


text:
Q: Push Notifications not connecting to firebase messaging properly I am attempting to test out push notifications on my Iphone simulator. For some reason none of my tests seems to be going through. With the new updates on firebaseMessaging I also cannot figure out how to properly print the test notification to my terminal to see if it is connected properly. I am new to flutter and following a very outdated Udemy class. If anyone could maybe give some advice on where I may be going wrong, I would greatly appreciate it. Thank you in advance. Below is my pushnotification service.dart file.
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:driver/datamodels/jobdetails.dart';
import 'package:driver/globalvariables.dart';
import 'dart:io';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:driver/widgets/ProgressDialog.dart';

class PushNotificationService {

  final FirebaseMessaging fcm = FirebaseMessaging.instance;

  Future initialize(context) async {
    if (Platform.isIOS) {
      fcm.requestPermission(
        alert: true,
        announcement: false,
        badge: true,
        carPlay: false,
        criticalAlert: false,
        provisional: false,
        sound: true,
      );
    }

    FirebaseMessaging.onMessage.listen((event) {
      // fetchJobInfo(getJobID(message), context);
      (Map<String, dynamic> message) async => fetchJobInfo(getJobID(message), context);
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      // fetchJobInfo(getJobID(message), context);
      (Map<String, dynamic> message) async => fetchJobInfo(getJobID(message), context);
    });
  }

  Future<String> getToken() async {
    String token = await fcm.getToken();
    print('token: $token');

    DatabaseReference tokenRef = FirebaseDatabase.instance.reference().child('drivers/${currentFirebaseUser.uid}/token');
    tokenRef.set(token);

    fcm.subscribeToTopic('alldrivers');
    fcm.subscribeToTopic('allusers');
  }

  String getJobID(Map<String, dynamic> message){

    String jobID = '';

    if(Platform.isAndroid){
      jobID = message['data']['job_id'];
    }
    else{
      jobID = message['job_id'];
      print('job_id: $jobID');
    }

    return jobID;
  }

  void fetchJobInfo(String jobID, context) {
    //show please wait dialog
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) =>
          ProgressDialog(status: 'Fetching Details...',),
    );

    DatabaseReference jobRef = FirebaseDatabase.instance.reference().child(
        'jobRequest/$jobID');
    jobRef.once().then((DataSnapshot snapshot) {
      Navigator.pop(context);

      final assetAudioPlayer = AssetsAudioPlayer();
      if (snapshot.value != null) {
        assetAudioPlayer.open(Audio('sounds/sounds_alert.mp3'));
        assetAudioPlayer.play();

        double destinationLat = double.parse(
            snapshot.value['destination']['latitude'].toString());
        double destinationLng = double.parse(
            snapshot.value['destination']['longitude'].toString());
        String destinationAddress = snapshot.value['destination_address'];
        String paymentMethod = snapshot.value['payment_method'];

        JobDetails jobDetails = JobDetails();

        jobDetails.jobID = jobID;
        jobDetails.destinationAddress = destinationAddress;
        jobDetails.destination = LatLng(destinationLat, destinationLng);
        jobDetails.paymentMethod = paymentMethod;

        // showDialog(
        //     context: context,
        //     barrierDismissible: false,
        //     builder: (BuildContext context) => NotificationDialog(jobDetails: jobDetails,),
        // );
      }
    });
  }
}

A: There is a way how you can push notifications to simulator manually with Xcode cli and this way even looks easier to test notifications for Flutter/FireBase.
First you have to set up notification payload file e.g. notification.apns. The contents of the file:

{
    "Simulator Target Bundle": "<Your App bundle identifier>",
    "gcm.message_id": "random string",
    "aps": {
        "alert": "Push Notifications Test",
        "sound" : "default",
        "badge": 1,
    },
    "dataKey": "any data value to ise in the app"
}

The key is defining a property gcm.message_id - because FireBase Messaging service checks for it and only executes callbacks if it is present.
Once you have it ready, just run xcrun simctl push booted notification.apns and all the FBM callbacks will be executed.
Also, you can learn more about simulating notifications in this answer: How can I test Apple Push Notification Service without an iPhone?

A: Please see the latest doc link is below:-
Flutter Notifications

A: It is already answered, but with a picture. You can't get notifications to an iPhone simulator.

For iOS; you must have a physical  iOS device to receive messages.
Firebase Cloud Messaging integrates with the Apple Push Notification service (APNs), however APNs only works with real devices.


text:
Q: How to make only some text in a text-box read-only while allowing the rest to be edited I'm trying to use Javascript to make a text box that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. How can I do this in Javascript/jquery?

A: here is some thoughts
roughly a solution with jquery
html
<input type="text" id='myinput' value ="my text">

jquery
var orginal_text = $('#myinput').val();
var regular_expression = '/^' + orginal_text +'/' ;
$('#myinput').keyup(function(){
    var current_text = $('#myinput').val();
    if(current_text.match('^' + orginal_text +'') == null){
        $('#myinput').val(orginal_text + ' ' +current_text )
    }

})

http://jsfiddle.net/e5EDY/
with css
html
 <input type="text" id='my_sticky_text' value ="my text" readonly='readonly'>
<input type="text" id='myinput' value ="my text">

css
#my_sticky_text{
    position:absolute;
    left : 0px;
}

#myinput{
    position:absolute;
    left : 50px;
    border-left:none;
}

http://jsfiddle.net/kaf4j/
combination to retrieve the value
html
 <input type="text" id='my_sticky_text' value ="my text" readonly='readonly'>
<input type="text" id='myinput' value ="my text">

    <button id='getval'>get value</button>

css
#my_sticky_text{
    position:absolute;
    left : 0px;
}

#myinput{
    position:absolute;
    left : 50px;
    border-left:none;
}

jquery
$('#getval').click(function(){
   var sticky_text = $('#my_sticky_text').val();
    var user_text = $('#myinput').val();
alert (sticky_text + ' ' + user_text)

})

http://jsfiddle.net/YsNMQ/
what do we get from all this ?!.. simply  you cant acomplish what you want in a nice way .. and i cant imagine  a situation where i want to do so .
alternatives
1 - in the text-field label put the constant text .
2 - when the user submits the form capture the value of the text-field and add your text to it .
3- add a help note to the user that this input should be as follows (eg : mytext-yourtext)

A: Here's an attempt:

var readOnlyLength = $('#field').val().length;

$('#output').text(readOnlyLength);

$('#field').on('keypress, keydown', function(event) {
  var $field = $(this);
  $('#output').text(event.which + '-' + this.selectionStart);
  if ((event.which != 37 && (event.which != 39)) &&
    ((this.selectionStart < readOnlyLength) ||
      ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
    return false;
  }
});

<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />

This disables keys other than the left and right arrows for the read-only part. It also disables the backspace key when just at the end of the read-only part.
From what I've read, this won't work on IE <= 8.

Here it is in plain JavaScript (no JQuery):

function makeInitialTextReadOnly(input) {
  var readOnlyLength = input.value.length;
  field.addEventListener('keydown', function(event) {
    var which = event.which;
    if (((which == 8) && (input.selectionStart <= readOnlyLength)) ||
      ((which == 46) && (input.selectionStart < readOnlyLength))) {
      event.preventDefault();
    }
  });
  field.addEventListener('keypress', function(event) {
    var which = event.which;
    if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
      event.preventDefault();
    }
  });
}

makeInitialTextReadOnly(document.getElementById('field'));
<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />

A: Below is a modified version of John S's answer to prevent cut/paste operations (e.g. via right-click):
function makeInitialTextReadOnly(input) {
    var readOnlyLength = input.value.length;
    input.addEventListener('keydown', function(event) {
        var which = event.which;
        if (((which == 8) && (input.selectionStart <= readOnlyLength))
                || ((which == 46) && (input.selectionStart < readOnlyLength))) {
            event.preventDefault();
        }
    });
    input.addEventListener('keypress', function(event) {
        var which = event.which;
        if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
            event.preventDefault();
        }
    });
    input.addEventListener('cut', function(event) {
        if (input.selectionStart < readOnlyLength) {
            event.preventDefault();
        }
    });
    input.addEventListener('paste', function(event) {
        if (input.selectionStart < readOnlyLength) {
            event.preventDefault();
        }
    });
}

makeInitialTextReadOnly(document.getElementById('field'));

Fiddle: http://jsfiddle.net/p0jyktvu/3/


text:
Q: What is this kind of shell code in c or c++? i have this code
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
 char shellcode[]=
       "\x31\xc0"             /* xorl    %eax,%eax              */
       "\x50"                 /* pushl   %eax                   */
       "\x68""//sh"           /* pushl   $0x68732f2f            */
       "\x68""/bin"           /* pushl   $0x6e69622f            */
       "\x89\xe3"             /* movl    %esp,%ebx              */
       "\x50"                 /* pushl   %eax                   */
       "\x53"                 /* pushl   %ebx                   */
       "\x89\xe1"             /* movl    %esp,%ecx              */
       "\x99"                 /* cdql                           */
       "\xb0\x0b"             /* movb    $0x0b,%al              */
       "\xcd\x80"             /* int     $0x80                  */
     ;

    void main(int argc, char **argv)
    {
        char buffer[517];
        FILE *badfile;

        /* Initialize buffer with 0x90 (NOP instruction) */
        memset(&buffer, 0x90, 517);

        /* You need to fill the buffer with appropriate contents here */

        /* Save the contents to the file "badfile" */
        badfile = fopen("./badfile", "w");
        fwrite(buffer, 517, 1, badfile);
        fclose(badfile);
    }

i want to know and learn more about this kind of codes that calls expliot,what is that shell code?how can i learn to code that shells,i want to know exactly what does this code do.

A: Probably a too broad question but I'll provide some info for a novice anyway:
A shellcode is usually a series of instructions in a target-specific language that are "written" to memory and intended to be executed to gain privileges or manipulate data.
Shellcodes are extremely hardware, platform and version specific: if you have an x86 processor you'll have to target that ISA in order to get your code running once you "injected" or diverted the main program's execution to it.
Machine instructions are usually binary code (or hex, depending on how you represent the data) and to tell the machine what should it do next, you use an opcode. In the code above, you're exactly looking at opcodes which specify

*

*The instruction to be executed

*The operands on which it should be executed

That said: there's a lot you would need to learn on programming, reversing, architectures, system internals and security systems if you really want to tackle the security field.
As for what that code does: it enters a syscall and executes /bin/sh
#include <unistd.h>

void main()
{
        char *shell[2];

        shell[0] = "/bin/sh";
        shell[1] = NULL;

        execve(shell[0], shell, NULL);
}

Taken from http://www.enderunix.org/docs/en/bof-eng.txt
Good luck.

A: Page 315 of Hacking: The Art of Exploitation does a good job explaining what that code does.


text:
Q: React&Typescript Exclude from interface definition after many hours of test i ask you. i want define my interface object
export interface OptionPros {
    text: string;
    color?: string|undefined;
    fontStyle?: string|undefined;
    sidePadding?: number|undefined;
}

after, i will want create a type that use only "text" property, the other are optional.
type OO=Exclude<"color"|"fontStyle"|"sidePadding", OptionPros>

now it's all ok, but whe i try use this definition in props of my class react
file1.tsx
export interface OptionPros {
    text: string;
    color?: string|undefined;
    fontStyle?: string|undefined;
    sidePadding?: number|undefined;
}
type OO=Exclude<"color"|"fontStyle"|"sidePadding", OptionPros>

export interface DProps extends BaseProps {
    optionD: OO
}
export default class DDD <DProps> {
    static defaultProps = {
        optionD: {
            text: '',
            color: '#FF6384', // Default is #000000
            fontStyle: 'Arial', // Default is Arial
            sidePadding: 20 // Defualt is 20 (as a percentage)
        }
    };
    render() {
AAAA
}
 }

file2.tsx
 //i omit react and other inclusion or extension
 import.....
 export default class AAAA {
 render() {return(<DDD optionD={{text:"hello world"}}>AAAA</DDD >)}

and i have this messagge error
Type '{ text: string; }' is not assignable to type '{ text: string; color: string; fontStyle: string; sidePadding: number; }'.
  Property 'color' is missing in type '{ text: string; }'.
i can not understand why? i use typescript > 2.8 anche the ts documentation it's not very clear. Can someone help me to resolved and undestand my errors?

A: I believe I've succeeded in reproducing the error.  Your component declaration should be:
export default class DDD extends React.Component<DProps> { ... }
//                       ^^^^^^^^^^^^^^^^^^^^^^^

And if you want to exclude the color, fontStyle, and sidePadding properties from OptionPros, what you need is not Exclude (which just excludes one type from another) but the operation more commonly called Omit, defined and used as follows:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type OO=Omit<OptionPros, "color"|"fontStyle"|"sidePadding">

With these changes, I am no longer getting the error.


text:
Q: java.lang.NullPointerException with Android Java Apparently the problem is with line 62.If you comment that out then line 63 and so on.
I also tried a non array and it worked.
I cant see that any of the variables are nulled either.
Logcat says the problem is: java.lang.NullPointerException.
Here is my code so far:
package com.zxz.zxcdnd;

import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.widget.*;

public class MainActivity extends Activity
{

    //Player statistics
    int playerStatistics[];

    //Room statistics
    String roomStatistics[];
    int type = 1;

    //Player inventory
    int inventorySlot = 1;
    int playerInventoryNumbers[];
    String playerInventoryNames[];
    String playerInventoryAffectedStats[];

    //Index representation variables
    int name = 1,roomsConquered = 2,goldCoins = 3,stamina = 4,damage = 5,luck = 6,difficulty=3;

    //Random generator
    Random r = new Random();
    int dice;

    //List of available items
    int itemNumbers[] = {1,1,2,2,3,3,4,4,5,5};

    String itemAffectedStats[] = {"stamina","damage",
                                  "luck","damage",
                                  "stamina","damage",
                                  "damage","luck",
                                  "damage","stamina"};

    String itemNames[] = {"lemon","app",
                                   "ist","Bms",
                                   "Hateech","Lasacsyrup",
                                   "Picagger","Hompa",
                                   "Bori","Offipenser"};

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

        //Initialize important player variables
        startUp();

        //Create room
        initializeRoom();
    }

    void startUp()
    {
        //Initialize stamina, damage and luck
        playerStatistics[stamina] = r.nextInt(7-1) + 1; //LINE 62
        playerStatistics[damage] = r.nextInt(7-1) + 1; //LINE 63
        playerStatistics[luck] = r.nextInt(7-1) + 1;

        //Initialize player inventory
        playerInventoryNumbers[inventorySlot] = itemNumbers[r.nextInt(11-1) + 1];
        playerInventoryNames[inventorySlot] = itemNames[r.nextInt(11-1) + 1];
        playerInventoryAffectedStats[inventorySlot] = itemAffectedStats[r.nextInt(11-1) + 1];

        playerStatistics[damage] = playerStatistics[damage] + playerInventoryNumbers[inventorySlot];
        inventorySlot++;
    }

Thanks in advance! I owe alot.

A: You declared but didn't initialize your playerStatistics array, so it's null.  Try declaring it as:
int playerStatistics[] = new int[7];

or one more than your largest index possible.
You will need to do something similar with your other arrays, which also don't appear to be initialized.


text:
Q: Use Redis Cache in production environment i have a microservice (webapi .NET) to deploy with Docker in K8S.
Internally, in docker compose file, i use a image of Redis as cache.
In development environment everything is ok, my question is: in production which is the best practice? use an image of Redis in the pod, or reference to an external Redis service (es. Azure, AWS, etc)?
THanks for any advice

A: You can use Bitnami Helm Chart to deploy Redis in your Kubernetes environment.
It uses non-root Redis container image and is highly configurable. You can find more information about deployment options and configuration at their GitHub repo.


text:
Q: как сделать так чтобы автором коментария становился залогиненый User в django на данный момент при создании коментария необходимо выбрать Userа, в какую степь мне копать, чтобы я смог все сделать так, чтобы автор коментария если он вошел в аккаунт автоматически становился автором коментария?
вот мой код:
models.py
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
    # method adds url to redirect user after new post has been created

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.body

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})`

views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView
)
from .models import Post, Comment
from .forms import CommentForm

class PostDetailView(DetailView):
    model = Post

def add_comment(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post-detail',  pk=post.pk)
    else:
        form = CommentForm()
    template_name = 'blog/add_comment.html'
    context = {'form': form}
    return render(request, template_name, context)

forms.py
from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['user', 'body']

add_comment.html
{% extends 'blog/base.html'%}
{% load crispy_forms_tags %}

{% block content %}

        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">comment</legend>
                {{ form|crispy }}
            </fieldset>

                <button class="btn btn-outline-info" type="submit">Post</button>

        </form>

{% endblock %}

A: forms
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['body']

views
from django.contrib.auth.decorators import login_required

@login_required
def add_comment(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.user = request.user
            comment.save()
            return redirect('post-detail',  pk=post.pk)
    else:
        form = CommentForm()
    template_name = 'blog/add_comment.html'
    context = {'form': form}
    return render(request, template_name, context)

A: Ответ @m0nte-cr1st0 верный и хорош, но предложу и свой вариант. Он заключается в передаче в форму самого пользователя
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['body']

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        self.post = kwargs.pop('post', None)
        super().__init__(*args, **kwargs)

    def clean(self):
        if not self.user:
            raise ValidationError('No user in form')
        if not self.user.is_authenticated():
            raise ValidationError('User must be authentificated for add comment')
        if not self.post:
            raise ValidationError('Cannot add comment for non-post object')
        super().clean()

    def save(self, *args, **kwargs):
        self.instance.user = self.user
        self.instance.post = self.post
        return super().save()

Использование
# Для вьюхи вроде функции
def add_comment(request, *args, **kwargs):
    post = ....
    if 'POST' in request.method:
        form = CommentForm(request.POST, post=post, user=request.user)
        if form.is_valid(): form.save()
        .....
    ...

# Для generic
class CommentView(generic.<какой удобнее будет>):
    form_class = CommentView

    def get_form_kwargs(self, *args, **kwargs):
        res = super().get_form_kwargs(*args, **kwargs)
        res['user'] = self.request.user
        res['post'] = ... #код поиска поста
        retur res

В моем случае, проверкой данных занимается сама форма


text:
Q: Can I replace ActionBarActivity with AppCompatActivity in a Tabbed Activity in Android Studio? The following Tabbed Activity is created by Android Studio 1.2.2 Wizard, it works well in API 9, but someboyd told me that ActionBarActivity is deprecated,
so I hope to replace public class MainActivity extends ActionBarActivity implements ActionBar.TabListener with public class MainActivity extends AppCompatActivity implements ActionBar.TabListener , and stay all other code the same, is it OK?
Thanks!
package com.example.cuiwei.myapplication;

import java.util.Locale;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}

A: You can safely replace ActionBarActivity with AppCompatActivity.
As you can see in v7-appcompat source code from version v22.1.0 ActionBarActivity simply extends AppCompatActivity:
/**
 * @deprecated Use {@link android.support.v7.app.AppCompatActivity} instead.
 */
@Deprecated
public class ActionBarActivity extends AppCompatActivity {
}


text:
Q: django-notifs raising an exception: django.core.exceptions.FieldDoesNotExist: Notification has no field named 'timestamp' I'm trying to apply Notifications system to my django (version 3.2) app for  the first time using the tutorial: https://django-notifs.readthedocs.io/en/stable/index.html#
I'm stuck at the installation process. First I solved the (fields.E180) SQLite does not support JSONFields., using the documentation at: https://code.djangoproject.com/wiki/JSON1Extension
After running makemigrations, it worked fine. BUT after running manage.py migrate, it threw the following error:
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: Notification has no field named 'timestamp'.
Please help me out :(
A part of a full very long traceback (cannot embed images due to cruddy reputation):
File "C:\Users\Abdullah\Envs\DJANGO\lib\site-packages\django\db\migrations\migration.py", line 126
, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\Abdullah\Envs\DJANGO\lib\site-packages\django\db\migrations\operations\fields.py",
line 240, in database_forwards
from_field = from_model._meta.get_field(self.name)
File "C:\Users\Abdullah\Envs\DJANGO\lib\site-packages\django\db\models\options.py", line 610, in g
et_field
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Notification has no field named 'timestamp'


text:
Q: find value pair in json object using key element With reference to question posted here use jQuery's find() on JSON object
I have json object in which i'd like to search value of the element if i passed respective key element to it
Json:
{"RESPONSE":{"@xmlns":"","CODE":"0","SECODE":"0","TXNID":"17527","LASTBALANCE":"-12078.8","SURCHARGE":"2","CUSTOMERDETAILS":{"NAME":"Mr.ABC"}}}

I want to retrieve value Mr.ABC when i passed Name as a key to my function
Code:
console.log(getObjects(ContextObj, 'Name'));

function getObjects(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (i == key) {
            objects.push(obj);
        }
    }
    return objects;
}

It gives output now as
[ ]

A: Try this:
var data = {"RESPONSE":{"@xmlns":"","CODE":"0","SECODE":"0","TXNID":"17527","LASTBALANCE":"-12078.8","SURCHARGE":"2","CUSTOMERDETAILS":{"NAME":"Mr.ABC"}}};
function find_value(key, inner_key) {
    var value = "";
    $.each(data.RESPONSE, function (i, k) {
        console.log(i, key, i == key)
        if (i == key) {
            value = k;
            return false;
        }
    });
    if (inner_key) {
        if (value[inner_key]) {
            value = value[inner_key];
        }
    }
    return value;
}

Calling function:
find_value("LASTBALANCE");
find_value("CUSTOMERDETAILS", "NAME");

See DEMO here.

A: You need to call your code recursive for nested json keys like,
var s={"RESPONSE":{"@xmlns":"","CODE":"0","SECODE":"0","TXNID":"17527","LASTBALANCE":"-12078.8","SURCHARGE":"2","CUSTOMERDETAILS":{"NAME":"Mr.ABC"}}};
console.log(getObjects(s, 'NAME'));
console.log(getObjects(s, 'LASTBALANCE'));

function getObjects(obj, key) {
    var objects = [];
    for (var i in obj) {
        if(typeof obj[i] == 'object'){
            return getObjects(obj[i], key); // if it is an object then find the key recursively.
        }
        if (!obj.hasOwnProperty(i)) continue;

        if (i == key) {
            return obj[key];
        }
    }
    return '';
}

Working DEMO