text:
Q: Как передать список ListView в DialogFragment Подскажите пожалуйста, нужно передать ListView со списком Блютуз в DialodFragment, создание списка в layout работает корректно? но вот в Fragment открывается пустой прямоугольник без писка
public class MainActivity extends AppCompatActivity {

private BluetoothAdapter bluetoothAdapter;
private ListView listView;
private ArrayList<String> pairedDeviceArrayList;
private ArrayAdapter<String> pairedDeviceAdapter;
public static BluetoothSocket clientSocket;

private ImageView btnImageBluetooth;

DialogFragment bltDialog;

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

    listView = (ListView) findViewById(R.id.list_device);

    btnImageBluetooth = (ImageView) findViewById(R.id.btnImageBluetooth);
    btnImageBluetooth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            MyDialogFragment myDialogFragment = new MyDialogFragment();
            FragmentManager manager = getSupportFragmentManager();
            //myDialogFragment.show(manager, "dialog");

            FragmentTransaction transaction = manager.beginTransaction();
            myDialogFragment.show(transaction, "dialog");

            if (permissionGranted()) {

                bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (bluetoothEnabled()) {
                    findBluetooth();

                }
            }

        }
    });
}

private boolean bluetoothEnabled() {
    if (bluetoothAdapter.isEnabled()) {
        return true;
    } else {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 0);
        return false;
    }
}

private boolean permissionGranted() {

    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH)
            == PermissionChecker.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.BLUETOOTH_ADMIN) == PermissionChecker.PERMISSION_GRANTED) {
        return true;
    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN}, 0);
        return false;
    }
}

public void findBluetooth() {
    Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();

    if (pairedDevice.size() > 0) {
        pairedDeviceArrayList = new ArrayList<>();
        for (BluetoothDevice device : pairedDevice) {

            pairedDeviceArrayList.add(device.getAddress() + "/" + device.getName());
        }

        pairedDeviceAdapter = new ArrayAdapter<String>(this,
                R.layout.item_device, R.id.item_device_textView, pairedDeviceArrayList);

        Dialog dialog = new Dialog(MainActivity.this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                final String itemMAC = listView.getItemAtPosition(i).toString().split("/", 2)[0];

                new Thread() {
                    @Override
                    public void run() {

                        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(itemMAC);
                        try {

                            BluetoothSocket socket = device.createRfcommSocketToServiceRecord
                                    (device.getUuids()[0].getUuid());
                            socket.connect();
                            if (socket.isConnected()) {

                                Log.e("eee", "socket get");
                                clientSocket = socket;

                            } else {

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

                }.start();

            }
        });
    }
}
 }

public class MyDialogFragment extends DialogFragment {

ListView listView;

@SuppressLint("ResourceType")
public Dialog onCreateDialog(Bundle savedInstanceState) {
//  MainActivity ;

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   // builder.setView(R.id.list_device);
    builder.setTitle("Выберите ")
            .setItems(R.layout.item_device, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                }
            });

    return builder.create();
}

}

A: Передать виджет вряд ли получится в диалог. Но вот передать массив устройств можно. Для этого нужно в процессе вывода диалога в этом месте:
MyDialogFragment myDialogFragment = new MyDialogFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
myDialogFragment.show(transaction, "dialog");

добавить bundle который будет использоваться для передачи данных:
Bundle bundle = new Bundle();
bundle.putSerializable("devices_list", pairedDeviceArrayList);

по итогу будет выглядеть так:
MyDialogFragment myDialogFragment = new MyDialogFragment();
FragmentManager manager = getSupportFragmentManager();
Bundle bundle = new Bundle();
bundle.putStringArrayList("devices_list", pairedDeviceArrayList);
myDialogFragment.setArguments(bundle)
FragmentTransaction transaction = manager.beginTransaction();
myDialogFragment.show(transaction, "dialog");

и дальше получения массива в диалоге делается так:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    arrayList= getArguments().getStringArrayList("devices_list");
    ...
}

так же не забудьте что нужно будет сделать глобальную переменную в диалоге чтобы можно было ее потом использовать. Таким образом вы передадите данные в ваш диалог, и потом уже их можно будет отобразить в списке который добавляется через xml так же как и в активности. Если же вы хотите передавать список устройств bluetooth то нужно сделать глобальную переменную в активности которая будет соответствовать вашему массиву устройств и дальше ее передавать:
Bundle bundle = new Bundle();
bundle.putSerializable("devices_list", devicesList);

Так как сейчас код выше будет передавать массив строк и все. Поэтому если вам нужно будет что-то делать с элементами массива например подключится к устройству, то стоит передавать массив устройств а не строк.


text:
Q: Creating a new repo/project from a previous cloned project I cloned an existing repo from Git (Bitbucket) and copied that file to a new location. Now I wanted to push that to an empty repository to Bitbucket as a new project with changes that are related to that project. This happened:
git remote add origin
fatal: remote origin already exists

After that I checked the git version (with $ git remote -v) and it indicates to the original cloned git repo from the last project. Is there a way to remove the git history so that I can do git init and push the project to a new repo? If I use rm -rf .git will that harm the original cloned git repo? Or can I then initialize the new project and push that to the new empty repo?

A: Description
The reason why you are getting this

fatal: remote origin already exists

is because origin is a local version of a remote repository. Think of it as a folder with a name origin.
Example
Just change the name when you add a remote
git remote add <name> <url>

You can use whatever name you like, as long as it doesn't violate conditions applied by the file system
Alternatively, you can remove the remote origin.
git remote rm origin

Note: This will remove local copy of a remote repository named origin from your file system!
Reference
git-remote

A: Inside .git you store everthing related to your local clone of a git repository. In your case it should be no problem to delete it and rerun git init . after. Once you have done this you have to commit your complete folder …. so your commands could look like (pseudo)
$ cd new_project
$ rm -rf .git
$ git init .
$ git add *
$ git commit -m "Initial commit of my fork"
$ git remote add …
$ git push

However, this would purge the complete history of the base of your fork. I would consider this bad style and might conflicts with copyright depending on license original project is used. why not conside a full fork and do something like:
$ cd original_repo
$ git remote add -f myfork <bitbucketurl>
$ git push myfork

After that has be done you can either remove the original origin from your clone or just reclone from bitbucket. This would keep original history.

A: You can simple add a new remote (git remote add new_origin destination), or rename the actual (git remote rename origin old_origin), or delete the actual (git remote rm actual_destination).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filters in Kibana Need to find logs about errors in Kibana.
I can add a filter by content of a message but it's a temporary solution.
How can I make this filter constant (not just pin)?
What is the best way to do it? May be there are other solutions, not about filters in Kibana?
Thank you for help!

A: You can do this also from the Discover tab:

You need to use a logstash filter , this enables you split your entire log message into elements (see picture 2), that way you can easily read your messages and it lets you focus on the important attributes.


text:
Q: How to disable grid cell in extJS grid while loading base on some row record data How to disable grid cell in extJS grid while loading base on some reacid data.
I am using grid where I want to disable one grid editor based on record data. Here what I am trying but what happening is when any of the cell is getting disable entier column cellis getting disable.
My clumn definaation
{
    "header": "column 3",
    "tdCls":"editable-grid-cell",
    "dataIndex": "clumn3",
    "width":120,
    "renderer":"enableDisablecolumn3",
    "editor": {
      "xtype": "numberfield",
      "bind": "{record.column3}",
      "disabled":false,
      "allowDecimals":true,
      "decimalPrecision":5,
      "allowNegative": false,
      "maskRe": "/[0-9.-]/",
      "minValue": 0
    }
}

My renderer methos.
enableDisablecolumn3:  function(value, metaData, record) {
        //debugger;
        let _this = this;
        var gridEditor = metaData.column.getEditor();
        if ('Yes' === record.data.column2&& ) {
            gridEditor.setDisabled(true);
        }
    }

Any idea how to achive this. I want disable only that perticular cell.

A: You can use beforeedit event. Something like this:
Ext.application({
    name: 'Fiddle',

    launch: function () {
        Ext.create('Ext.data.Store', {
            storeId: 'simpsonsStore',
            fields: ['name', 'email', 'phone'],
            data: [{
                name: 'Lisa',
                email: 'lisa@simpsons.com',
                phone: '555-111-1224'
            }, {
                name: 'Bart',
                email: 'bart@simpsons.com',
                phone: '555-222-1234'
            }, {
                name: 'Homer',
                email: 'homer@simpsons.com',
                phone: '555-222-1244'
            }, {
                name: 'Marge',
                email: 'marge@simpsons.com',
                phone: '555-222-1254'
            }]
        });

        Ext.create('Ext.grid.Panel', {
            title: 'Simpsons',
            store: Ext.data.StoreManager.lookup('simpsonsStore'),
            columns: [{
                header: 'Name',
                dataIndex: 'name',
                editor: 'textfield'
            }, {
                header: 'Email',
                dataIndex: 'email',
                flex: 1,
                editor: {
                    completeOnEnter: false,
                    field: {
                        xtype: 'textfield',
                        allowBlank: false
                    }
                }
            }, {
                header: 'Phone',
                dataIndex: 'phone'
            }],
            selModel: 'cellmodel',
            plugins: {
                cellediting: {
                    clicksToEdit: 1
                }
            },
            height: 200,
            width: 400,
            listeners: {
                beforeedit: function( editor, context, eOpts ) {
                    if(context.field === 'name' && context.value === "Marge") {
                        return false;
                    }
                }
            },
            renderTo: Ext.getBody()
        });
    }
});


text:
Q: How to create dynamic html table from a xml file I have a requirement to create a dynamic table from an xml file similar to below, where I can use xpath or similar to show filesystem content in it, with proper variable pagination, filtering, sort and selection of particular row.
<?xml-stylesheet type="text/xsl" href="csmclientiir.xsl"?>
<csmclient product="abc"   date="4/26/11 2:05 PM">
<system>
    <osname>Linux
    </osname>
    <hostname>AbhishekNix
    </hostname>
    <release>2.6.18-128.el5
    </release>
    <filesystem>
        <file mount='/home/hp1' home='(innfs2:/vol/home/shome/home/hp1)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
        <file mount='/home/par21' home='(innfs2:/vol/home/shome/home/par21)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
        <file mount='/home/h231' home='(innfs2:/vol/home/shome/home/h231)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
        <file mount='/home/avallin1' home='(innfs2:/vol/home/shome/home/avallin1)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
        <file mount='/home/park' home='(innfs2:/vol/home/shome/home/park)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
        <file mount='/home/sp1' home='(innfs2:/vol/home/shome/home/sp1)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
        <file mount='/home/ganga1' home='(innfs2:/vol/home/shome/home/ganga1)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
        <file mount='/home/nbp1' home='(innfs2:/vol/home/shome/home/nbp1)' total='1717567488' free='644306780' used='1073260708' percentage='62' />
    </filesystem>
</system>
<product>
    <showtime>Tue Apr 26 14:05:23 2011
    </showtime>
</product>
</csmclient>

Edited
Here is what I used using jqGrid
jQuery("#listTable").jqGrid({
    url: cpath,
    datatype: "xml",
    colNames:["Total Space","Free Space","Used Space", "Used Percentage"],
    colModel:[ {name:"Total Space",index:"Total Space", width:90, xmlmap:"system>filesystem>file>@total"},
               {name:"Free Space",index:"Free Space", width:120, xmlmap:"system>filesystem>file>@free"},
               {name:"Used Space",index:"Used Space", width:180,xmlmap:"system>filesystem>file>@used"},
               {name:"Used Percentage",index:"Used Percentage", width:100, align:"right",xmlmap:"system>filesystem>file>@percentage", sorttype:"float"}
             ],
    height:250,
    pager: '#pager',
    rowNum:10,
    rowList:[10,20,30],
    viewrecords: true,
    gridview: true,
    loadonce: true,
    xmlReader: {
        root : "csmclient",
        row: "system>filesystem",
        repeatitems: false,
        id: "ASIN"
        },
    caption: "Disk Usage"
    });

it only shows heading without any data
Note: my xml file structure is fixed

A: Recently I used jqGrid for a project but I was using JSON instead of XML as it's data.
But this plugin also accepts the XML type of data. It's pretty dynamic and have all the functionalities you want. You might want to check the demo here. There's a section named Data Mapping which explains how to map XML files.
Comment on the edit
I would change your code this way:
 xmlReader: {
    root : "filesystem",
    row: "file",
    repeatitems: false,
 }

Since I guess it's the file attributes you want to show in a single row. Also make sure the colModel name maps to the name of your node. I still don't know if you could map node attributes but assuming you do:
    colModel:[ {name:"total",index:"total", width:90},
           {name:"free",index:"free", width:120},
           {name:"used",index:"used"},
           {name:"percentage",index:"percentage", width:100, sorttype:"float"}
         ]

This wiki is also useful it can help you to start with jqGrid.


text:
Q: How to prevent duplicate booking in calendar? What is the best way to implement duplicate booking issues with calendar? We are on SP 2010. I tried couple of approach (like group settings) but that did not help. Any other way?

A: I've come across this before. You need to use jquery and call REST services to call the Calendar after the form loses focus on the due date. The call will check to see if the request is unavailable.
Another way is to use the Resources content type, and have conference rooms or whatever you are trying to book as a resource that people can use. The form that you use will be able to check double booking...


text:
Q: java messaging - how to create an ad-hoc network I have 3 clients. I would like to create an application that shows when each client is online and when not based on the JMS - java messaging and tomcat server. Till now I successfully succeed to create a sending and receiving messaging using JMS (queue1).
I don't know from where to start in order to make my application alive.
Thank you.
Need help.
Appreciate!

A: First of all, JMS is quite a heavy-weight way to implement this behaviour.  You'd be far better off using a MulticastSocket.
However the basic principle is the same whichever route you take:

*

*each client sends a heartbeat messages identifying itself at predefined intervals until it is closed or dies.

*the monitoring application listens for those heartbeat messages, keeps track of the clients that have identified themselves in the heartbeat messages and assumes a client is dead when the heartbeat messages stop for a given client.

With JMS these messages would be sent to a single queue, with a MulticastSocket you send a DatagramPacket to a group.


text:
Q: Instabug Proguard issue I have a problem including instabug library in an obfuscated project (all other third party libraries are ok).
The error I get is following ( I know there have been other question about this error message, but my problem appears only with instabug, and none of the proposed solutions work for it ).

Error:Execution failed for task ':app:packageRelease'.
Unable to compute hash of C:\Projects\ProguardExample\app\build\intermediates\classes-proguard\release\classes.jar

I have added some statements to my configuration file when trying to solve the problem.
-dontwarn android.support.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.** { *; }
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**
-keep class com.instabug.** { *; }

// here I tried also to change the proguard-project.txt
and to my proguard-rules.pro
-dontwarn java.nio.file.Files
-dontwarn java.nio.file.Path
-dontwarn java.nio.file.OpenOption
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

Here is how my build.gradle looks like.
   buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.config
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile 'com.android.support:appcompat-v7:23.0.1'
    //compile 'com.github.danieltwagner:android-async-logger:0.1.0@aar'
    compile 'com.instabug.library:instabugsupport:1+'
    // compile 'org.apache.commons:commons-collections4:4.0'
}

I would be very thankful if you could guide me towards solving this problem. Even if you don't know its solution, but suspect in which area, should I research to find it, please share with me :)

A: The guys from instabug helped me out via email. So here is the solution (that totally works for me) - add those statements to you proguard-rules.pro
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn com.google.android.gms.**
-dontwarn com.android.volley.toolbox.**
-dontwarn com.instabug.**


text:
Q: Converting date in DD/MM/YY formate and order by it I have table having two column 1) ProductId(int) 2) PublishDate(varchar)
data is like following
ProductId   PublishDate
73          22/01/97
56          17/09/90
56          01/09/90
69          15/05/13
69          09/05/13

I have to get record from this table but in PublishDate Order by Desc,
as PublishDate is varchar, I am not able to do this can anyone please help me for this.
I have tried following query:
SELECT T.ProductId,
       T.MYDATE
FROM
(
SELECT     ProductId, CONVERT(varchar(max), PublishDate , 101) AS MYDATE
FROM         DateValidation

) T
ORDER BY T.MYDATE DESC

A: Yo don't need to change date format because it is stored in your needed format ( it is stored as varchar, this is a dirty pattern).
But your issue is sorting by date. To sort by calendar date you need to convert varchar to a valid date:
SELECT     ProductId, PublishDate
  FROM     DateValidation
 ORDER BY  CONVERT(DATE, PublishDate, 103) desc

I encourage to you to store dates in a date format but varchar.

A: Here is the SQLFIddel Demo
below is the Query Which You can try
Select ProductId,
       Convert(Date,substring(PublishDate,4,3) +
                    substring(PublishDate,1,3) +
                    substring(PublishDate,7,2))
  From DateValidation
 Order By 2 Desc

A: Try This
SELECT ProductId,CONVERT(date,PublishDate,3)
FROM DateValidation
order by 2 desc


text:
Q: Where can I find a log of the information shown at boot splash? An elderly computer of ours has stopped working. When it's turned on, it gives an error of "unsupported display" - this is normal for us and happens because the graphics card can't render the splash screen. However, now it just stays stuck at that error message and won't boot.
I booted a live CD and looked over a bunch of log files but none of them have entries from today, the day the problem started.
Is there any way to figure out what the error on the hidden splash screen is?

A: The easiest way might be to boot the system that's having problems and disable the splash screen. That will then show the boot messages during bootup.
To show the boot messages, start up and when grub appears press 'e' to edit the grub entry. Press the down arrow until you get to the linux kernel line. Press CTRL-E to go to the end of the line. Remove quiet splash from the line. You might also need to delete any line that begins with gfxmode if it still doesn't work. I had to remove the gfxmode line to be able to see the boot messages on Xubuntu. Now press F10 to boot. The boot messages should appear.
Something else you can try is to boot from your rescue disk, mount the filesystems of the computer, then look at /var/log/syslog, /var/log/boot.log, and /var/log/boot. The last one may not exist or be empty if the computer is not configured to run bootlogd at startup. You can edit /etc/default/bootlogd and make sure that BOOTLOGD_ENABLE=Yes is set, then reboot, to get the boot output into /var/log/boot.
Between all of those options you should be able to determine where the system is getting stuck at bootup.


text:
Q: Node js form submit TypeError: Cannot set property 'userId' of undefined I have added login and registration features to a page in my application in views/employee/login.hbs. When I enter in registration details (email, username, password and conf password), I hit the register button to hopefully be redirected to the views/employee/home.hbs page. However, when I complete this action my MongoDB Compass Community database receives the registration details that I have entered successfully but  my browser states 'The site cannot be reached' and URL is "localhost:3000/employee/employee/login" when it should be "localhost:3000/employee/home". I have added in the code below that would be in use. I have also added the the folder and file structure below with the folders open to show this display. I am new to Node js so I am sorry if this is an easy fix.
I have tried changing the routes in the "router.post('/employee/login', function (req, res, next) {" in the controller file or the "form action="/employee/login" method="post" to other ways but for the ones I used got an error of - Cannot POST /employee/login, or similar (Cannot POST / etc)

controllers/employeeController.js
router.get('/home', (req, res) => {
  res.render('employee/home', {layout: 'main.hbs'});
});

router.get('/login', (req, res) => {
    res.render('employee/login', {layout: 'main.hbs'});
  });

//POST route for updating data
router.post('/employee/login', function (req, res, next) {
    // confirm that user typed same password twice
    if (req.body.password !== req.body.passwordConf) {
      var err = new Error('Passwords do not match.');
      err.status = 400;
      res.send("passwords dont match");
      return next(err);
    }

    if (req.body.email &&
      req.body.username &&
      req.body.password &&
      req.body.passwordConf) {

      var userData = {
        email: req.body.email,
        username: req.body.username,
        password: req.body.password,
      }

      User.create(userData, function (error, user) {
        if (error) {
          return next(error);
        } else {
          req.session.userId = user._id;
          return res.redirect('employee/home');
        }
      });

    } else if (req.body.logemail && req.body.logpassword) {
      User.authenticate(req.body.logemail, req.body.logpassword, function (error, user) {
        if (error || !user) {
          var err = new Error('Wrong email or password.');
          err.status = 401;
          return next(err);
        } else {
          req.session.userId = user._id;
          return res.redirect('employee/home');
        }
      });
    } else {
      var err = new Error('All fields required.');
      err.status = 400;
      return next(err);
    }
  })

  // GET for logout logout
  router.get('/logout', function (req, res, next) {
    if (req.session) {
      // delete session object
      req.session.destroy(function (err) {
        if (err) {
          return next(err);
        } else {
          return res.redirect('employee/login');
        }
      });
    }
  });
module.exports = router;

models/user.js (should be fine since database recieves data but shown for further context)
var UserSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true
  },
  username: {
    type: String,
    unique: true,
    required: true,
    trim: true
  },
  password: {
    type: String,
    required: true,
  }
});

//authenticate input against database
UserSchema.statics.authenticate = function (email, password, callback) {
  User.findOne({ email: email })
    .exec(function (err, user) {
      if (err) {
        return callback(err)
      } else if (!user) {
        var err = new Error('User not found.');
        err.status = 401;
        return callback(err);
      }
      bcrypt.compare(password, user.password, function (err, result) {
        if (result === true) {
          return callback(null, user);
        } else {
          return callback();
        }
      })
    });
}

//hashing a password before saving it to the database
UserSchema.pre('save', function (next) {
  var user = this;
  bcrypt.hash(user.password, 10, function (err, hash) {
    if (err) {
      return next(err);
    }
    user.password = hash;
    next();
  })
});

var User = mongoose.model('User', UserSchema);
module.exports = User;

server.js
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/testForAuth', { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false }, (err) => {
    if (!err) { console.log('MongoDB Connection Succeeded.') }
    else { console.log('Error in DB connection : ' + err) }
});

var db = mongoose.connection;

//handle mongo error
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
  // we're connected!
});

//use sessions for tracking logins
app.use(session({
  secret: 'work hard',
  resave: true,
  saveUninitialized: false,
  store: new MongoStore({
    mongooseConnection: db
  })
}));

const employeeController = require('./controllers/employeeController');

var app = express();

//setting up morgan middleware
app.use(logger('dev'));

app.use(bodyparser.urlencoded({
    extended: false
}));
app.use(bodyparser.json());

app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainLayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');

//serving blank favicon to keep from throwing 404 errors
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))

//setting up static path for serving static files
app.use(express.static(path.join(__dirname, 'public')));

//Bringing in the routes
const index = require('./routes/index');
const api = require('./routes/api');

app.use('/', index);
app.use('/api', api);

app.listen(3000, () => {
    console.log('Express server started at port : 3000');
});

app.use('/employee', employeeController.router);

views/employee/login.hbs (handlebars)

Login

                    <form action="employee/login" method="post">
                        <input type="text" name="logemail" placeholder="E-mail" required="">
                        <input type="password" name="logpassword" placeholder="Password" required="">

                            <input type="submit" value="LOGIN NOW">

                    </form>

Register

                    <form id="login2" action="employee/login" method="post" onsubmit="event.preventDefault(); validateMyForm();">
                        <input type="text" name="email" placeholder="E-mail" required="">
                        <input type="text" name="username" placeholder="Username" required="">
                        <input type="password" name="password" placeholder="Password" id="password" required="" >
                        <input type="password" name="passwordConf" placeholder="Confirm Password" id="password_conf" required="">
                        <input type="submit" value="REGISTER">
                    </form>

 By clicking register, I agree to your terms

A: Take away any lines of code with
req.session.userId = user._id;

Also, change anything with res.redirect as such
return res.redirect('employee/home');

to res.render, as such
return res.render('employee/home');


text:
Q: Foreign key on PostgreSQL range bounds Is it possible in PostgreSQL 9.6 to apply a foreign key constraint on the lower and upper bounds of a range (of integers in my case)?
Currently I keep the lower bound and upper bound in two columns, but would like to unify them into a range column while keeping the foreign key references.
Example
I have a table containing a list of sessions, something like:
CREATE TABLE sessions (
    session_id    SERIAL      PRIMARY KEY,
    session_start TIMESTAMPTZ NOT NULL,
    description   TEXT
);

and then a table of groups of those sessions which is currently expressed as:
CREATE TABLE session_groups (
    group_id      SERIAL  PRIMARY KEY,
    first_session INTEGER NOT NULL UNIQUE,
    last_session  INTEGER NOT NULL UNIQUE,
    description   TEXT,

    FOREIGN KEY (first_session)
                REFERENCES sessions (session_id)
                ON UPDATE CASCADE
                ON DELETE RESTRICT,
    FOREIGN KEY (last_session)
                REFERENCES sessions (session_id)
                ON UPDATE CASCADE
                ON DELETE RESTRICT,

    CONSTRAINT last_session_after_first
         CHECK (last_session >= first_session)
);

What I would like:
CREATE TABLE session_groups (
    group_id      SERIAL    PRIMARY KEY,
    session_range INT4RANGE NOT NULL UNIQUE,
    description   TEXT,

    FOREIGN KEY (lower(session_range))
                REFERENCES sessions (session_id)
                ON UPDATE CASCADE
                ON DELETE RESTRICT,
    FOREIGN KEY (upper(session_range))
                REFERENCES sessions (session_id)
                ON UPDATE CASCADE
                ON DELETE RESTRICT

    -- Dropped last_session_after_first constraint since
    -- the INT4RANGE type checks it automatically.
);

which is throwing a syntax error.

A: It is not allowed to have arbitrary expressions in FOREIGN KEY constraints, only columns. That's why you get an error when you try the 2nd approach.
You can however, use a VIEW to access the table:
CREATE VIEW v_session_groups
    (group_id, session_range, description) AS
SELECT
    group_id,
    int4range(first_session, last_session, '[)'),
    description
FROM
    session_groups ;

You could even add triggers, and then be able to INSERT/UPDATE/DELETE from the view, as if it was a normal table.

Side notes:

*

*The first design has 2 UNIQUE constraints, on (first_session) and (last_session), while the 2nd has 1 UNIQUE constraint, on (first_session, last_session). These are not equivalent designs, so re-examine your requirements.

*I used the default '[)' (inclusive-exclusive) parameter for the int4range column. You may want to change that to '[]' (all-inclusive), depending on how you want to be saving ranges.
Examples:int4range(1,1) and int4range(1,1,'[)') is the empty range while int4range(1,1,'[]') is the [1,2) range.

*If you want to enforce / avoid overlapping ranges, then you don't need a UNIQUE constraint at all but an EXCLUDE constraint:
CREATE TABLE session_groups (
    group_id      SERIAL  PRIMARY KEY,
    first_session INTEGER NOT NULL,
    last_session  INTEGER NOT NULL,
    description   TEXT,

    FOREIGN KEY (first_session)
                REFERENCES sessions (session_id)
                ON UPDATE CASCADE
                ON DELETE RESTRICT,
    FOREIGN KEY (last_session)
                REFERENCES sessions (session_id)
                ON UPDATE CASCADE
                ON DELETE RESTRICT,

    CONSTRAINT non_overlapping_sessions
        EXCLUDE  USING gist
        ( int4range(first_session, last_session, '[)') WITH && )
);

See also the documentation on constraints on range types. You probably need to add the extension as well:
CREATE EXTENSION btree_gist;


text:
Q: Finding statistics about duplicate emails in MySQL I need to query statistics about duplicate values in my database table. For example, say that I have an e-mail field and multiple rows can have the same e-mail. I know want to know is how many addresses is repeated how many times. In other words: "908 emails are repeated 10 times, 1783 emails are repeated 9 times" and so on.
Repeated       # of Emails
10             908
9              1783

I don't need to see the actual e-mail addresses, just these statistics.
Right know I have this query which also retrieves the e-mail address:
select email_address,
count(email_address) as NumberOccurrences
from table_user_info
group by email_address
having ( count(email_address) > 1 )

How do I group these results?

A: An aggregate COUNT() with a subquery also returning an aggregate COUNT() will provide this.  The subquery groups and counts per email address, as in abc@example.com - 10, and the outer query then counts and groups by the number of repeats returned by the subquery, discarding the actual email addresses.
SELECT
  repeated,
  COUNT(*) AS numemails
FROM (
  SELECT
     email,
     COUNT(*)
  FROM emails
  GROUP BY email
) emailcounts

A: select email_address,
       count(email_address) as NumberOccurrences
from table_user_info
group by email_address
having count(*) > 1


text:
Q: Android - How to setup child views inside a viewgroup Can someone help me with my Syntax/Methodology?  I would like to set up a bunch of different views in a viewgroup.  My code fails at the addView method.
Unfortunately, I can't find jack for examples (which is how I learn) using the ViewGroup class online.
Thanks all.
public class TileView extends ViewGroup {
private TestClass mTestClass;
    public TileView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initViews();
    }
    public TileView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews();
    }
    public void initViews() {
        addView(mTestClass);
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
    }
}

public class TestClass extends View{

public TestClass(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public TestClass(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public TestClass(Context context) {
    super(context);
}

}

A: First of all you should check your own layout xml file. By error message line number 6 is wrong. second problem is you didn't initialize mTestClass object in your view group source code. If you want to get children view, you can use getChildAt(int) method in view group. It is simple example,
int count = getChildCount();

for (int i = 0; i < count; i++) {
    View child = getChildAt(i);
}

And, is it full source code? I think you should implement onMeasure and onLayout method in ViewGroup and View instance.


text:
Q: How to filter columns with another file's dummy I have two data frames that look like this:
df1 <- data.frame(date = c("01.01.", "02.01.", "03.01.", "04.01.", "05.01."),
                  A = c(102, 75, 99, 175, 60),
                  B = c(94, 37, 140, 63, 87),
                  C = c(55, 23, 90, 102, 107))

df2 <- data.frame(ID = c("A", "B", "C"),
                  dummy = c(1, 0, 1))

I'm now trying to create a df3 using the select() function in dplyr. The result should only include those who have a dummy == 1, meaning that df3 would only have column A and C remaining. However, since the dummy is found in a separate file, and can't really be merged into the first one, I am unsure how to do this.
Thanks!

A: Is this what you want?
library(dplyr)
df3 <- df1 %>%
  select(matches(df2 %>% filter(dummy == 1) %>%
                   pull(ID)))

If you want it without the date column, add ignore.case = FALSE to the matches function, i.e.
df3 <- df1 %>%
  select(matches(df2 %>% filter(dummy == 1) %>%
                   pull(ID), ignore.case = FALSE))

Output:
   A   C
1 102  55
2  75  23
3  99  90
4 175 102
5  60 107

A: library(dplyr)
df1 %>%
  select(df2$ID[df2$dummy == 1])

    A   C
1 102  55
2  75  23
3  99  90
4 175 102
5  60 107

A: Using base R
 subset(df1, select = df2$ID[as.logical(df2$dummy)])
    A   C
1 102  55
2  75  23
3  99  90
4 175 102
5  60 107


text:
Q: Why a replacement of fonts changes not only English characters, but also Chinese characters? Originally my website uses two Google fonts, i.e., Montserrat and Lato. To reduce the load time for these fonts, I replace them with web safe fonts Georgia and Arial.
It is obviously that the English texts in the websites are changed.
However, I notice that the Chinese texts are also changed.
So I go back to Google fonts and check if their fonts have Chinese subset:
https://fonts.google.com/?query=Montserrat&subset=chinese-simplified
https://fonts.google.com/?query=Lato&subset=chinese-simplified
All returns empty.
So, how can know what will they be in Chinese characters?
And why the replacement of the fonts will also change the Chinese characters?
BTW: I find the way to specify the font for different languages: Can CSS choose a different default font and size depending on Language
Update:

*

*The original font family(for headings and menu items):

font-family: Montserrat;

replaced with:
font-family: 'Georgia', 'Verdana', 'Arial', serif, sans-serif;

*The original font family(for paragraph texts):

font-family: Lato;

replaced with:
font-family: 'Arial', 'Helvetica', 'Tahoma', 'Times New Roman', sans-serif, serif;


text:
Q: Can I say "What are you doing today?" when I want to say "Hi!" to a person? Can I say "What are you doing today?" when I want to say "Hi!" to a person?

A: No, "What are you doing today?" is not a replacement for hi, or any greeting.
You can say "Hi. What are you doing today?" and that would not be the same as saying "Hi. Hi."

A: As expressed in previous answer, it is too literal to use as a greeting.
You could perhaps use "What's up?" instead to try to achieve a similar thing.
This is treated as a greeting whilst literally meaning "what are you doing?" / "how are you?".
The receiver can then either just say a greeting back or answer either question above.

A: No, those phrases are not the same. "Hi" is a greeting, while "What are you doing today?" is used when you want to know what that person's schedule will be like that day. Why would you want to know what they are doing today? Maybe you want to spend time with them (if they are busy then you can't), or you are simply curious as to what they will be doing later that same day.
However, there is a similar phrase to "what are you doing today?" It is "how are you doing today?"
For example:

Other person: "Hello!"
You: "Hi! How are you (doing) today?"
Other person: "Great, how are you?"
You: "Great, thanks."

I put the "doing" in parentheses because the sentence would still make sense if it was not there.


text:
Q: No me carga la Funcion, pygame Anteriormente había hecho una publicación, donde me expresé mal y no explique cual era mi problema, así que ahora voy a intentar ser extenso y explicar lo que me sucede.
Estoy haciendo un juego para aprender en pygame, es un juego super sencillo, donde mi idea es crear un juego, donde sos un granjero que intentas recolectar monedas. sin sprites me funcionaba bien, es más. se podia jugar, el problema fue cuando le puse la clase "granjero" con sus atributos; Así esta;
    import pygame
import tamaño
class Granjero:
    def __init__(self):
        self.imagen = pygame.image.load("juegos/imagenes/granjero.png")
        self.sprites = []
        self.recortar_sprites()
        self.sprite_actual = 0
        self.rect = pygame.Rect(5, 120, 30, 43)
        self.direccion = "abajo"

    def recortar_sprites(self):
        #Cargar imagen con los sprites
        sprites_image = pygame.image.load("juegos/imagenes/granjero.png")

        #Obtener sub-superficie del primer sprite (caminando hacia arriba)
        sprite_arriba1 = sprites_image.subsurface(pygame.Rect(0,129 ,30, 43))
        sprite_arriba2 = sprites_image.subsurface(pygame.Rect(41, 129, 30, 43))
        sprite_arriba3 = sprites_image.subsurface(pygame.Rect(86.21, 129, 30, 43))
        sprite_arriba4 = sprites_image.subsurface(pygame.Rect(133, 129, 30, 43))
        #sprite_arriba5 = sprites_image.subsurface(pygame.Rect(174, 129, 30, 43))
        #sprite_arriba6 = sprites_image.subsurface(pygame.Rect(220, 129, 30, 43))
        #Obtener sub-superficie del segundo sprite (caminando hacia arriba)
        sprite_derecha1 = sprites_image.subsurface(pygame.Rect(0, 86, 30, 43))
        sprite_derecha2 = sprites_image.subsurface(pygame.Rect(41, 86, 30, 43))
        sprite_derecha3 = sprites_image.subsurface(pygame.Rect(86, 86, 30, 43))
        sprite_derecha4 = sprites_image.subsurface(pygame.Rect(133, 86, 30, 43))
        #sprite_derecha5 = sprites_image.subsurface(pygame.Rect(174, 86, 30, 43))
        #sprite_derecha6 = sprites_image.subsurface(pygame.Rect(220, 86, 30, 43))

        sprite_izquierda1 = sprites_image.subsurface(pygame.Rect(0, 44, 30, 43))
        sprite_izquierda2 = sprites_image.subsurface(pygame.Rect(41, 44, 30, 43))
        sprite_izquierda3 = sprites_image.subsurface(pygame.Rect(86, 44, 30, 43))
        sprite_izquierda4 = sprites_image.subsurface(pygame.Rect(133, 44, 30, 43))
        #sprite_izquierda5 = sprites_image.subsurface(pygame.Rect(174, 44, 30, 43))
        #sprite_izquierda6 = sprites_image.subsurface(pygame.Rect(220, 44, 30, 43))

        sprite_abajo1 = sprites_image.subsurface(pygame.Rect(0, 0, 30, 43))
        sprite_abajo2 = sprites_image.subsurface(pygame.Rect(41, 0, 30, 43))
        sprite_abajo3 = sprites_image.subsurface(pygame.Rect(86, 0, 30, 43))
        sprite_abajo4 = sprites_image.subsurface(pygame.Rect(133, 0, 30, 43))
        #sprite_abajo5 = sprites_image.subsurface(pygame.Rect(174, 0, 30, 43))
        #sprite_abajo6 = sprites_image.subsurface(pygame.Rect(220, 0, 30, 43))

        self.sprites.append(sprite_arriba1)
        self.sprites.append(sprite_arriba2)
        self.sprites.append(sprite_arriba3)
        self.sprites.append(sprite_arriba4)
        #self.sprites.append(sprite_arriba5)
        #self.sprites.append(sprite_arriba6)
        self.sprites.append(sprite_derecha1)
        self.sprites.append(sprite_derecha2)
        self.sprites.append(sprite_derecha3)
        self.sprites.append(sprite_derecha4)
        #self.sprites.append(sprite_derecha5)
        #self.sprites.append(sprite_derecha6)
        self.sprites.append(sprite_izquierda1)
        self.sprites.append(sprite_izquierda2)
        self.sprites.append(sprite_izquierda3)
        self.sprites.append(sprite_izquierda4)
        #self.sprites.append(sprite_izquierda5)
        #self.sprites.append(sprite_izquierda6)
        self.sprites.append(sprite_abajo1)
        self.sprites.append(sprite_abajo2)
        self.sprites.append(sprite_abajo3)
        self.sprites.append(sprite_abajo4)
        #self.sprites.append(sprite_abajo5)
        #self.sprites.append(sprite_abajo6)

    def update(self):
        self.sprite_actual += 1
        if self.sprite_actual >= len(self.sprites):
            self.sprite_actual = 0
            tamaño.ventana.blit(self.sprites[self.sprite_actual], (self.x, self.y))

Tuve que quitar partes del codigo, porque me daba error, no sabia lo que era, así que opte por lo más sencillo, sacarlo del codigo comentandolo, jejeje.
Bueno, el problema no es ese, el problema es en el archivo "principal.py" donde tengo la función menú, función creditos, función gameover y función "jugar".
Cuando le doy ejecutar, funciona de lo más bien, es más, hasta se escucha la música y todo, te podes mover.

El problema viene cuando le doy a "inciar jugar", ahí es cuando empieza el fallo, ya que cuando lo presiono, se me tranca la pantalla del juego y se queda sin responder.
La verdad pienso que es un problema del sprite o del fondo, tambien podria ser directamente el problema de la funcion menu cuando le doy a jugar, no sé, pueden ser muchas cosas, así que dejo  el codigo,  expliquenme y ayudenme a arreglarlo, soy nuevo y quiero aprender
Solo dejaré el def menu y el def jugar, pienso que lo otro es irrelevante
 import pygame
import random
import sys
import tamaño

pygame.init()
pygame.mixer.init()

pygame.display.set_caption("Tu hermana 1")
def menu():
    pygame.mixer.music.load("juegos/musica/hola1.mp3")
    fondonivel = pygame.image.load("juegos/imagenes/fondomenu.jpg")

    # Reproducir música del menú en loop
    pygame.mixer.music.play(loops=-1)

    opcion = 1
    fuente = pygame.font.Font(None, 30)

    while True:
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    opcion -= 1
                elif event.key == pygame.K_DOWN:
                    opcion += 1
                elif event.key == pygame.K_RETURN:
                    if opcion == 1:
                        # Iniciar juego
                        jugar()
                    elif opcion == 2:
                        # Mostrar opciones
                        creditos()
                    elif opcion == 3:
                        # Salir del juego
                        pygame.quit()
                        sys.exit()
        tamaño.ventana.blit(fondonivel,(0,0))
        opciones = ["Iniciar juego", "creditos", "Salir"]
        y = 50
        for i, texto in enumerate(opciones):
            if i + 1 == opcion:
                color = (255, 0, 0)
            else:
                color = (255, 255, 255)
            opcion_texto = fuente.render(texto, 1, color)
            text_rect = opcion_texto.get_rect()
            text_rect.center = ((tamaño.Ancho / 2), (tamaño.Altura / 2)+y)
            tamaño.ventana.blit(opcion_texto, text_rect)
            y +=50
        pygame.display.update()

def jugar():
    from granjero import Granjero
    granjero= Granjero()

    fondojuego = pygame.image.load("juegos/imagenes/fondonivel.jpg")
    tamaño.ventana.blit(fondojuego,(0,0))
    tamaño.ventana.blit(granjero.sprites[granjero.sprite_actual], granjero.rect)
    pygame.mixer.music.load("juegos/musica/bebe.ogg")
    pygame.mixer.music.play(loops=-1)

    pygame.mixer.music.play()
    reloj = pygame.time.Clock()

    tamaño_x=20
    tamaño_y=20

    velocidad_x= 1
    velocidad_y=1
    velocidad_x_enemigo=1
    velocidad_y_enemigo=1

    food_rect = pygame.Rect(random.randint(10, 1200), random.randint(10, 600), tamaño_x,tamaño_y)
    enemigo=  pygame.Rect(random.randint(10, 1200), random.randint(10, 600), tamaño_x,tamaño_y)

    puntos = 0
    vida= 10

    fuente = pygame.font.Font(None, 30)

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                if event.unicode == "w":
                    granjero.rect.y -= 5+velocidad_y
                    granjero.cambiar_animacion("arriba")

                elif event.unicode == "s":
                    granjero.rect.y += 5+velocidad_y
                    granjero.cambiar_animacion("abajo")

                elif event.unicode == "a":
                    granjero.rect.x -= 5+velocidad_x
                    granjero.cambiar_animacion("izquierda")

                elif event.unicode == "d":
                    granjero.rect.x += 5+velocidad_x
                    granjero.cambiar_animacion("derecha")

            pygame.display.flip()
            tamaño.ventana.blit(fondojuego, (0, 0))
            tamaño.ventana.blit(granjero.sprites[granjero.sprite_actual], granjero.rect)
            pygame.display.update()
        if granjero.left < 0 or granjero.right > 1200:
            velocidad_x = -velocidad_x
        if granjero.top < 20 or granjero.bottom > 600:
            velocidad_y = -velocidad_y
        if enemigo.left < 0 or enemigo.right > 1200:
            velocidad_x_enemigo = -velocidad_x_enemigo
        if enemigo.top < 20 or enemigo.bottom > 600:
            velocidad_y_enemigo = -velocidad_y_enemigo
        enemigo.x += velocidad_x_enemigo
        enemigo.y += velocidad_y_enemigo

        if granjero.colliderect(food_rect):

            granjero.width += 5
            granjero.height += 5

            food_rect = pygame.Rect(random.randint(0, 450), random.randint(0, 450), tamaño_x,tamaño_y)
            puntos +=1
        if granjero.colliderect(enemigo):

            enemigo.x = random.randint(0, 1200)
            enemigo.y = random.randint(10, 600)

            enemigo = pygame.Rect(random.randint(0, 1200), random.randint(0, 600), tamaño_x,tamaño_y)
            vida -= 1

        if vida == 0:
            pygame.mixer.music.stop()
            Gameover()

        tamaño.ventana.blit(puntos_texto, (10, 10))
        tamaño.ventana.blit(vida_texto, (200, 10))
        pygame.display.update()

        pygame.draw.rect(tamaño.ventana, (255, 0, 0), food_rect)
        pygame.draw.rect(tamaño.ventana, (255, 100, 200), enemigo)
        tamaño.ventana.blit(fondojuego, (0, 0))
        tamaño.ventana.blit(granjero.sprites[granjero.sprite_actual], granjero.rect)

        puntos_texto = fuente.render("Puntos: " + str(puntos), 1, (255, 255, 255))
        vida_texto= fuente.render("Vida:"  +str(vida),1,(255, 255, 255) )
        tamaño.ventana.blit(puntos_texto, (10, 10))
        tamaño.ventana.blit(vida_texto, (200, 10))
        pygame.display.update()

        reloj.tick(130)
        pygame.display.flip()


text:
Q: How to write pretty permalinks using nginx and php I am working on custom RSS feeds for one of my clients website "example.com" and for that the feed url takes query strings to customize the feeds like
http://example.com/feeds/rss_feed.php?num=20&store=2998

and i would like to convert these urls to
http://example.com/feeds/rss_feed.php/php/num/20/store/2998/

Any help on this matter would be really appreciated.

A: You have to create additional section in your site config. Don't forget to restart nginx after making changes.
location ~* ^/feeds/rss_feed.php/(.*)$ {
rewrite ^/feeds/rss_feed.php/php/num/(\d+)/store/(\d+)/$ /feeds/rss_feed.php?num=$1&store=$2 last;
}


text:
Q: Accept header NSXMLParser I can not set the header for a connection with NSXMLParser.
in particular I should put this header:
"Accept Application/xml"
this is my code:
func parse (handler: () -> Void) {
     self.handler = handler

     dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

         newLink NSURL var = (string: SomeStructure.newLink)
         UIApplication.sharedApplication (). NetworkActivityIndicatorVisible = true
         let xmlCode = NSData (contentsOfURL: newLink!)
         UIApplication.sharedApplication (). NetworkActivityIndicatorVisible = false
         // let resulset = NSString (date: xmlCode, encoding: NSASCIIStringEncoding)
         // println (resulset)
         let parser = NSXMLParser (date: xmlCode)
         parser.delegate = self

         if! Parser.parse () {
             self.delegate? .XMLParserError (self, error: "Error Parser Category.")
             println ("Parser error")
         }
     }
 }

Thanks


text:
Q: libGL error with Linux target of OpenFL I'm planning on doing game development with Haxe, utilizing its C++ target, and for that I chose the HaxeFlixel framework, which uses OpenFL as its backend.  The "hello world" test runs just fine with flash, HTML5 seems to work (minus sound), though I'm not planning on using either of those, as the game I wish to create would be a desktop game that runs natively.
However, when I tried to run the HaxeFlixel hello world example with the target set to native linux, the test program crashed on startup and gave me the following errors:
libGL: screen 0 does not appear to be DRI2 capable
libGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/tls/swrast_dri.so
libGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/swrast_dri.so
libGL: Can't open configuration file /home/zauber/.drirc: No such file or directory.
libGL error: failed to load driver: swrast
X Error of failed request:  GLXUnsupportedPrivateRequest
  Major opcode of failed request:  153 (GLX)
  Minor opcode of failed request:  16 (X_GLXVendorPrivate)
  Serial number of failed request:  211
  Current serial number in output stream:  213

I'm at a loss as to how to fix the problem.  I've never seen anything like it, and all other 3D software and games I have run just fine.  I asked on the HaxeFlixel forums, but was only told that it might be a bug in OpenFL.  That seems to be the case since I have the same problem with Awe6, another game framework that uses OpenFL.
I've done a google search for similar issues, but turned up pretty much nothing.  I already have all the relevant libraries that I should have (mesa, nVidia drivers, dri2, 32bit libs), and all the solutions I found pretty much pointed to installing a specific library, which I already had installed.
So far, I have asked on both the OpenFL forums and on the IRC channel, and in both cases I was completely ignored.  I really need to get this problem fixed because unless I do, I cannot proceed with my gamedev project.
For reference, my system is running 64bit Linux Mint 16, Linux kernel 3.11.0-12, and nVidia drivers 319.32

A:
For reference, my system is running 64bit Linux Mint 16, Linux kernel 3.11.0-12, and nVidia drivers 319.32

Then something in your system configuration is completely messed up: For some reason your program loads a libGL.so provided by the Mesa drivers instead of the NVidia drivers libGL.so. The telltale sign is, that the loaded libGL complains about DRI2 not being available. NVidia's proprietary drivers don't use or support DRI2. DRI2 is the low level state tracker API of Mesa.
Make sure your system is properly configured. Most importantly make sure that none of the libraries, frameworks, etc. you use did something foolish, like bundling up a libGL.so.


text:
Q: Definability of subgraphs of random graphs I'm new to model theory and I'm trying to solve this problem.
Let $N$ and $M\subseteq N$ random graphs, is there a $\phi \in L(N)$ (where $L(N)$ is the language of graphs with a constant symbol for each element of $N$) such that $\phi$ defines $M$ for every such $M$? In other words, is $M$ definable with parameters in $N$?
I don't have any clue. I noticed that I can't use an atomic formula of the form $\phi(a,x)$ with $a$ parameter, so I was thinking the answer is no and trying of use the fact that every automorphism send definable sets with parameters in definable sets with parameters to find a contradiction, but I'm not sure of this method. Do you have any suggestion?

A: If $N$ is a random graph (countable) then it is a fact that for any finite partition of $N$ at least one of the members of the partition is a random graph (with induced graph structure). Since there are continuum many partitions in say two sets, there are continuum many subgraphs of $N$ which are random. On the other hand there are only countably many formulae in $L(N)$. Therefore, not every random $M\subseteq N$ is definable.

A: As an alternative to SMM's argument, you can construct a non-definable elementary substructure of the random graph by directly diagonalizing against formulas. This strategy has the advantage of also working for other Fraïssé limits which do not satisfy the property about finite partitions in SMM's answer.
Let $(\varphi_n(x,a_n))_{n\in \omega}$ enumerate the $L(N)$-formulas with the property that the subgraph they define is an isomorphic copy of the random graph. We will build two sequences of finite sets $(A_n)_{n\in \omega}$ and $(B_n)_{n\in \omega}$ such that $A_n\subseteq A_{n+1}$, $B_n\subseteq B_{n+1}$, and $A_n\cap B_n = \varnothing$ for all $n$. The idea is that we want ensure that the union of the $A_n$ is an isomorphic copy of the random graph, by throwing in witnesses to the extension axioms, while at the same time ensuring that it's not defined by any formula. We do this by putting "blocking" elements into $B_n$, one for each formula. Start with $A_n = B_n = \emptyset$.
Now suppose we're given $A_n$ and $B_n$. If $X$ and $Y$ are disjoint subsets of $A_n$, there is some $a\in N\setminus B_n$ (because $B_n$ is finite) such that $a$ is has an edge to every element of $X$ and has no edge every element of $Y$. Pick such an element $a$, which we call an extension witness for $X$ and $Y$. Let $A_{n+1}$ be $A_n$ together with an extension witness for every pair of disjoint subsets of $A_n$. Then $A_{n+1}$ is finite, because there are only finitely many such pairs. Now look at the formula $\varphi_n(x,a_n)$. Because it defines an isomorphic copy of the random graph, in particular it defines an infinite set, and there is some $b$ such that $N\models \varphi_n(b,a_n)$ and $b\notin A_{n+1}$. Let $B_{n+1} = B_n\cup \{b\}$.
By induction, we've defined $A_n$ and $B_n$ for all $n$. Let $M = \bigcup_{n\in \omega} A_n$, and note that $M$ is disjoint from $B_\infty = \bigcup_{n\in \omega} B_n$. Also $M$ is an isomorphic copy of the random graph, because it satisfies all extension axioms. But on the other hand, $M$ is not defined by any formula $\varphi_n(x,a_n)$. This is because for any such formula, there is some element $b\in B_\infty$ such that $N\models \varphi_n(b,a_n)$, and $b\notin M$.


text:
Q: Random positioning of pawns on chessboard I want to (pseudo) randomly position a number points on a grid. Think of it as 10 x 10 chessboard with 100 squares) And think of these points as pawns on the chessboard, that occupy one square each. What I want is for the pawns to be "evenly" distributed over the board. The middle-square method is fine for generating the random numbers.
00  01  02  03  04  05  06  07  08  09
10  11  12  13  14  15  16  17  18  19
20  21  22  23  24  25  26  27  28  29
30  31  32  33  34  35  36  37  38  39
40  41  42  43  44  45  46  47  48  49
50  51  52  53  54  55  56  57  58  ...

My problem that is that if I store the grid squares as list, and draw them from top left to bottom right, then square 9 is not next to 10, as you would expect. 10, is next to 0 & 20. What's the best way around this?

A: Element numbering in lists starts with zero, not with 1. So your first square has number 0 (you do see it, right?) and the 10th square has number 9. That is why the 1st square in the 2nd row has number 10 and not 11. It is because 0 + 10 = 10. If you want to print the numbers starting from 1 you can do it adding 1 to a square number in print:
print (square[number] + 1)

As I do not see your code I cannot provide a better code example which would perfectly pass to your code.

A: Just because you store the final squares as a list, that doesn't mean you have to generate random numbers in a linear range. If you know you have, say, a 100x100 grid, then choose points by choosing X and Y coordinates separately, and then fill in square number 100 * X + Y.
If you want the points distributed randomly, then just make sure you choose both X and Y from a uniform random distribution 0..99. If you want the points distributed evenly, use something like a Halton sequence.


text:
Q: updatedTransactions failed to be called back after iOS 4.2 We've been having a tricky problem with store kit. We are trying to implement correctly the in-app purchase renewable subscriptions process into an app that already is on the appStore with standard in-app purchase (non-consumable products) set up.
So far, and after spending 2 months fighting with the sandbox weird behavior, we came up with a working solution on a test iPad running iOS4.2.
Nasty surprise we got when testing this code on a iPad with 4.3 or 5.0, it does not have the same behavior.
We narrowed it down to this simple fact:
- iOS4.2 : the updatedTransactions callback is working properly
- iOS4.3 and above: the updatedTransactions callback is never called by the sandbox.
Any ideas on why a store kit code that works on iOS4.2 wouldn't work on following iOS versions? I didn't see anything deprecated on this.
Here is the code of our updatedTransactions code:
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    NSLog(@"Add payment queue");
    for(SKPaymentTransaction *transaction in transactions)  {
        NSLog(@"Transaction state: %d, %d, %d, %d", transaction.transactionState, SKPaymentTransactionStatePurchased, SKPaymentTransactionStateFailed, SKPaymentTransactionStateRestored);
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchased:

                if([transaction.payment.productIdentifier isEqualToString:FM_PRODUCT_IDENTIFIER_SUBSCRIPTION]){
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:transaction.transactionReceipt forKey:@"TransactionReceiptOfTransaction"];
                }

                [self completeTransaction:transaction];
                [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

                break;

            case SKPaymentTransactionStateFailed:
                NSLog(@"%@", transaction.error);

                [self failedTransaction:transaction];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
                                                                message:NSLocalizedString(@"Your subscription has expired.", @"")
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles: nil];
                [alert show];
                SAFE_RELEASE(alert);

                [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

                if([transaction.error code] != SKErrorPaymentCancelled) {
                    if([transaction.payment.productIdentifier isEqualToString:FM_PRODUCT_IDENTIFIER_SUBSCRIPTION]){
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:transaction.transactionReceipt forKey:@"TransactionReceiptOfTransaction"];
                    }
                }
                break;

            case SKPaymentTransactionStateRestored:

                if([transaction.payment.productIdentifier isEqualToString:FM_PRODUCT_IDENTIFIER_SUBSCRIPTION]){
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:transaction.transactionReceipt forKey:@"TransactionReceiptOfTransaction"];
                }

                [self restoreTransaction:transaction];
                [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

            default:
                    NSLog(@"Other");
                break;
        }
    }
}

Thanks,
Stephane

A: I had exactly the same problem and to solve it I switched the source file which contains the
addTransactionObserver call to ARC = none.
//  StoreKit
CustomStoreObserver *observer = [[CustomStoreObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer];

Seems that ARC or StoreKit framework can't work well together.
To switch a source file with the ARC = none, I set -fno-objc-arc flag as Josh Caswell says it in the "Disable Automatic Reference Counting for Some Files" question.

The answer is to add -fno-objc-arc to the compiler flags for the files you don't want ARC. In Xcode 4, you can do this under your target -> Build Phases -> Compile Sources.

Update: My explanation about that behavior is that ARC wants to manage the memory itself but it does not do it well for Storekit. ARC releases too early the 'observer' object. That cause the crash when the InAppPurchase module (Apple side) wants to advise your "updatedTransactions"
method. And for me to stuck 'observer' object in memory during the life of my application. I decided to give it the property retain in my .h file.


text:
Q: Elimination in a tournament In a single-elimination tournament, teams are paired up and play head-to-head matches in rounds. After each round, all losers are eliminated, and the winners move on to the next round. The tournament ends when there is only one team left.
Two tournaments are the same if the same matches are played and won by the same teams, and are different otherwise. How many different single-elimination tournaments amongst n teams are possible, where n is a power of two?
How do I begin this question?

A: Start by picking any $n/2$ teams for winning side (the rest become losing side) and then shuffling the losing side to get all permutations. This gives you the number of possibilities for the first round.
$$N_1 = {n\choose n/2}\cdot (n/2)!$$
Now using the same rationale, you get the possibilities for the second round by choosing $n/4$ teams for winning side and shuffling to get
$$N_2 = {n/2\choose n/4}\cdot (n/4)!$$
Similarly,
$$N_i ={n/2^{i-1}\choose n/2^i}\cdot (n/2^i)!$$
Since $N_1$, $N_2$ ... $N_i$ are independent events, we multiply them together to get total possibilities
$$N=N_1N_2N_3...$$
$$N=\frac{n!}{(n/2)!(n/4)!(n/8)!...1!}$$


text:
Q: CSS - Adjust height to bottom of screen I have a div with a big list, I only want to see (with a scroll) the number of elements that fits in the screen. So I cannot figure how can I adjust the height of the div to the bottom border of screen.
Do I have to use JS?

A: If you got a fixed size above. You can fill the rest by using css calc.

.test {
  height:300px;
  width: 100%
  background-color:yellow;
 }

.full-height {
  height: calc(100vh - 300px);
  background-color:red;
  }

A better solution is to use a wrapper. Like this:

.wrapper {
  background-color:red;
  height: 100vh;
}

.list {
  background-color: white;
  width: 100%
}

This

is

a

list

A: Based on screen size apply media query styles.
for example Footer want to be bottom we use this for all the browsers

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ff0;
   padding:10px;
}
#body {
   padding:10px;
   padding-bottom:60px;   /* Height of the footer */
}
#footer {
   position:absolute;
   bottom:0;   /* Always make footer in bottom at any screen */
   width:100%;
   height:60px;   /* Height of the footer */
   background:#6cf;
}


text:
Q: Powershell 3.0 : Alternative to "Get-Volume" I'm trying to get various properties for each hdd-volume on the computer.
I was using the cmdlet get-volume and then walking through it via foreach, but that cmdlet does not exist in Windows Server 2008. :(
Does anybody know an alternative?
I just need the drive letter, objectId/guid, free space, total space, and the name of each volume.

A: The WMI class Win32_Volume has the information you are looking for
Get-WMIObject -Class Win32_Volume | Select DriveLetter,FreeSpace,Capacity,DeviceID,Label

Which a little fancy footwork you can make the drive space properties looking a little more appealing.
Get-WmiObject -Class Win32_Volume |
        Select DriveLetter,
            @{Label="FreeSpace (In GB)";Expression={$_.Freespace/1gb}},
            @{Label="Capacity (In GB)";Expression={$_.Capacity/1gb}},
            DeviceID,Label |
        Format-Table -AutoSize

A: Get-Volume is only in Powershell 4.
You can do this tho:
Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID, Size, FreeSpace, VolumeName


text:
Q: Java Stream: Parsing Strings inside the reduce() operation I have a stream of strings:
Stream<String> st = Arrays.stream(new String[]{"10", "20", "30",  "40", "50"});

I want to convert them to integer and sum them up using the reduce method. I'm using reduce in the following format:
int result = st.reduce(0, (a, b) -> a + Integer.parseInt(b));

I get this error:
no suitable method found for reduce(int, (a, b) -> a + [...]nt(b))

any hint about how can I rewrite the reduce method to make it work?

A: You need to provide a combiner function as the third argument to make it work:
int sum = Arrays.stream(new String[]{"10", "20", "30",  "40", "50"})
            .reduce(0, (a, b)-> a + Integer.parseInt(b), Integer::sum);

Otherwise you're getting the different flavor of reduce() which is capable of produce the result of the same type as the type of elements in the stream.
And you don't need reduce(), the better way:
int sum = Stream.of("10", "20", "30",  "40", "50")
            .mapToInt(Integer::parseInt)
            .sum();

A: Instead of using reduce(), I'd break it into two steps: Convert the strings to ints (As an IntStream), and then sum them:
Stream.of("10", "20", "30", "40", "50").mapToInt(Integer::parseInt).sum()

A:
I want to convert them to integer and sum them up using the reduce method. I am using reduce in the following format:

When converting to an IntStream via Integer::parseInt the reduce method takes a form of an int starting value and an IntBinaryOperator. So the following will work.
String[] data ={"10", "20", "30",  "40", "50"};
int sum = Arrays.stream(data)
           .mapToInt(Integer::parseInt).reduce(0, (a,b)->(a+b));
System.out.println(sum);

prints
150

And for your edification (and future requirements) you can do it like so.
int sum = Arrays.stream(data).mapToInt(Integer::parseInt).sum();
System.out.println(sum);

prints
150


text:
Q: Find multiple programs with same SSNs I have the following tables:

*

*Contact - This has client SSN info

*Program - This has program info that the client is enrolled in

----- Programs with same SSN
select MAX(p.name)
from raw_prod.bedrock.contact c
join raw_prod.bedrock.program_c p on p.account_id_c = c.account_id
HAVING COUNT(*) > 1;

Desired output: Different program names with same SSNs
Program Name   ----------   SSN
P - 0001 ---------         000-00-0000
P - 0002 --------          000-00-0000
P - 0003 ---------          111-11-1111
P - 0004 ----------          111-11-1111
P - 0005 -----------           111-11-1111
P - 0006 -----------          222-22-2222
P - 0007 ------------          222-22-2222
Sorry about the formatting issues.
The query should give me P- 0001 and P- 0002 as these programs have same SSNs
Please let me know if more info is needed. I am new to SQL :(


text:
Q: Filter dates according to the month and paste them in a new column with month as column name I have about 30+ columns with dates all ranging in current year for databases. I need to filter dates and arrange them in new columns, as in all dates falling in May in a new column called May while all dates in June in another column June.
(I have a schedule for databases which all the release date in the current year in different columns. I need to create a column month-wise and add dates in these columns)
I did write a code but I could only filter dates of one of the many columns and also the date format is distorted
sf.loc[(sf['Unnamed: 16']>= start) & (sf['Unnamed: 16']<=end), 'CurrentMonth'] = sf['Unnamed: 16']

Input file
Output file

A: If the first bit managed to filter what you wanted with:
sf.loc[(sf['Unnamed: 16']>= start) & (sf['Unnamed: 16']<=end), 'CurrentMonth'] = sf['Unnamed: 16']
Then create a column like this
sf['New column'] = values for new column
I can't reproduce the problem as you haven't provided a useful dataset (images are not useful for this - see the instructions for how to create a minimal example https://stackoverflow.com/help/mcve


text:
Q: Converting Mongoose MPromise into Rxjs.Observable in TypeScript I want to convert MPromise which is used by mongoose - https://github.com/aheckmann/mpromise into Observable Rxjs.Observable. Could you share your opinion on the following code snippet. Is it good enough?
export function fromMPromise<T>(m: mongoose.Promise<T>): Rx.Observable<T> {
    const subject = new Rx.ReplaySubject<T>(1);
    m.onFulfill((v: T) => {
        subject.next(v);
        subject.complete();
    });
    m.onReject((e: any) => {
        subject.error(e);
        subject.complete();
    });
    return subject.asObservable();
}


text:
Q: RabbitMQ using AMQplib - Timeout for queue_declare I use RabbitMQ for handling logging between services (written in PHP).
If services can't connect to RabbitMQ, they timeout within 3 seconds and try to use a different method for logging. This has been tested and works well with if the RabbitMQ server is down, or behind a firewall. The code that has these timeouts appears to be the in the AMQPStreamConnection class of the php-amqplib/php-amqplib PHP package as shown below:
public function __construct(
        $host,
        $port,
        $user,
        $password,
        $vhost = '/',
        $insist = false,
        $login_method = 'AMQPLAIN',
        $login_response = null,
        $locale = 'en_US',
        $connection_timeout = 3.0, // here
        $read_write_timeout = 3.0, // and here
        $context = null,
        $keepalive = false,
        $heartbeat = 0
    ) {
        $io = new StreamIO(

Unfortunately, these timeouts don't seem to help me if I am running a massive "Purge queue" operation by clicking the button in the web UI (a queue with over 20 million in size). I wrote some code to log the times during a purge to see what was going wrong:
...
$this->m_queueName = $queueName;

print "creating connecton: " . time() . "
";
$connection = new \PhpAmqpLib\Connection\AMQPStreamConnection(
    $host,
    $port,
    $user,
    $password
);

print "creating channel: " . time() . "
";
$this->m_channel = $connection->channel();

print "declaring queue: " . time() . "
";
$this->m_channel->queue_declare(
    $queueName,
    $passive = false,
    $durable = true,
    $exclusive = false,
    $auto_delete = false,
    $nowait = false,
    $arguments = null,
    $ticket = null
);

print "queue declared. " . time() . "
";

The result being as follows:
creating connecton: 1523977606
creating channel: 1523977606
declaring queue: 1523977606
queue declared. 1523977622
hello world: 1523977622

I can see that the connection and channel get created, but the declaration of the queue takes way too long to respond and I would rather the queue_declare step would timeout in 3 seconds and an Exception be thrown. Is this possible? What configuration variable(s) do I need to change?


text:
Q: Database is full in sqlite I tried to write delete query in sqlite database:
DELETE FROM photoGalleryTbl WHERE id=204
and I got error:
"Error: database is full".
Can I remove that record? How??
Thanks!!

A: Maybe the partition where the sqlite file is stored is full; try to move the file elsewhere and retry the delete command.

A: Yes try to move the DB file to some other location and try to use delete command and also check if you have stored the data in DB

A: It probably is the drive or the partition. Might even be that the drive or the DB file is read-only.
Alternatively, you could try querying the following database properties to find out why the DB is reporting that it is full:
max_page_count
page_count
journal_size_limit


text:
Q: Digital Crown - Moving Images? Is it possible to use the Digital Crown to move an Object in my WKnterfaceController?
Something like an Image or an Button?
The only thing i found was to use it in a PickerView.

A: You can use the digital crown to scroll lists. This is the built in behaviour of lists. If you place your image or the buttons in a list, you can move it.


text:
Q: How do I add a custom column with a hyperlink in the django admin interface? I have a django admin interface and in the model listing I want a custom column that will be a hyperlink using one of the fields values.  Basically one of the models' fields is a url and i'd like the column to have that URL in a clickable hyperlink.  This link will need to have additional URL prepended to it as its a relative path in the model field.

A: Define a method in your ModelAdmin-class and set its allow_tags attribute to True. This will allow the method to return unescaped HTML for display in the column.
Then list it as an entry in the ModelAdmin.list_display attribute.
Example:
class YourModelAdmin(admin.ModelAdmin):
    list_display = ('my_url_field',)

    def my_url_field(self, obj):
        return '%s' % ('http://url-to-prepend.com/', obj.url_field, obj.url_field)
    my_url_field.allow_tags = True
    my_url_field.short_description = 'Column description'

See the documentation for ModelAdmin.list_display for more details.

A: Use the format_html utility. This will escape any html from parameters and mark the string as safe to use in templates. The allow_tags method attribute has been deprecated in Django 1.9.
from django.utils.html import format_html
from django.contrib import admin
from django.utils.translation import gettext_lazy as _

class MyModelAdmin(admin.ModelAdmin):
    list_display = ['show_url', ...]
    # ...

    @admin.display(description=_("Column title"))
    def show_url(self, obj):
        return format_html("{0}", obj.url)

Now your admin users are safe even in the case of:
url == ''

See the documentation for more info.

A: I am using 'instance' instead of 'obj'. Seppo Erviälä's answer helped me the most as I'm using Django 3.0.1.
def get_facebook(self, instance):
    return format_html("{0}", instance.profile.facebook)
get_facebook.short_description = 'Facebook'


text:
Q: Loop and Save Data Actually, I am new in Python, so I need more help to handle my data. The next step is make loop for a month data from daily data (one day one file). And then make the variables (numeric) resulted from this program as a new array and save those as a file. Thank you in advance.

A: You can add each of the files i.e., A1,A2..Ax in a list. Then save the list. That should work for you.

A: First of all, like @leeladam said, is better to store the values of your A variables in a list (a nested list, each element of the A list is other list with your data).
Then the csv module is the best approach for that task.  Each line of the csv line (row) is an A list and each column is a data comma separated.  With this module you can save the data with Excel format.


text:
Q: Display message if foreach comes back as empty So I can't seem to figure out this logic, so I'm reaching out to see if someone might be able to help me.
So I have the following foreach:
echo "Page: " . $page_placement . "/" . $total_pages . "\n\n";
foreach ($posts as $post) {
    $current_post_id = post_exists(
        $post->title->rendered,
        '',
        '',
        '',
        ''
    );
    if ($current_post_id === 0) {
        $my_post = [
            'post_type'     => 'post',
            'post_status'   => 'pending',
            'post_title'    => wp_strip_all_tags($post->title->rendered),
            'post_content'  => wp_strip_all_tags($post->content->rendered),
            'post_excerpt'  => wp_strip_all_tags($post->excerpt->rendered),
            'post_author'   => 1,
            'post_date'     => $post->date,
        ];

        // Insert post.
        $post_id = wp_insert_post($my_post);
        wp_set_object_terms($post_id, 'Global', 'category');
        wp_set_object_terms($post_id, 'Global', 'post_tag');
        echo "ID: " . $post->id . " - Title: " . $post->title->rendered . " has been imported.\n";
    }
}

It grabs 50 $posts and then loops through and calls post_exists() to check the title of the post, and if it doesn't exist, it will import the post otherwise it will skip it.

How can I display an echo message if all 50 of the posts aren't imported?
I can't call if (!$current_post_id) { inside the foreach, as it will display the message 50 times and I tried to play an variable outside the foreach and then call $my_post[] = [ .... ] but then the wp_import_post didn't work.

A: Just use a variable (e.g. $imported, initial value=0) to check the counts. If imported, increment it .
So at last if the variable is still 0, call the echo statement
Hence:
<?php
echo "Page: " . $page_placement . "/" . $total_pages . "\n\n";

$imported=0;

foreach ($posts as $post) {

    $current_post_id = post_exists(
        $post->title->rendered,
        '',
        '',
        '',
        ''
    );
    if ($current_post_id === 0) {
        $my_post = [
            'post_type'     => 'post',
            'post_status'   => 'pending',
            'post_title'    => wp_strip_all_tags($post->title->rendered),
            'post_content'  => wp_strip_all_tags($post->content->rendered),
            'post_excerpt'  => wp_strip_all_tags($post->excerpt->rendered),
            'post_author'   => 1,
            'post_date'     => $post->date,
        ];

        // Insert post.
        $post_id = wp_insert_post($my_post);
        wp_set_object_terms($post_id, 'Global', 'category');
        wp_set_object_terms($post_id, 'Global', 'post_tag');
        echo "ID: " . $post->id . " - Title: " . $post->title->rendered . " has been imported.\n";
        $imported++;
    }

}

if ($imported==0){
echo "No record imported";
}


text:
Q: How to add a watermark to Google Docs Now that there is an official way to insert a watermark in google docs through the user interface, I am trying to find how to do the same from apps script.
Any idea?


text:
Q: Component not being rendered in React after upgrading to Gatsby v.2 even though I'm getting no errors in Gatsby CLI When I rungatsby develop I get no errors and the page shows everything but the navigation. While in the Chrome dev tools I'm getting this error: Warning: Each child in a list should have a unique "key" prop. The thing is I can't put together this error message with the issue I'm having.
src/layouts/index.js
import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'

import Header from '../components/Header'

const Layout = ({ children, data }) => (

    <Helmet
      title={data.site.siteMetadata.title}
      meta={[
        { name: 'description', content: data.site.siteMetadata.description },
        { name: 'keywords', content: data.site.siteMetadata.keywords },
      ]}
    />

    {children()}

)

Layout.propTypes = {
  children: PropTypes.func,
}

export default Layout

export const query = graphql`
  query SiteTitleQuery {
    site {
      siteMetadata {
        title
        description
        keywords
      }
    }
  }
`

src/components/Header.js
import React from 'react'
import Link from 'gatsby-link'
import './Header.css'

class Header extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      hasScrolled: false
    }
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
  }

  handleScroll = (event) => {
    const scrollTop = window.pageYOffset

    if (scrollTop > 50) {
      this.setState({ hasScrolled: true })
    } else {
      this.setState({ hasScrolled: false })
    }
  }

  render() {
    return (

          <Link to="/"></Link>
          <Link to="/courses">Courses</Link>
          <Link to="/downloads">Downloads</Link>
          <Link to="/workshops">Workshops</Link>
          <Link to="/buy"><button>Buy</button></Link>

    )
  }
}

export default Header

This is my gatsby info
System:
    OS: macOS 10.15.6
    CPU: (8) x64 Intel(R) Core(TM) i7-3615QM CPU @ 2.30GHz
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 12.16.2 - /usr/local/bin/node
    npm: 6.14.4 - /usr/local/bin/npm
  Languages:
    Python: 2.7.16 - /usr/bin/python
  Browsers:
    Chrome: 85.0.4183.102
    Safari: 13.1.2
  npmPackages:
    gatsby: ^2.24.55 => 2.24.56
    gatsby-link: ^2.4.13 => 2.4.13 => 2.4.13
    gatsby-plugin-react-helmet: ^3.3.10 => 3.3.10
    gatsby-plugin-styled-components: ^3.3.10 => 3.3.10
    gatsby-source-contentful: ^2.3.42 => 2.3.44
  npmGlobalPackages:
    gatsby-cli: 2.12.95

A: There is no error, it is a warning as it is shown in the message. It doesn't block your rendering even it appears. This is a common warning that shows up in every loop that misses a key value in any React component. The key value must be unique and the purpose of using it is to help React to identify internally which items have changed (by adding/removing/re-ordering them). This article may help you to clarify some stuff.
For example:
{anyArray.map((item, index)=>
{item.value}
}

In the dummy example above, the key value is item.value. It's not recommended to use the index loop itself, however, you can append it to item.value if you want in order to avoid duplicated entries.
In addition, what I've found potentially code-breaking in your code is the usage of window without doing any validation before. As you can see in Gatsby's documentation about global objects (debugging builds), since the code is compiled in the server, the usage of global objects such as document or window may break the code because they are not defined at the time your code is requesting it. To fix this, just add:
  componentDidMount() {
    if(typeof window !== 'undefined'){
        window.addEventListener('scroll', this.handleScroll)
    }
  }


text:
Q: weird page when using media query I'm doing a page it use media query:
@media
only screen and (max-width: 320px){}

If the page width size <= 320px (we call it small page), it will load the css inside media query.
But I meet a problem, if I open a tab1 in Chrome, and resize the browser width less than 320px, the mobile style page will show, but then I open a new page in new tab2, then maximize this tab, some while later(5 minutes), go back to tab1, it still load the mobile style. If I go back immediately, the tab1 will show the correct css style.
Please see the screeshot.
Picture 1 is the normal page
Picture 2 is the small page load the media query style
Picture 3 is the weird page, if maximize another tab, some while later, go back to account summary page, it will be like this, the expect result is showing the normal page

A: I had the same problem, but the opposite.
Maybe should you try :
only screen and (min-width: 320px){}
instead of
only screen and (max-width: 320px){}
.


text:
Q: Write text to file in bash script with variable replacement but without backtick replacement I'm trying to tidy up my bash script to make use of variables to define repeated things once only.
I'm running into a problem in one part where I am using the bash script to create other bash scripts for later execution.
Specifically, I want to avoid backtick execution at the time of running the parent script (so that the backticks are executed only when running the child scripts).  But I also want to make use of variable substitution so that I can make multiple use of a single definition.
What I'm doing at present is along the following lines:
GLOBAL="yellow"
BASE="script"
APPS="foo bar"

for APP_NAME in $APPS; do
cat << EOF > ./"$BASE-$APP_NAME"
#!/bin/bash
mkdir ./app--$APP_NAME--$GLOBAL--`date +%Y%m%d_%H%M%S`
# do some other stuff
EOF
chmod +x ./"$BASE-$APP_NAME"
done

When I run the above, variable substitution is performed as I want, but the backticked date is expanded at the time of running the parent script.
I know that I can preserve the backticks by using "EOF" instead:
...
cat << "EOF" > ./"$BASE-$APP_NAME"
...

But then variable substitution is not performed!  How do I do this so that variables are substituted and backticks are not executed?
I want the generated script-foo script to look like:
#!/bin/bash
mkdir ./app--foo--yellow--`date +%Y%m%d_%H%M%S`
# do some other stuff


text:
Q: What is the relationship between a JavaScript Object and an element created in it? Is it possible to pass this.brother as a variable in the eventListener of this.son?
function Object(a){
  this.brother = a;
  this.son = document.createElement("div");
  document.getElementById('parent').appendChild(this.son);
  this.son.addEventListener('mousedown',function(){
    onMouseDown(event,this.brother);
  });
}

User input changes the value of this.brother later on,so i cannot just pass the input variable a.
Do I have to add a new eventListener everytime the value of this brother changes?

A: Your question basically comes down to what the keyword this means inside a function. There are three options.
1. "Proper" functions
this.son.addEventListener('mousedown', function() {
  onMouseDown(event, this.brother);
});

If you define a function with the complete function definition syntax, function() {}, then this will refer to the object through which the function is invoked. In the case of an event listener, it's the object that you defined the listener on, which in your case is the div you created. This means you'll get an error, because div elements do not have a property called brother.
2. Arrow functions
Arrow functions were introduced in more recent years, and use different syntax:
this.son.addEventListener('mousedown', () => {
  onMouseDown(event, this.brother);
});

Arrow functions work exactly like "proper" functions in every way, with one exception: they do not have their own this, i.e. this will refer to whatever it refers to in the scope where the function is defined. In your case, it will refer to the object you're initializing in your Object() function. This is probably the one you want.
(Side note: You really shouldn't name your function Object, that name is already taken by the base class for all objects in JavaScript. Overwriting it can cause all sorts of trouble)
3. Bound functions
Functions in JavaScript are objects, and thus they also have methods. One of these is bind(), which allows you to create a bound copy of the function:
this.son.addEventListener('mousedown', (function() {
  onMouseDown(event, this.brother);
}).bind(this));

Bound functions also work like "proper" functions, except this will always refer to the object you passed as the argument to bind(). Before arrow functions, bound functions used to be the most widespread way to ensure this always refers to the same object within a scope. After arrow functions appeared they started to fall out of favor, since arrow functions are more efficient and produce more readable code.

A: I'm not gonna suggest this but you can use a bound function:
function _Object(a){ //this is not a great function name
  this.brother = a;
  this.son = document.createElement("div");
  document.getElementById('parent').appendChild(this.son);
  this.son.addEventListener('mousedown',(function(event){
    onMouseDown(event,this.brother);
  }).bind(this));
}

As for your question, no you do not have to update it.this refers to the _Object, if the brother pointer is changed, this.brother will point to the new brother.


text:
Q: Export class from files other than index.ts I made a file called assembly/Vec3.ts with this content:
/**
 * @constructor
 * @name pc.Vec3
 * @classdesc A 3-dimensional vector.
 * @description Creates a new Vec3 object.
 * @param {Number} [x] The x value. If x is an array of length 3, the array will be used to populate all components.
 * @param {Number} [y] The y value.
 * @param {Number} [z] The z value.
 * @example
 * var v = new pc.Vec3(1, 2, 3);
 */
export class Vec3 {
    x: number;
    y: number;
    z: number;

    // AS is more strict than TS... need to replace all occuranves of this in PlayCanvasTS at some point
    //constructor(x?: any, y?: number, z?: number)
    constructor(x: number, y: number, z: number)
    {
        //if (x && x.length === 3) {
        //  this.x = x[0];
        //  this.y = x[1];
        //  this.z = x[2];
        //} else {
        //  this.x = x || 0;
        //  this.y = y || 0;
        //  this.z = z || 0;
        //}
        this.x = x;
        this.y = y;
        this.z = z;
    }

    /**
     * @function
     * @name pc.Vec3#add
     * @description Adds a 3-dimensional vector to another in place.
     * @param {pc.Vec3} rhs The vector to add to the specified vector.
     * @returns {pc.Vec3} Self for chaining.
     * @example
     * var a = new pc.Vec3(10, 10, 10);
     * var b = new pc.Vec3(20, 20, 20);
     *
     * a.add(b);
     *
     * // Should output [30, 30, 30]
     * console.log("The result of the addition is: " + a.toString());
     */
    add(rhs: Vec3): Vec3 {
        this.x += rhs.x;
        this.y += rhs.y;
        this.z += rhs.z;

        return this;
    }

    /**
     * @function
     * @name pc.Vec3#add2
     * @description Adds two 3-dimensional vectors together and returns the result.
     * @param {pc.Vec3} lhs The first vector operand for the addition.
     * @param {pc.Vec3} rhs The second vector operand for the addition.
     * @returns {pc.Vec3} Self for chaining.
     * @example
     * var a = new pc.Vec3(10, 10, 10);
     * var b = new pc.Vec3(20, 20, 20);
     * var r = new pc.Vec3();
     *
     * r.add2(a, b);
     * // Should output [30, 30, 30]
     *
     * console.log("The result of the addition is: " + r.toString());
     */
    add2(lhs: Vec3, rhs: Vec3): Vec3 {
        this.x = lhs.x + rhs.x;
        this.y = lhs.y + rhs.y;
        this.z = lhs.z + rhs.z;

        return this;
    }
}

Then building it via npm run asbuild
But the file is just ignored and not included inside the untouched.wasm.
Is it possible to export classes from all files?

A: Currently AssemblyScript support global export only from entry file (index.ts). So you should reexport all your entities to this file. But this may improve in future. See this discussion: https://github.com/AssemblyScript/assemblyscript/issues/464

A: Currently I solved it by adding the Vec3.ts to asc in doit.sh:
# print the commands via -x/+y
set -x
npx asc assembly/index.ts assembly/Vec3.ts -b build/untouched.wasm -t build/untouched.wat --sourceMap --validate --debug
npx asc assembly/index.ts assembly/Vec3.ts -b build/optimized.wasm -t build/optimized.wat --sourceMap --validate --optimize
set +x