text:
Q: .when() in joi validation, to validate one key based on another key Admin will create users, and while doing so he will enter some random string as a password. When admin edit the existing user, he don't need to enter any password unless he wants to change it. If the admin doesn't enter any password, then the old password will be used.
So i am trying to use .when() to handle this case. When _id exists in the payload (which is possible only when the user exists), then we should make the password field optional or else password is required.
Here is my Joi validation
const usersJoiSchema = Joi.object({
  _id: Joi.string().optional(),
  firstName: Joi.string().required(),
  lastName: Joi.string().required(),
  email: Joi.string().required(),
  password: Joi.string().when('_id', { is: Joi.exist(), then: Joi.optional(), otherwise: Joi.required() })
})

Joi have a method .when in case of such cases. But for some strange reason it is giving me
{"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}

as the response of the api, and there is nothing in the server console.
I tried to compare the string length for _id as well instead of exists() and i have also tried
password: Joi.string().when('_id', { is: Joi.string().required(), then: Joi.string().optional(), otherwise: Joi.string().required() }),

password: Joi.string().when('_id', { is: Joi.string(), then: Joi.string().optional(), otherwise: Joi.string().required() }),

for password key, but still the same issue.
If any one has any kind of idea on this issue, please help me.

A: Well, I created a simple test and all conditions are passed according to your requirements.
I believe there is something else in your code occurs that error.
Here is my test code, please take a look.
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = require('code').expect;
const Joi = require('joi');

const usersJoiSchema = Joi.object({
    _id: Joi.string().optional(),
    firstName: Joi.string().required(),
    lastName: Joi.string().required(),
    email: Joi.string().required(),
    password: Joi.string().when('_id', {is: Joi.exist(), then: Joi.optional(), otherwise: Joi.required()})
});

describe('Validator usersJoiSchema checks', () => {

    it('It should save new user without id', () => {
        const result = Joi.validate({
            firstName: "Hello",
            lastName: "World",
            email: "hello@world.com",
            password: "123456"
        }, usersJoiSchema, {abortEarly: false});
        expect(result.error).to.null();
        expect(result.error).to.not.exist();
    });

    it('It should update user without password field when id included', () => {
        const result = Joi.validate({
            _id: "some-id-string-here",
            firstName: "Hello",
            lastName: "World",
            email: "hello@world.com",
        }, usersJoiSchema, {abortEarly: false});
        expect(result.error).to.null();
        expect(result.error).to.not.exist();
    });

    it('It should fail when id is empty and no password provided', () => {
        const result = Joi.validate({
            firstName: "Hello",
            lastName: "World",
            email: "hello@world.com",
        }, usersJoiSchema, {abortEarly: false});
        expect(result.error).to.not.null();
        expect(result.error).to.exist();
    });
    it('It should fail when id is empty and password is also empty', () => {
        const result = Joi.validate({
            firstName: "Hello",
            lastName: "World",
            email: "hello@world.com",
            password: "",
        }, usersJoiSchema, {abortEarly: false});
        expect(result.error).to.not.null();
        expect(result.error).to.exist();
    });
});

Here is the test command
> lab --coverage-exclude test/data -m 5000n -a code -P "simple" "test/validators"

  ....

4 tests complete
Test duration: 8 ms
Assertions count: 8 (verbosity: 2.00)
No global variable leaks detected

A:   _id: Joi.string(),
  password: Joi.string().when("_id", {
     is: Joi.exist(),
     then: Joi.required()
  })

With the above, Joi will ensure that password is required whenever _id exists


text:
Q: Magento 2 API to get all products with filter I am working on an API where I need all product of Magento store. I am using postman to make a collection, but I am getting this error.
kindly tell me what is causing this error
image with the new error

A: When you look at webapi.xml you could see route of above mentioned api defined like this:
<route url="/V1/products" method="GET">
        <service class="Magento\Catalog\Api\ProductRepositoryInterface" method="save"/>
        <resources>
            <resource ref="Magento_Catalog::products" />
        </resources>
    </route>

ref="Magento_Catalog::products" means that only users with configured ACL which allow access to this resource are allowed to get it. In magento ONLY admin user can have a configuration of ACL.
So that you will have to use admin token or Integration token
Get an admin token :
   Method:POST Endpoint: /V1/integration/admin/token

For More details refer this official documentation : https://devdocs.magento.com/guides/v2.3/get-started/authentication/gs-authentication-token.html

A: baseurl/rest/default/V1/products?searchCriteria[currentPage]=4&searchCriteria[pageSize]=10

Use above endpoint to eradicate the issue fieldName is a required field

A: You need to pass Admin token in Headers. Below is docs to get Admin token in Maganto 2.
https://devdocs.magento.com/guides/v2.3/rest/tutorials/orders/order-admin-token.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create struct data globally accessible in a singleton class in swift 2.0 (iOS)? I'm very new to iOS programming and swift. I am trying to create a singleton class to store my global data. My global data are a struct and an array of this struct. I want to have only one instance of this class, thus a singleton class. Global data should be accessible and editable to all ViewControllers. I have been searching around and I almost have it figured out except one last part. Here is the singleton class:
    import Foundations
    class Global {

     struct Info {
      var firstname:String!
      var lastname:String!
      var status:String!

      init (firstname:String, lastname:String, status:String)
       {
        self.firstname=firstname
        self.lastname=lastname
        self.status=status
       }
    }

   var testString: String="Test" //for debugging
   var member:[Info]=[]

    class var SharedGlobal:Global
     {
      struct Static
      {static let instance = Global()}
      return Static.instance
     }
    }

Now I want to access the global variables of this singleton class from some viewControllers. When I type this in xcode:
    Global.SharedGlobal.

I get two options one is the array member and the other is the testString. The struct Info is not available. However, if I just type
    Global.

then I see Global.Info and Global.SharedGlobal as my options.
Why is that I can't access the struct in my singleton class (i.e.  Global.SharedGlobal.Info)? I am missing something? I appreciate any feedback or help. Thanks a lot in advance.

A: Unless there's a very specific reason to do it, you don't need to nest classes like that.
Let's simplify a bit your code for the exercise:
struct Info {
    // No need for these properties to be Implicitly Unwrapped Optionals since you initialize all of them
    var firstname: String
    var lastname: String
    var status: String

    init (firstname:String, lastname:String, status:String) {
        self.firstname=firstname
        self.lastname=lastname
        self.status=status
    }
}

class Global {

    // Now Global.sharedGlobal is your singleton, no need to use nested or other classes
    static let sharedGlobal = Global()

    var testString: String="Test" //for debugging

    var member:[Info] = []

}

// Use the singleton like this
let singleton = Global.sharedGlobal

// Let's create an instance of the info struct
let infoJane = Info(firstname: "Jane", lastname: "Doe", status: "some status")

// Add the struct instance to your array in the singleton
singleton.member.append(infoJane)

Now it would make sense to me. A struct holding info about some user, and I can make any number instances of them - and a singleton class, unique, were I can store these Info instances, this singleton being usable anywhere.
Is it the kind of thing you wanted to achieve?


text:
Q: Show multiple lines output in Vim script? My vim script runs multiple commands (2 actually) which output message. When i type in these 2 commands in command mode, there will be 2 lines output, but when I put these 2 commands in script, the output would only for the last line. Use below 2 commands as example, I only see ` world" when put it into Vim script file. Is there a way to show both lines?
:echo "hello" | echo " world"

BTW: I can use :echon to get the whole content above, but it would not work if replace echo with other commands which also output to console.


text:
Q: How to call a Servlet when I click on a Hyperlink On a JSP Page I have populated a table with some id's. I have made these ID's as hyperlink. Now i want that if I click on any id it should go to a servlet and that particular id should also be passed to the servlet.

A: Use this code in your JSP:
  <a href="<%=request.getContextPath() %>/servlet-url?id=<%=id %>">...

to create a link which invokes the servlet at /servlet-url and passes the ID in the request parameter id.


text:
Q: Mysql create trigger 1064 error The sql i wrote
**delimiter |
CREATE
DEFINER=CURRENT_USER
TRIGGER set_profiletype_after_insert BEFORE INSERT ON trl_translator FOR EACH ROW
BEGIN
UPDATE trl_profile SET trl_profile.type = 'translator' WHERE trl_profile.profile_id = NEW.translator_id
END
|
delimiter ;**

The error given
[SQL]
**CREATE
DEFINER=CURRENT_USER
TRIGGER set_profiletype_after_insert BEFORE INSERT ON trl_translator FOR EACH ROW
BEGIN
UPDATE trl_profile SET trl_profile.type = 'translator' WHERE trl_profile.profile_id = NEW.translator_id
END
;
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 6**

How to solve this ? where is the mistake i do ?

A: It looks like you simply need to terminate your UPDATE statement with a semicolon.

A: Try this code
delimiter |
CREATE
DEFINER=CURRENT_USER
TRIGGER set_profiletype_after_insert BEFORE INSERT ON trl_translator FOR EACH ROW
BEGIN
UPDATE trl_profile SET trl_profile.type = 'translator' WHERE trl_profile.profile_id = NEW.translator_id;
END;|
delimiter ;


text:
Q: What is the difference between [^span] and (?!span) in regular expressions? I got into a discussion with my co-worker on whether there can be only one correct regular expression for every pattern. I think that two correct regular expressions can occur. Can a pattern be associated with two different, correct regular expressions? Are [^span] and (?!span) the same thing?

A: (?!phrase) is negative lookahead: from the current point, the following phrase must not be "phrase".
[^span] is much different - it matches any single character that is not s, p, a, or n.


text:
Q: Laravel 5 can't store image name in database I am using Laravel 5.1
I can move image to my destination folder with correct name but in database it's saved with a temp name, like D:\xampp\tmp\phpC7EA.tmp
form.blade.php

    {!! Form::label('image', 'Upload Image', ['class'=>'control-label col-sm-4']) !!}

        {!! Form::file('image', null) !!}

TeacherController.php
public function store(TeacherRequest $request)
{
    Teacher::create($request->all());
    $image_name = $request->file('image')->getClientOriginalName();
    $request->file('image')->move(base_path().'/public/images', $image_name);
    Session::flash('success_message', 'Teacher has been added successfully!');
    return redirect('teacher');
}

A: I am having the same problem when updating the record with new image,image name save in correct name but tmp name in database like 'C:\wamp\tmp\phpD10D.tmp'
what i did before saving is
$request['img'] = $imageName; //with new name
$images->update($request->all());

I know it should be like $_FILE['img']['name'] = $imageName
but how to manage it in Laravel 5.1


text:
Q: how to pass an array to a jade partial 'after' said array has finished loading I have a nice tight array that would render nicely into a jade partial if I could only pass it over to the partial once it was done assembling itself. (I've confirmed it does by preloading it)
The problem I have now and can't find the answer anywhere is that when I run my app I can't use or display the array until it is done assembling/loading itself..(its being populated with scraped data)
-So I'm using async to run the functions that build the array. Works great.
-I'm then calling a function done() once the whole thing is built where I confirm it is indeed built
-And now I just want to pass the array over to my partial but seems I can't do it unless using Ajax + JSON :(  of which I'm trying to avoid since the partial already has solid iteration built in.
-Does anybody know of an easy way to populate the partial after the app is already running (without using sockets)?
//in my main app, web.js
//assume I have all the dependencies loaded
//setup an empty array
var items = new Array();

// then run 'fetch' which populates array with scraped data, takes about 10 seconds
app.get('/', function(req, res){
    fetch(p.u[0]);  //builds the array, returns items[]
    res.render('index.jade', {
        title: 'my first node.js app',
        item: 'items' //what the partial needs, this throws an error if I don't
    })
});

//have to use this to avoid initial error due to array being empty/undefined when app
//first starts
var params = {
    "namespace": {
        "items": [
            "an unnecessary value"
        ]
    }
};

//and finally this is what's called once the array is finished assembling itself
function displayItems(){
    app.get('/', function(req, res){
      req.render('items.jade', {item : 'items'})
    })
}

//index.jade
//setup my partial
//script is there to avoid initial error due to array being empty/undefined when app
//first starts
div.list
  script
    if(namespace.items) {
      if(namespace.items.length) {
        != partial('item', items)
      }
    }

//and my partial, _items.jade
//express docs confirm that jade would iterate over each item in the items array
//with this jade markup
ul.list
  li.date #{item.date}
  li.descrip #{item.descrip}
  li.reas #{item.reas}
  li.cmpny #{item.cmpny}
  li.photo #{item.photo}

A: it's late, i'm not entirely certain I understood your question, but if you are willing to wait 10 secs once, you could do it like this and just cache the result:
var items = null;

app.get('/', function(req, res){
    function done(){
       res.render('index.jade', {
          title: 'my first node.js app',
          item: items
       }):
    }
    if( items == null ){
       return fetch(p.u[0], function(err,fetchedItems){
          if( err ) throw err;
          items = fetchedItems;
          return done();
       });
    }
    return done();
});

hope this helps.
or maybe not: you are using jade on the server-side to assemble pages BEFORE they are sent across the wire.
If I understand correctly, you would like to display a page to the user and after 10 secs show the results (items) on that same page without reloading. Without using Sockets or Ajax, there is no way I know of to accomplish this.
You can either wait until the data is ready, or show a page, saying that the data is loading currently, then switch it out.
partials are page-fragments, or html snippets, that can be included in a .jade like so !=partial(template name[, options]) or called from express like so: res.partial(template name[, options]);. All of this happens on the server.

A: If you're trying to do this synchronously than you're defeating the whole idea behind node.js and Express. If your app is waiting for the query / script that generates this array than what's going to happen to next http requests? You should restructure your app to take advantage of node's ansync approach and pass render as a callback:
app.get('/', function(req, res){
    var renderView = function(items) {
        return res.render('index.jade', {
            title: 'my first node.js app',
            item: items
        })
    };

    fetch(p.u[0], renderView);
});

And you have to modify fetch() to accept 2nd param (the callback), which you will have to call with the items object.


text:
Q: 2nd order Diophantine Equation, when does it have solution(s)? I have this problem:
Ax^2 + Cy^2 + Dx + Ey + F = 0, (B = 0 => Bxy)
I need to know under which circumstances the above has solution(s).
Thank you for your time.

A: See Paul Garrett's nice notes.


text:
Q: WiFi problems on HP Probook 4520S running 16.04 I have an HP ProBook 4520s that I have just installed 16.04 on.
It's impossible to get wifi to connect. Connects fine via LAN.
iwconfig returns :
lo        no wireless extensions.

ens5      no wireless extensions.

wlo1      IEEE 802.11bgn  ESSID:off/any
          Mode:Managed  Access Point: Not-Associated   Tx-Power=off
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on


text:
Q: How to create a sliding bar for buttons in my Android App like that of the Sliding bar in Evernote for Bold, Italics, Underline etc Here is a link to the image of the Evernote app with the sliding bar at the bottom

A: I figured an answer to my own question.
Here is the code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent">
            <Button
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="Button 1"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="Button 2"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="Button 3"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="Button 4"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="Button 5"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="Button 6"/>

        </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>


text:
Q: Does _RC_NEAR use 'ties to even' or 'ties away from zero' rounding? I am looking for documentation that clarifies which IEEE 754 rounding mode the Visual Studio (2022) C++ compiler uses when the _RC_NEAR flag is used to switch floating-point rounding modes.
This MS doc page shows examples for switching rounding to + and - infinity, along with specifying the default rounding method (turns out it is _RC_NEAR if you look in float.h), but I can't find any more detail about _RC_NEAR, if that corresponds to ties to even or ties away from zero, as mentioned on the wikipedia page.


text:
Q: Prevent 'lein repl' in SublimeREPL from echoing the previous command I'm running Sublime Text 3 Build 3117 on both OS X 10.10.5 and Ubuntu 16.04. I just installed Leiningen 2.6.1 on both, and I'm starting to play around in SublimeREPL. I'm following the lein tutorial. Here is my project.clj, in case it matters:
(defproject my-stuff "0.1.0"
  :description "Leiningen Tutorial Project"
  :url "http://example.com/FIXME"
  :license {:name "MIT"
            :url "http://opensource.org/licenses/MIT"}
  :dependencies [[org.clojure/clojure "1.8.0"]]
  :main ^:skip-aot my-stuff.core
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}}
  :repl-options {
    ;; custom prompt
    prompt (fn [ns] (str "> " ))
  }
)

Now, when I run lein repl in the my-stuff directory from the command line and run an arbitrary command (I've been using (+ 1 2 3)), it prints out the answer nicely:

However, if I run lein repl from SublimeREPL with project.clj focused, and run the same command, it echoes the command before printing the return value:

I've also created a lein trampoline run -m clojure.main command for SublimeREPL, and it doesn't have the echoing problem:

Basically, what I would like to do is be able to run a REPL using project.clj, but not have every command echoed before the output is printed. I can't seem to figure out how to run a trampoline REPL in Sublime using project.clj, if that's the best option. If there's a different way, i.e., using lein repl, I just want to get rid of the command echo, and make it look similar to what appears when I run it from the command line.

A: Thanks to some help at the Sublime Text Forum, I got an answer: you simply need to put "suppress_echo": true in the Main.sublime-menu file where the Clojure menu options are defined. In this case, open Packages/SublimeREPL/config/Clojure/Main.sublime-menu, put a comma , after "extend_env": {"INSIDE_EMACS": "1"}, then on the next line put "suppress_echo": true and you're all set.


text:
Q: how to modularize django settings.py? When you install a new django application, you have to add/modify your settings.py module.
For a project I'm trying to make that module a python subpackage and create a module for each application:
settings\
    __init__.py
    base.py
    admin.py
    feincms.py
    ...

The problem I'm confronted with is how to merge settings.py attributes (INSTALLED_APPS for example is a tuple of values) that are getting values in the different submodules?
Thanks

Ok, I asked the wrong question (got the right answer for it though). My question should have been, how to get attributes from all submodules and merge them? Django will import settings and expects everything to be there.

A: "When you install a new django application, you have to add/modify your settings.py module."
I think this is fine as is.
I don't see any reason to change or modify this at all.
What we do, however, is to "subclass" the core settings module.
Our developer-specific and installation-specific files have names like settings_devxy_linux2 and settings_checkout_win32, etc.
Each of these files starts with from settings import * to import the core settings and extend those core settings with overrides for a specific installation and platform.
It doesn't require any real work.  It does, however, mean that we do most things with django-admin.py because our settings aren't called settings.

A: You might be interested in this solution; uses execfile() to load a series of settings files in order, where each file has full access to settings from previously-loaded files, to update, modify, etc.

A: I've used this work-around:
settings.py:
INSTALLED_APPS = ('whatever',)
import more_settings
more_settings.modify(globals())

more_settings.py:
def modify(settings):
    settings['INSTALLED_APPS'] += ('another_app',)

A: I created https://code.djangoproject.com/wiki/SplitSettings#SettingInheritancewithHierarchy as my preferred solution. Allows for inheritance from a common file in any deployment environment.

A: I have the same structure of settings files and I do the following to import the settings of the submodules:
def load_settings_file(file):
    file = open(os.path.join(INSTALL_DIR, '<projectname>', 'settings', file + '.py'))
    content = file.read()
    file.close()
    return content

for submodule in ['base', 'admin', 'feincms']:
    exec(load_settings_file(submodule))

A: If you prefer more magic than in my previous more_settings.modify() approach, try this:
settings.py:
INSTALLED_APPS = ('whatever',)
import more_settings
more_settings.modify(globals())

more_settings.py:
def config(INSTALLED_APPS=(), **other_settings):
    INSTALLED_APPS += ('another_app',)
    del other_settings
    return locals()

def modify(settings):
    settings.update(config(**settings))

Pros: no need to refer to settings with dict notation
Cons: must define modified settings as kwargs for config()

A: Presumably the best way to "merge" varies, attributes by attributes.  For example, given several tuples (from the INSTALLED_APPS of various submodules), you might simply concatenate them into a new tuple (for the INSTALLED_APPS attribute of the package as a whole), or, if possible duplications are a problem, so something smarter to remove the duplications (in this case you may not care about ordering, so simply tuple(set(tup1+tup2+tup3)) might suffice).
For other cases ("merging" dictionaries, "merging" settings which are just scalars or strings, etc) you'll need different strategies (maybe successive .update calls for the dictionaries, pick just one according to some criteria for the scalars or strings, etc, etc) -- I just don't see a "one size fits all" approach working here.

A: just put
from base import *
from admin import *
...

in ur init.py
that should work
i used it for different sites
base/settings.py # common settings: db, apps, ...
base/sites/website1/settings.py # site_id, custom middleware
base/sites/website2/settings.py # site_id, custom middleware

the website settings import the common settings with
from base.settings import *

and define custom attribtues


text:
Q: Как реализовать логику "radio button" для
* элементов списка на React? Помогите пожалуйста решить проблему.

В React компоненте List есть элементы ListItem. Нужно при событии onClick для ListItem сделать, чтобы к нажатому элементу добавлялся класс active. Но при этом у других элементов, этого же списка, класс active пропадал. То есть нужно реализовать логику как у input type="radio", но для списка.

A: Вам придется в родительском компоненте <List> добавить в state состояние всех <ListItem> (какой из них active, а какой нет) и эти состояния передавать им через props-ы (каждому своё). так же обязательно нужно создать в родителе метод, который бы менял свой state при клике на каждый <ListItem> и передавать его в эти <ListItem>. это прием называется "всплытие состояния".
я бы написал Вам подробнее в коде, но, боюсь, у Вас только скриншот и очень неудобно. пожалуйста, напишите пример Вашего кода в письменной форме.


text:
Q: how to switch to other layout in zend framework? if i have 2 layout in my application how can change my default layout to other layout for some controller or action?

A: robertbasic's answer is correct. You can also do the following inside of a controller action:
$this->_helper->layout->setLayout('otherlayout');

A: Here you go:
$layout = Zend_Layout::getMvcInstance();
$layout->setLayout('otherlayout');

Where otherlayout is the name of the second layout (otherlayout.phtml in your layouts folder).

A: On my opinion, It is better to use
$layout = Zend_Layout::getMvcInstance();
$layout->setLayout('otherlayout');

in your view rather than use
$this->_helper->layout->setLayout('otherlayout');

from the controller.
The latter method has a bug. I had an experience where
I used
$this->_helper->layout->setLayout('otherlayout');

and the new layout was displayed inside the old layout.
I used
$layout = Zend_Layout::getMvcInstance();
$layout->setLayout('otherlayout');

then it worked


text:
Q: How to create a working executable jar file of a Java FX 8.0 Application In my java fx application I used mysql as the database.I developed this application using InteliJ IDE, and for the User interface I used scene builder and also I used jfoenix,jasper and mysql libraries in this project.I created artifact and build an executable jar file correctly but I got an exception when I runs that jar file.
"C:\Program Files\Java\jdk1.8.0_161\bin\java.exe" -Dfile.encoding=windows-1252 -jar D:\onetcoNew\onetco_pos_system\out\artifacts\onetco_pos_system\onetco_pos_system.jar
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javafx.fxml.LoadException:
file:/D:/onetcoNew/onetco_pos_system/out/artifacts/onetco_pos_system/onetco_pos_system.jar!/lk/onetco/fx/view/Login.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2848)
    at javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2692)
    at javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2661)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2517)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at lk.onetco.fx.main.Main.start(Main.java:27)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    ... 1 more
Caused by: java.lang.ClassNotFoundException: com.jfoenix.controls.JFXButton
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2916)
    at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2905)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2846)
    ... 20 more
Exception running application lk.onetco.fx.main.Main

Process finished with exit code 1


text:
Q: Using subset in R but got one particular subset with 0 rows I used R to subset a data set D (in CSV format) but D3 always contains 0 rows "<0 rows> (or 0-length row.names)." I checked the data set and did not find any missing values. What could be the problem with my data set? Thanks!
D <- read.csv(file="C:\\...\\D.csv", header = T, sep = ",")

D1 <- subset(D, Season == "Spring")
D2 <- subset(D, Season == "Summer")
D3 <- subset(D, Season == "Fall")

D3
[1] Cost
[2] Gender
[3] Participant
<0 rows> (or 0-length row.names)

names(D)
[1] "Cost"
[2] "Gender"
[3] "Participant"

unique(B$Season)
[1] Spring       Summer    Fall
3 Levels: Fall Spring Summer

I created a new data set containing only D3 (in CSV format), and the problem was gone. However, that was not an efficient solution.
Thanks everyone for all your suggestions! I just retyped every "Fall" in my original CSV data set, which somehow worked.

A: Before you're taking a subset, you should check the logical statement you're using. If your data frame is relatively small ( < 25 rows or so), then run:
D$Season == "Fall"

That will give you a vector like:
[1] TRUE TRUE FALSE FALSE FALSE TRUE

Or even:
which(D$Season == "Fall")

[1] 1 2 6

This is telling you which rows subset will select.
If you have a huge data frame, just do:
table(D$Season == "Fall")

This will tell you how many rows have the value Fall. I am willing do bet if you run table(D$Season == "Fall") you will see that all results come up FALSE


text:
Q: Get text and use for aria-label on each I want to get the text from each a.parent_link and apply it as an aria-label on each corresponding toggle button (button.sub-expand_collapse). The final result I want is if aria-expanded = true add aria-label= close + (text) and if aria-expanded = false add aria-label= expand + (text).
The first part gives me the text
$(".togSubList").each(function () {
        var bob = $(this).find(".parent_link").text();
        console.log(bob);
    });

But I can't get each one to add a the aria-label.
     $(".togSubList").each(function () {
        var bob = $(this).find(".parent_link").text();
        //console.log(bob);
        $(".sub-expand_collapse").each(function(){
            $(this).attr("aria-label","expand " + bob)
        });
    });

HTML

        <button class="sub-expand_collapse" aria-expanded="false">

        </button>

        Space saving widgets

            list of links

A: You  Don't need second each function because inside LI you have only one element so just use node traverse . and find the element like this . and apply the attribute .

$(".togSubList").each(function () {
        var bob = $(this).find(".parent_link").text();

        $(this).find(".sub-expand_collapse[aria-expanded='false']").attr("aria-label","expand " + bob);
         $(this).find(".sub-expand_collapse[aria-expanded='true']").attr("aria-label","close " + bob);

    });

        <button class="sub-expand_collapse" aria-expanded="false">

        </button>

        Space saving widgets

            list of links

A: Because you are already looping through each ".togSubList" you dont need to loop through each toggle button within that. Just use "this" as a reference and target both accordingly.
The only problem is that you will need to re-run the function whenever the button is expanded/collapsed.
$(".togSubList").each(function () {
    var bob = $(this).find(".parent_link").text();
    //console.log(bob);
    $(".sub-expand_collapse[aria-expanded='false']", this).attr("aria-label","expand " + bob);
    $(".sub-expand_collapse[aria-expanded='true']", this).attr("aria-label","close " + bob);
});


text:
Q: How do I get the external storage's path? I'm trying to write a file to my phone.
I used Environment.getDataDirectory() to know the internal storage's path and Environment.getExternamStorageDirectory() to know the external storage's path.
But when I use Environment.getExternalStorageDirectory() as path, the file is created in internal storage. And when I use Environment.GetDataStorage() as the path, the file is not created. (I am not sure, but I can't find it in the explorer app, at least.)
I think my phone's internal storage is perceived as external storage.(In my case, it has 32 GB amount of storage)
I want to know removable storage(e.g. micro SD card) path. What should I do?

A: From the official documentation for getExternalStorageDirectory()

Don't be confused by the word "external" here. This directory
can better be thought as media/shared storage. It is a filesystem that
can hold a relatively large amount of data and that is shared across
all applications (does not enforce permissions). Traditionally this is
an SD card, but it may also be implemented as built-in storage in a
device that is distinct from the protected internal storage and can be
mounted as a filesystem on a computer.

So, it can be different from built-in storage in a device.
For your case, you could use getExternalStoragePublicDirectory(java.lang.String)

This is where the user will typically place and manage their own
files
The path here should be one of DIRECTORY_MUSIC, DIRECTORY_PODCASTS,
DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS,
DIRECTORY_PICTURES, DIRECTORY_MOVIES, DIRECTORY_DOWNLOADS, or
DIRECTORY_DCIM. May not be null.

Or if you want your data to be deleted whenever the user uninstalls your app, you could use getExternalFilesDir().
As these files are internal to the applications, and not typically visible to the user as media.
Also there are some differences between getFilesDir() and getExternalFilesDir()

*

*External files are not always available: they will disappear if the user mounts the external storage on a computer or removes it. See the APIs on environment for information in the storage state.

*There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.

A: Try this...
static String storagestate = Environment.getExternalStorageState();

    private static FileOutputStream outStream;
    private static File imageFilepath;

    public static String saveImage(Bitmap bitmap) {
        File folder = null;

        // Check for SD card
        if (storagestate.equals(Environment.MEDIA_MOUNTED)) {
            folder = new File(Environment.getExternalStorageDirectory(),
                    "*YourStorageNameInDevice");
            if (!folder.exists()) {
                folder.mkdir();
            }
            outStream = null;

            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
                    .format(new Date());

            // Getting filepath
            imageFilepath = new File(folder.getPath() + File.separator
                    + timestamp + ".PNG");
            try {
                outStream = new FileOutputStream(imageFilepath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                outStream.flush();
                outStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return imageFilepath.getAbsolutePath();
    }
}


text:
Q: Returning non-copyable non-movable object with explicit constructor If we have a non-movable, non-copyable class with non-explicit constructor, we can return it and use as follows (in C++11):
#include <iostream>
class NonCop
{
public:
    /*non explicit*/ NonCop(int a, int b) : number(a + b) {}
    NonCop(const NonCop&) = delete;
    int number;
};

NonCop get_non_cop()
{
    return {1, 2};
}

int main()
{
    NonCop &&nc = get_non_cop();
    std::cout << "three: " << nc.number << std::endl;
    return 0;
}

However if the constructor is explicit, it doesn't work. Is there any method of doing this in C++11/C++14 with no modifications in NonCop?
Currently I'm using workaround with deriving from NonCop with wrapper that "deexplicits" the constructor but it doesn't seem very pretty.

A: No, this isn't possible.  There is no mechanism to call explicit constructors while returning from a function in C++11 or 14 without having an implicit move or copy (that the compiler will certainly elide).
In C++17 you can just type return NonCop(1,2); and due to "guaranteed elision" it will no longer require a move or copy constructor.

But this is C++, so yes, I can make your code work with zero additional overhead.  By cheating, and returning a different type.
template<class T>
struct implicit_construct:T {
  template<class...Ts>
  implicit_construct(Ts&&...ts):
    T(std::forward<Ts>(ts)...) // note: this is an EXPLICIT construction
  {}
};

implicit_construct<NonCop> get_non_cop()
{
  return {1, 2};
}

Live example.
An implicit_construct<NonCop> derives from a NonCop, so you can store the return value in a NonCop&&.

If you are writing NonCop yourself, then what I'd do is add:
 struct explicit_construct_t {};
 // ...
 struct NonCop {
   // ...
   template<class...Ts>
   NonCop( explicit_construct_t, Ts&&...ts ):
     NonCop( std::forward<Ts>(ts)... )
  {}
  // ...
};

which means you can call explicit constructors by prefixing it with a explicit_construct_t to call them implicitly:
NonCop get_non_cop() {
  return {explicit_construct_t{}, 1, 2};
}

A: Unfortunatelly, in this context you can't return the temporary object, since in a return by value expression the compiler requires that the object's copy constructor is accessible, even if this object is going to be copy elided in the end. However, you could return a std::unique_ptr instead of concrete object.
std::unique_ptr<NonCop> get_non_cop() {
    return std::make_unique<NonCop>(1, 2);
}

Live Demo


text:
Q: PHP MongoDB update multiple documents using $in/$or I'm having trouble figuring out how to construct an update query in PHP that will update document IDs X,Y, and Z. Does anyone have experience with this?
$ids[] = array(
  new MongoId('4eaaf929498fe2c80300000c'),
  new MongoId('4eaaff24498fe2ba0900001f')
);
$collection->update(
  array('_id' => array('$in' => $ids)),
  array('$set' => array("title"=>"test")),
  array("upsert" => true)
);

A: I assume that your trouble is, that only one document get's updated, right? If this is the case, there is another setting you have to specifiy in the third parameter (the options parameter) for the update method:
multiple => true

Otherwise, it will only update the first match of your query. See the documentation to the update method at:
http://de.php.net/manual/en/mongocollection.update.php


text:
Q: Oracle to_char subquery in Trigger I have a table (Meeting) with date type attribute (MeetDate) and another varchar2 type attribute (WorkWeek). I'm trying to do an After trigger to fill in the WorkWeek field based on the MeetDate value using the to_char function. Tried the following codes separately and they compile without errors but when I try to insert a row with Null for WorkWeek, it gives me a 'mutating trigger/function may not see it' error. What am I doing wrong here? thanks in advance to any help.
--Code 1
Create or Replace Trigger Update_WorkWeek
After Insert On Meeting
For Each Row
Begin
Update Meeting
Set WorkWeek  = (Select to_char(:new.MeetDate, 'YYYY IW') From Dual)
Where MeetID = :new.MeetID;
End;
/
show Errors;

--Code 2
Create or Replace Trigger Update_WorkWeek
After Insert On Meeting
For Each Row
Begin
if :New.WorkWeek is Null then
Update Meeting
Set WorkWeek  = (Select to_char(:new.MeetDate, 'YYYY IW') From Dual)
Where MeetID = :new.MeetID;
End if;
End;
/
show Errors;

A: You just want a trigger to change the value of a column before it gets inserted - and it's on the same row, so you don't need an UPDATE:
Create or Replace Trigger Update_WorkWeek
BEFORE Insert On Meeting
For Each Row
Begin
  :new.WorkWeek := to_char(:new.MeetDate, 'YYYY IW');
End;
/
show Errors;

You might want the column kept up-to-date if the MeetDate is changed, i.e.:
Create or Replace Trigger Update_WorkWeek
BEFORE Insert
    OR Update OF MeetDate
On Meeting
For Each Row
Begin
  :new.WorkWeek := to_char(:new.MeetDate, 'YYYY IW');
End;
/
show Errors;


text:
Q: Should I avoid using object spread in reduce? Given the following example:
// option 1
items.reduce((values, item) => ({
     ...values,
     [item.id]: item.name
}), {})

// option 2
items.reduce((values, item) => {
    values[item.id] = item.name;
    return values;
}, {});

Is there a best practice pro or contra using object spread syntax in this case?

A: Option 2 is clearly preferable for performance reasons:

*

*Option 1 runs in O(n²) time, since the spread syntax copies O(n) properties on each iteration. Option 2 runs in O(n) time.

*Option 1 creates O(n²) garbage, since it creates a garbage object of size O(n) on each iteration. Option 2 creates no garbage.

That said, in most cases you should just write this with a plain old for loop:
let result = {};
for(let item of items) {
    result[item.id] = item.name;
}

It is not bad to use for loops, and the code is even more readable than the two options in the question. Option 2 may seem like it is more in the functional programming style, but if you are using mutation to achieve your desired result then you are not really doing functional programming.
See this article for a more in-depth discussion of why Option 1 is an antipattern.

A: In the first code, you're creating a new object for every iteration of .reduce. In certain engines, this may be slightly less efficient than your second code, which only creates a single object. (That said, efficiency rarely matters much; code clarity is much more important in most situations).
But, for this situation, there's an even more suitable method to use when creating an object from an array, which avoids the slightly clunky syntax of reduce:
const output = Object.fromEntries(
  items.map(item => [item.id, item])
);

const items = [
  { id: 5, val: 5 },
  { id: 10, val: 10 },
  { id: 15, val: 15 },
];
const output = Object.fromEntries(
  items.map(item => [item.id, item])
);
console.log(output);

That said, keep in mind that Object.fromEntries is a relatively new feature, so if this is meant for a public-facing website, make sure to include a polyfill.

A: ...values will create a shallow copy of your array each time, which may prove costly if the array is large. Setting the property on the accumulator, on the other hand, is more efficient. That being said, you could determine that your array is certain to be small enough that you'd prefer the terseness of the spread syntax.


text:
Q: How To Use Decimal Numbers In JavaScript Math? I have a calculation where I need to multiply the values of two different inputs, add the value of a third, and put that value into the other input. The first input will sometimes have a decimal point number (EX: 3.2) while the second number has commas for thousands, millions, etc... I then need to properly multiply those two numbers into each other, add the third input value, and put the result into the fourth input correctly.
Right now the behavior is a bit strange, sometimes the decimal number 3.2, for example, will be used as 32. I have tried a few different solutions to similar problems, but they did not produce the results I need or also had odd behavior. The toFixed() method sometimes creates numbers that are far too large. It may turn millions into quadrillions, for example.
EDIT: Sorry, I forgot to mention I have a third input value that needs to be added to the other two after multiplication. THIS is where the issue appears.

$(document).on("input", "#input-1, #input-2, #input-3", function() {
  var val1 = $("#input-1").val();
  var val2 = parseFloat($("#input-2").val().replace(/,/g, ''));
  var val3 = $("#input-3").val();
  var total = (val1 * val2) + val3;
  total = total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  $("#input-4").val(total).trigger("input");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <input id="input-1" type="text" value="3.2" />
  <input id="input-2" type="text" value="1,000,000" />
  <input id="input-3" type="text" value="3" />
  <input id="input-4" type="text" value="0" />
</div>

A: Try to cast input1's value to Number
var val1 = Number($("#input-1").val());

Also, you don't need parseFloat for the second input's value, if there would be no decimals. Anyway, you can wrap the result with Number() too.


text:
Q: How do I skip CRC check while processing images I have a program which processes images with imagick in PHP:
$image = new \Imagick();
$image->readImageBlob($fileSystem->read($file));

This process raises an error on CRC errors:
IDAT: CRC error `' @ error/png.c/MagickPNGErrorHandler/1643

There is nothing wrong with this image and I want to process it just like the rest of them, I don't care that the CRC check fails.


text:
Q: Comparing cohomology of a total complex with the cohomology of semidirect product $\DeclareMathOperator{\Tot}{Tot}$I have the following problem. Let $H$ and $G$ be groups such that $H$ acts on $G$, i.e., there exists a group homomorphism $H\to \mathrm{Aut}(G)$ and let $M$ be an abelian group treated as a trivial $G$- and $H$-module.
Further on, there is a double complex $C^{p,q}:= C^p(H,C^q(G,M))$ (I use here bar resolutions). To this double complex there are two spectral sequences associated, one of them is Lyndon--Hochschild--Serre spectral sequence. In particular, I know that both spectral sequences converge to $H^\ast(G\rtimes H, M)$. On the other hand, by the general construction of both spectral sequences, we know that they converge to $H^\ast(\Tot(C^{\ast \ast}))$.
My question is the following. If I have a specific cohomology class in $H^\ast(\Tot(C^{\ast \ast}))$, how can I decide to which class in $H^\ast(G\rtimes H, M)$ it corresponds? In particular, an answer to any of the following questions would do the job (I think):

*

*Is there an explicit map $H^\ast(\Tot(C^{\ast \ast}))\to H^\ast(G\rtimes H, M)$ giving the isomorphism? Or is there a cochain level map?

*Given a class in $H^2(\Tot(C^{\ast \ast}))$, how can I construct a group extension $1\to M \to E\to G\rtimes H\to 1$?

I am mostly interested in cohomology classes of degree 2 (as indicated by the second question). Also, reference would be enough.

A: Let me change the notation a little: let $\phi \colon H \to \operatorname{Aut}(N)$ be a group homomorphism, and consider $G = N \rtimes_\phi H$ (we will drop the subscript $\phi$ in the rest of this post). As usual, write $^hn$ for $\phi(h)(n)$ if $h \in H$ and $n\in N$.
The point is that the double complex $C^{\bullet\bullet}$ actually comes from a natural bi-cosimplicial abelian group, as follows:
Definition. Define the bisimplical set $X_{\bullet\bullet}$ via $X_{p,q} = N^{q+1}\times H^{p+1}$, where a morphism $(f,g) \colon ([p],[q]) \to ([p'],[q'])$ in $\Delta \times \Delta$ acts as
\begin{align*}
X_{p',q'} &\to X_{p,q}\\
\big(n_0,\ldots,n_{q'},h_0,\ldots,h_{p'}\big) &\mapsto \big(n_{f(0)},\ldots,n_{f(q)},h_{g(0)},\ldots,h_{g(p)}\big).
\end{align*}
Endow each $X_{p,q}$ with a $G$-action via
\begin{align*}
G \times X_{p,q} &\mapsto X_{p,q}\\
\big((n,h),(n_0,\ldots,n_q,h_0,\ldots,h_p)\big) &\mapsto \big(n\ {^hn_0},\ldots,n\ {^hn_q},hh_0,\ldots,hh_p\big)\\
\big((n,h),\big(\underline n,\underline h\big)\big) &\mapsto \big(n\ ^h\underline n,h\underline h\big).
\end{align*}
This is visibly functorial in $(p,q) \in \Delta^{\text{op}} \times \Delta^{\text{op}}$, so defines a bisimplicial $G$-set. Thus we can view $\mathbf Z[X_{\bullet\bullet}]$ naturally as a bisimplicial $\mathbf Z[G]$-module, and I claim that
$$\operatorname{Hom}_{\mathbf Z[G]}\big(\mathbf Z[X_{\bullet\bullet}],M\big) \cong C^{\bullet\bullet}\label{1}\tag{1}$$
as double complexes, for any $G$-module $M$ (not necessarily trivial). Indeed, note that
\begin{align*}
\operatorname{Hom}_{\mathbf Z[G]}\big(\mathbf Z[X_{p,q}],M\big) &\cong \operatorname{Map}_G\big(X_{p,q},M\big), \\
C^{p,q} &\cong \operatorname{Map}_H\big(H^{p+1},\operatorname{Map}_N(N^{q+1},M)\big).
\end{align*}
We have a bijection $\operatorname{Map}(X_{p,q},M) \stackrel\sim\to \operatorname{Map}(H^{p+1},\operatorname{Map}(N^{q+1},M))$, taking a function $\phi \colon X_{p,q} \to M$ to $\psi \colon H^{p+1} \to \operatorname{Map}(N^{q+1},M)$ given by
$$\psi\big(h_0,\ldots,h_p\big)\big(n_0,\ldots,n_q\big) = \phi\big(n_0,\ldots,n_q,h_0,\ldots,h_p\big).$$
Now $\psi$ has image in $\operatorname{Map}_N(N^{q+1},M)$ if and only if
$$\phi\big(n\underline n,\underline h\big) = n\phi\big(\underline n,\underline h\big) \qquad \text{for all } \big(\underline n, \underline h\big) \in X_{p,q}, \text{ all } n \in N.\label{2}\tag{2}$$
The $G$-action on $\operatorname{Map}_N(N^{q+1},M)$ is given by $(gf)(\underline n) = gf(g^{-1} \cdot \underline n)$, which is trivial on $N$ by definition of $\operatorname{Map}_N$. As action of $H$, it can be written explicitly by $(hf)(\underline n) = hf(^{h^{-1}}\!\underline n)$. This means that $\psi \colon H^{p+1} \to \operatorname{Map}_N(N^{q+1},M)$ is $H$-equivariant if and only if
$$\phi\big(\underline n,h\underline h\big) = h\phi\big({^{h^{-1}}}\!\underline n,\underline h\big) \qquad \text{for all } \big(\underline n,\underline h\big) \in X_{p,q}, \text{ all } h \in H.\label{3}\tag{3}$$
Combining \eqref{2} and \eqref{3} shows that $\psi \in C^{p,q}$ if and only if $\phi(g \cdot (\underline n,\underline h)) = g \phi(\underline n,\underline h)$ for all $(\underline n,\underline h) \in X_{p,q}$ and all $g$ in either $N$ or $H$. But this means exactly that $\phi \colon X_{p,q} \to M$ is $G$-equivariant, so
$$\operatorname{Map}_G\big(X_{p,q},M\big) \stackrel\sim\to \operatorname{Map}_H\big(H^{p+1},\operatorname{Map}_N\big(N^{q+1},M\big)\big).$$
This identification is natural in $p$ and $q$, giving the isomorphism \eqref{1}. This also shows that $C^{\bullet\bullet}$ is naturally a bi-cosimplicial abelian group.
In particular, the Eilenberg–Zilber theorem (nlab) shows that the totalisation of $C^{\bullet\bullet}$ is naturally chain homotopic (!) to the diagonal $dC^\bullet$ (i.e. $dC^n = C^{n,n}$). But the diagonal of $X_{p,q}$ is just the bar resolution of $G$, so we conclude that the inclusion $dX_\bullet \hookrightarrow X_{\bullet\bullet}$ induces a chain homotopy equivalence
$$\operatorname{Tot}C^{\bullet\bullet}\simeq C^\bullet(G,M).$$
Explicit descriptions of the map follow from sufficiently effective proofs of Eilenberg–Zilber. See for instance 8.5.4 in Weibel's An introduction to homological algebra. (For your direction, you need to use the Alexander–Whitney map on $\mathbf Z[X_{\bullet\bullet}]$, because the direction flips when applying $\operatorname{Hom}_{\mathbf Z[G]}(-,M)$.)
Concretely, the map $\operatorname{Tot}(C^{\bullet\bullet}) \to C^\bullet(G,M)$ takes a $(p,q)$-cocycle $f \colon X_{p,q} \to M$ to the $(r,r)$-cocycle $X_{r,r} \to M$ given by
$$\big(n_0,\ldots,n_r,h_0,\ldots,h_r\big) \mapsto f\big(n_p,\ldots,n_r,h_0,\ldots,h_q\big),$$
where $r = p+q$. (Here I am working with inhomogeneous cocycles, i.e. $G$-equivariant maps $G^{r+1} \to M$.)


text:
Q: How to do text search in API Documentation of Here iOS SDK Premium Edition? I'm developing an iOS project in Xcode using the Here SDK. I'm using the Premium Edition (v3.17).
I added the SDK to my project using CocoaPods. When I search my workspace I do not get any results from the HereSDK header files. E.g. when I search for "NMAProxyObject" I only get the results where I used that term in my own swift files.
The search function on the website gives much more results then the ones from the Premium iOS SDK.
Is there a way to search the API documentation of the premium iOS SDK only? Either through Xcode or otherwise?

A: In order to search in CocoaPods or other directories, you can define your own search scope in Xcode:

A: Once you download the SDK package, you will be able to find Developer Guide pdf inside user-guide folder. Also you can find all api references inside api_reference_jazzy_html_bundle_3.17. Search option is also available on the pages.


text:
Q: What things trigger Visual Studio to regenerate a *.Designer.cs file? Some form initialization issues I was having were traced to the .Designer.cs file overwriting values I had initialized in a user control's constructor.
I had designed a component (MyUserControl) and inserted it into a form (MainForm).  I later added some member initializations in MyUserControl's constructor, but the code that was in MainForm.Designer.cs for InitializeComponent() was stale, and code later in that functions was overwriting the my new initializations from the constructor called earlier in that function.
So, in essence, something I did triggered a rewrite of Mainform.Designer.cs but other activities didn't.
Is there a good reference that describes when the designer touches the *.Designer.cs files?  (Or is it a simple rule?) Jared Par pointed me to the DesignerSerializationVisibilityAttribute class but that seems to be one tree in the forest?

A: You specifically fell victim to having code for the old version of your UserControl still embedded in the form's InitializeComponent() method.  If you would have removed the control from the form before modifying the control code then you wouldn't have had the problem.  Removing it afterwards and putting it back would have fixed it too.
Yes, it is a simple rule.  InitializeComponent() is re-generated every time you add or remove a control to/from the form.


text:
Q: Getting error: Incorrect syntax near "-" while executing batch file I'm using this command:
SQLCMD -S %ServerName% -E -d %DBName% -Q "exec sp_Cust_Info %1 %2"

and get an error:

Incorrect syntax near "-"

Please help me with this


text:
Q: snap GPS points to sidewalks I have whole bunch of GPS coordinates collected from a device and sometimes they shift around 10m. Is there anyway to filter/modify points and snap them to sidewalks? So far I've written some javascripts to map those points to the center line of the nearest driving path but I still want them to be on sidewalks.
I noticed ArcGIS can display street curbs. Is there any way to extract the curbs? I cannot finde APIs for curbs at all.
There are some questions on this site regarding making sidewalk maps but no real solutions are available yet. I would prefer utilizing existing data sets like shape file and curbs to map points instead of adding sidewalks on google maps manually.

A: Take a look at ETGeoWizards.  The tool you are looking for is Global Snap Point (its in the Point section of the tool).  You could also look at Geospatial Modeling Environment from SpatialEcology.com.  They have a tool called snappoints.


text:
Q: Why close warning appears in Microsoft Edge? I'm working on a basic oauth authentication prototype and I have a HTML (called parent.html) opening a child window to serve the purpose. The child window would be redirected to the provider website and then to my registered page. My registered page would call window.close(); using javascript to close the child window.
But when I tried my prototype in Microsoft Edge, I noticed a close warning every time javascript tried to close the child window. I tested other websites which use popup window for oauth authentication like dropbox, I didn't see the same close warning when authentication was done and the child window was about to close.
Does anyone know why (and in what circumstance) does Edge show this warning dialog? Any information would be useful and appreciated. Thanks.

A: This is because of the popup blocker and automated script blocker features in MS Edge. Basically these two features will try to block any script that runs automatically without user's actions during the loading of the page.
For example, these two scripts will be blocked in MS Edge (they work in IE):
var w = window.open("page.htm"); //w will be null.

window.close(); //displays a warning.

The same two lines will work if you place them in a function and call them from a click event of a button, for example.

solution:
Create a function in the main window to close the popup window, and in the popup window call that function and pass it a reference to the popup window:
// in main window
function closePopup(w) {
    w.close();
}

// in popup window
opener.closePopup(this);


text:
Q: Kubernetes - kubectl version command fails Ubuntu 19.4
Just installed kubectl via snap: https://kubernetes.io/docs/tasks/tools/install-kubectl/
lky@lky-Z170-D3H:~$ kubectl version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.2", GitCommit:"66049e3b21efe110454d67df4fa62b08ea79a19b", GitTreeState:"clean", BuildDate:"2019-05-16T16:23:09Z", GoVersion:"go1.12.5", Compiler:"gc", Platform:"linux/amd64"}
The connection to the server localhost:8080 was refused - did you specify the right host or port?

Any ideas what could cause it?

A: it means that kubectl client version that you have installed is v1.14.2.
you cant connect to api server due to some issue, and hence kubernetes server version is not shown.
run below command to check kubernetes control plane health and take action on the components that are shown as UnHealthy
kubectl get cs

A: After installing kubectl, you have to configure it to use your cluster.
Almost any cloud providers, or bootstrappers such as kubeadm has easiest way to do it.
For example, on GKE you run below command to copy your cluster k8s config file, to localhost:
gcloud container clusters get-credentials ${CLUSTER}

For Kops:
kops export kubecfg ${CLUSTER}

For kubeadm you have to copy config file from master to your host machine. After completing kubeadm init command:
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

Note: /etc/kubernetes/admin.conf is located in master kubeadm node where you run kubeadm init, and you must copy this file to your host machine to use this cluster with kubectl.
Other useful links can be helpful:
Accessing first time with kubectl
Configure Access to Multiple Clusters
Hope it helps!


text:
Q: CSS media query not firing I have three stylesheets: a persistent one, one for windows 800px or greater ("standard"), and one for windows smaller than 800px ("mobile"). My problem is that the standard style sheet is being recognized and applied, but when I resize the window to under 800px, the mobile sheet is ignored and I'm left with only the persistent style. I suspect it's a basic syntax error, but I haven't been able to find the problem.
<link rel="stylesheet" type="text/css" href="persistentstyle.css">
<link rel="stylesheet" type="text/css" media="screen and (min-width:800px)" title="standard" href="style.css">
<link rel="stylesheet" type="text/css" media="screen and (max-width:799px)" title="mobile" href="mobilestyle.css">

I already have the necessary meta tag in the header:
<meta name="viewport" content="width=device-width" />

Thanks!

A: May be you need this:-
<meta name="viewport" content="width=device-width">

A: Generally, the most common mistake is not including the meta tag required for CSS media queries to work:
<meta name="viewport" content="width=device-width">

This link explains the viewport meta tag, and additional properties you can assign to it, such as allowing the screen to be scaled, and more.


text:
Q: Encoding problem in SQL Server 2008 I am trying to save a screen name in column on SQL Server 2008 without any special and international characters so that i can use that column in URL.
Can you guys please suggest some technique how to save this name in column with out any special or international characters.
Basic purpose of this is to use this column in URL.
Thank you very much.

A: You should urlencode the strings you store in the database instead of "removing" the invalid characters.
string url = "http://xyz.com/" + System.Web.HttpUtility.UrlEncode(myFieldContent);

This will replace the "special" characters with their corresponding percent encoding. See The RFC for more information.


text:
Q: Run a service (push notif) in a exact time repeatedly even if phone is in doze mode I want to run a service (push notification) in a specific time every day even if phone is in a doze mode l.
Using alarm manager with method of setExactAndAllowWhileIdle() has two issues first it just support sdk 23 and upper, second it cannot be repeated for every day

A: By the way, you should reschedule new alarm for next day after the time for this one comes.
And also you should note, that even this method of AlarmManager could be blocked in Doze mode.


text: Q: save value from Custom TextArea in Jqgrid to server using ajax I have a jqgrid with dynamic columns and model. In that grid I have textarea formatter in one column .I want to save values from all rows textarea in database on button click. I am able to do that successfully in IE but in Chrome and Firefox, jQuery("#tblAppendGrid").getRowData() is not providing values inputted in textarea.


text:
Q: Run python script as one of the command of command line tool I am new to Python, could someone please let me know if we can register our python script to work as one of the command of cmd.exe, I am not asking about parsing or accepting command line arguements using argparse, etc..
Lets say I have a SearchDir.py file, to run it from cmd prompt I have to do "python SearchDir.py", so is there any way to simply do "SearchDir" and it should act as one of the command of cmd.exe

A: Yes, it is possible (if I have understood you correctly. The question was a bit unclear)
The first thing you need to do is to add a shebang to the top of your script: https://en.wikipedia.org/wiki/Shebang_(Unix). I see you mentioned cmd.exe so I assume you need this to work on Windows? In that case you should read https://docs.python.org/3/using/windows.html#shebang-lines as well
On unix hosts, the second thing we need to do is set our file as executable with chmod +x <filename>. I try to stay away from Windows, but from what I remember this is not relevant on Windows.
Last you need to place the script in a folder referenced by your $PATH-variable
The script will now be accessible as SearchDir.py from cmd.exe or a unix shell. If you want to omit the ".py"-part you simply rename the file to just "SearchDir"


text:
Q: How to insert a space after insert node I want to insert a space after insert a node, the problem is the space that I insert is inside a node, not after the a node.
I have other solution, which is inserting a span and putting a space into the span node, but i think it should have a better solution.
var $preload = $('test.txt');
editor.insertNodeAtCaret($preload.get(0));
insertTextAtCursor('\u00A0', true);

function insertNodeAtCaret(node) {
   if (typeof window.getSelection != "undefined") {
       var sel = window.getSelection();
       if (sel.rangeCount) {
           var range = sel.getRangeAt(0);
           range.collapse(false);
           range.insertNode(node);
           range = range.cloneRange();
           range.selectNodeContents(node);
           range.collapse(false);
           sel.removeAllRanges();
           sel.addRange(range);
      }
  } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
       var html = (node.nodeType == 1) ? node.outerHTML : node.data;
       var id = "marker_" + ("" + Math.random()).slice(2);
       html += '';
       var textRange = document.selection.createRange();
       textRange.collapse(false);
       textRange.pasteHTML(html);
       var markerSpan = document.getElementById(id);
       textRange.moveToElementText(markerSpan);
       textRange.select();
       markerSpan.parentNode.removeChild(markerSpan);
    }
};

function insertTextAtCursor(text, moveTheCursor) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            var textNode = document.createTextNode(text);
            range.insertNode(textNode);
                if(moveTheCursor){
                    range.setStartAfter(textNode);
                    sel.removeAllRanges();
                    sel.addRange(range);
                 }
        }
   } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().text = text;
    }
  };

A: I suggest adapting insertNodeAtCaret to insert multiple nodes:

function insertNodesAtCaret() {
    var i, len, node, sel, range, html, id;
    var escapeHtml = function(text) {
        var div = document.createElement("div");
        div.appendChild( document.createTextNode(text) );
        return div.innerHTML;
    };

    if (typeof window.getSelection != "undefined") {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.collapse(false);
            for (i = 0, len = arguments.length, node; i < len; ++i) {
                node = arguments[i];
                if (typeof node == "string") {
                    node = document.createTextNode(node);
                }
                range.insertNode(node);
                range.setStartAfter(node);
                range.collapse(true);
            }
            range = range.cloneRange();
            range.selectNodeContents(node);
            range.collapse(false);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        html = "";
        for (i = 0, len = arguments.length, node; i < len; ++i) {
            node = arguments[i];
            if (typeof node == "string") {
                html += escapeHtml(node);
            } else if (node.nodeType == 1) {
                html += node.outerHTML;
            } else if (node.nodeType == 3) {
                html += escapeHtml(node.data);
            }
        }
        id = "marker_" + ("" + Math.random()).slice(2);
        html += '';
        var textRange = document.selection.createRange();
        textRange.collapse(false);
        textRange.pasteHTML(html);
        var markerSpan = document.getElementById(id);
        textRange.moveToElementText(markerSpan);
        textRange.select();
        markerSpan.parentNode.removeChild(markerSpan);
    }
}

function insertElementAndSpace() {
    var aEl = document.createElement("a");
    aEl.href = "http://stackoverflow.com?";
    aEl.appendChild( document.createTextNode("LINK TEXT") );

    insertNodesAtCaret(aEl, "\u00a0");
}
<input type="button" onmousedown="insertElementAndSpace(); return false;" value="Insert">

    This is some editable text. Put the caret somewhere in here and press the button.


text:
Q: image is not so clear after using this as background image The original image is in a folder and being accessed by background-image CSS property to be used in a div as background image. But it does not look same as the original image. I have tried CSS3 cover, image-rendering etc to fix this but still no change in output. I also tried CSS3 filters but nothing changed.
Original Image

Image as div background

The code I tried:
width: 48px;
height: 48px;
background-image: url(img/15294860.jpeg)

A: Check below snippet i think it's looking proper. just add background-repeat: no-repeat; to remove repeat image.

.image {
  width: 48px;
  height: 48px;
  background-image: url('https://i.stack.imgur.com/Aa1XR.jpg');
  background-repeat: no-repeat;
    background-size: cover;
}

A:

.background {
  width: 48px;
  height: 48px;
  background: url("https://vignette.wikia.nocookie.net/lego/images/1/16/Harrypottery5-7-200x200.jpg/revision/latest?cb=20111021110949")no-repeat;
    background-size: cover;
}


text:
Q: Cannot create file '*.mdf' because it already exists I am using Entity-Framework in a Winforms application. The application connects to MSSQLServer and everything works fine. Then I detach the database and copy the .mdf file to the app folder and change the connection string to use the local .mdf file, still everything works fine.
The problem is that when I copy my application together with the database to another PC suddenly EF tries to recreate the database and throws this error:

Cannot create file 'Path\MyDatabaseName.mdf' because it already exists.
  Change the file path or the file name, and retry the operation. CREATE
  DATABASE failed. Some file names listed could not be created. Check
  related errors.

Context Initializer is set to MigrateDatabaseToLatestVersion:
Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, DAL.Migrations.Configuration>("MyConnectionString"));

Also, automatic migration is off and database is created by EF Code-First on Sql-server and is already updated to the latest migration so no migration is needed.
Connection string for the first scenario is:
<add name="MyConnectionString" connectionString="Server=DESKTOP-XXXXXXX; Database=MyDatabase; Integrated Security=True; Connect Timeout=30;" providerName="System.Data.SqlClient">

and for local .mdf file is:
<add name="MyConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\MyDatabase.mdf; Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />

So, What is going on here??

A: In my case, go to C:\Program Files\Microsoft SQL Server\SQLSERVER\MSSQL\DATA folder and delete the same database name '*.mdf' file if exist. After deleting it and recreate the database, the problem is resolved.

A: For SQL Server running in docker:
Since I am using an SQL server in docker I have to get inside the docker using docker exec -it <CONTAINER ID> bash and delete mdf file from the/var/opt/mssql/data directory.
Steps:

*

*docker ps -> Copy CONTAINER ID of the docker container running SQL Server

*docker exec -it <CONTAINER ID> bash -> Now you can view/modify a file inside the docker

*cd /

*cd /var/opt/mssql/data -> To go to the directory of mdf/ldf file

*rm -rf <database_name>.mdf -> To delete mdf file

*rm -rf <database_name>_log.ldf -> To delete ldf file

This resolves my issue.


text:
Q: Looking for best practices to test stored procedures? We use sql server 2008 and my boss insist on testing stored procedures.
What is the best practice on testing stored procedures?
Do you use any tools ?
what is your approach?
thanks

A: Unit testing with a framework like DbUnit and DbFit is invaluable.  Having the discipline to test means also knowing what the before and after data should be, encoding tests for edge cases when you find bugs and so on.
We keep a database available in dev that contains idealised test output data for comparing data sets with in the main dev database.  Helps to write the tests.


text:
Q: Utilize model methods and properties in another model Thank you in advance for your help.
I am using inheritance to leverage properties from a base mode like this: HomeModel : BaseModel.
This is working as expected, but now I want to take it one step further. I want to use it one additional level down so the new model inherits everything from HomeModel.
I created a NavModel like this
public class NavModel : HomeModel {
    public string CloudVersion{get;set;}
    public IMxUser Usr {get;set;}
    public ILocalizer Localizer {get;set;}
    public NavModel(IMxUser mxUser, ILocalizer localizer)
    {
        Localizer = localizer;
        Usr = mxUser;
        CloudVersion = ConfigurationManager.AppSettings["cloudVersion"];
    }
}

but  it threw the error
'HomeModel' does not contain a constructor that takes 0 arguments.

Is it a bad idea for me to daisy-chain like this? What am I doing wrong? Is there a better approach?
UPDATE
Prior to adding the empty constructor, this is the standard HomeModel constructor:
public HomeModel(IMxUser mxUser, ILocalizer localizer)
{
    Localizer = localizer;
    Usr = mxUser;
    BomSearchJavascriptMethod = GetSearchJavascriptMethod(MnxConst.SearchOptions.BILL_OF_MATERIAL, EnterBOMSearchKeyStr);
    POSearchJavascriptMethod = GetSearchJavascriptMethod(MnxConst.SearchOptions.PURCHASE_ORDER_NUMBER, EnterBOMSearchKeyStr);
}

It would be nice if I could leverage the standard HomeModel in related models, but I am not sure how to pass those with my current method of reference.

A: You have to initialize the base class as well using the initializer like this:
public HomeModel(IMxUser mxUser, ILocalizer localizer)
  : base(mxUser, localizer)
{
    // ...
}


text:
Q: How can i get the output on how many times the program has looped? How can i get the output on how many times the program has looped?
Example output :
Enter Your Name: Harith

Harith, Please enter 4 numbers

Number 1:6

Number 2:7

Number 3:5

Number 4:10

Smallest = 5
Largest = 10

This program has repeated for 2 times.

Heres is my code:
import java.io.*;
class loop
{
public static void main(String args[])throws IOException
{
    BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
    String temp,name;
    int number,largest,smallest;
    System.out.print("Enter Your Name: ");
    name = cin.readLine();
    int num[] = new int[4];
    System.out.println(name+", Please enter 4 numbers");
    for(int i=0;i<4;i++)
    {
        System.out.print("Number "+(i+1)+":");
        temp = cin.readLine();
        num[i] = Integer.parseInt(temp);
    }
    largest=num[0];
    smallest=num[0];
    for(int i=0;i<4;i++)
    {
        if(num[i]>largest)
        {
            largest=num[i];
        }
        else if(num[i]<smallest)
        {
            smallest=num[i];
        }
    }
    System.out.println("Smallest = "+smallest);
    System.out.println("Largest = "+largest);

}
}

A: If you just want to know how many times the loops looped, introduce a variable for example int loopCounter = 0;
Then before the end of each loop in your program increment that variable by one and at the end print that variable.
For example.
import java.io.*;

class loop {

    public static void main(String args[]) throws IOException {
        int loopCounter = 0;
        BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        String temp, name;
        int number, largest, smallest;
        System.out.print("Enter Your Name: ");
        name = cin.readLine();
        int num[] = new int[4];
        System.out.println(name + ", Please enter 4 numbers");
        for (int i = 0; i < 4; i++) {
            System.out.print("Number " + (i + 1) + ":");
            temp = cin.readLine();
            num[i] = Integer.parseInt(temp);
            loopCounter++;
        }
        largest = num[0];
        smallest = num[0];
        for (int i = 0; i < 4; i++) {
            if (num[i] > largest) {
                largest = num[i];
            } else if (num[i] < smallest) {
                smallest = num[i];
            }
            loopCounter++;
        }
        System.out.println("Smallest = " + smallest);
        System.out.println("Largest = " + largest);
        System.out.println("Looped " + loopCounter + " times.");

    }
}

A: Please put one variable to count  the loop iteration
package com.test.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A1 {

    public static void main(String args[])throws IOException
    {
        BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        String temp,name;
        int largest,smallest;
        System.out.print("Enter Your Name: ");
        name = cin.readLine();
        int num[] = new int[4];
        System.out.println(name+", Please enter 4 numbers");
        int loopCount = 0;
        for(int i=0;i<4;i++)
        {
            System.out.print("Number "+(i+1)+":");
            temp = cin.readLine();
            num[i] = Integer.parseInt(temp);
            loopCount++;
        }
        System.out.println("Loop Counted :: "+loopCount);
        largest=num[0];
        smallest=num[0];
        for(int i=0;i<4;i++)
        {
            if(num[i]>largest)
            {
                largest=num[i];
            }
            else if(num[i]<smallest)
            {
                smallest=num[i];
            }
        }
        System.out.println("Smallest = "+smallest);
        System.out.println("Largest = "+largest);

    }
}

A: import java.io.*;
class loop
{
public static void main(String args[])throws IOException
{
    BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
    String temp,name;
    int number,largest,smallest;
    System.out.print("Enter Your Name: ");
    name = cin.readLine();
    int num[] = new int[4];
    System.out.println(name+", Please enter 4 numbers");
    for(int i=0;i<4;i++)
    {
        System.out.print("Number "+(i+1)+":");
        temp = cin.readLine();
        num[i] = Integer.parseInt(temp);
    }
    largest=num[0];
    smallest=num[0];
    int i;
    for(i=0;i<4;i++)
    {
        if(num[i]>largest)
        {
            largest=num[i];
        }
        else if(num[i]<smallest)
        {
            smallest=num[i];
        }
    }
    System.out.println("Smallest = "+smallest);
    System.out.println("Largest = "+largest);
    System.out.println("The loop has executed "+i+" times");
}
}

A: Here's my answer after a few try and error. Thanks for help.
import java.io.*;
    class loop
    {
        public static void main(String args[])throws IOException
        {
            BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
            String temp,name;
            int largest,smallest,time=0,i;
            do{
            System.out.print("Enter Your Name: ");
            name = cin.readLine();
            int num[] = new int[4];
            System.out.println(name+", Please enter 4 numbers\n");
            for(i=0;i<4;i++)
            {
                System.out.print("Number " +(i+1)+":");
                temp = cin.readLine();
                num[i] = Integer.parseInt(temp);
            }
            largest=num[0];
            smallest=num[0];
            for(i=0;i<4;i++)
            {
                if(num[i]>largest)
                {
                    largest=num[i];
                }
                else if(num[i]<smallest)
                {
                    smallest=num[i];
                }
            }
            System.out.println("Smallest = "+smallest);
            System.out.println("Largest = "+largest+"\n");
            time++;
            }while(smallest<=5);
            System.out.println("The program has been repeated for "+(time)+" times");
            System.out.print("Thanks You!!");
        }
    }


text:
Q: Setting Active Admin namespace using active admin config I am using active admin with devise and im trying to set namespace for all my active admin routes.
In active_admin.rb i have set the default_namespace as,
config.default_namespace = :abc_123

In the route i have,
  devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)

The routes generated are such,
                           root GET        /                                              pages#home
         new_admin_user_session GET        /abc_123/login(.:format)                  active_admin/devise/sessions#new
             admin_user_session POST       /abc_123/login(.:format)                  active_admin/devise/sessions#create
                     admin_root GET        /admin(.:format)                              admin/dashboard#index
              abc_123_root GET            /abc_123(.:format)                        abc_123/dashboard#index
            abc_123_quotes GET            /abc_123/quotes(.:format)                 abc_123/quotes#index
                           POST           /abc_123/quotes(.:format)                 abc_123/quotes#create
         abc_123_quote     GET        /abc_123/quotes/new(.:format)             abc_123/quotes#new
        edit_abc_123_quote GET        /abc_123/quotes/:id/edit(.:format)        abc_123/quotes#edit
             abc_123_quote GET        /abc_123/quotes/:id(.:format)             abc_123/quotes#show
batch_action_abc_123_users POST       /abc_123/users/batch_action(.:format)     abc_123/users#batch_action
             abc_123_users GET        /abc_123/users(.:format)                  abc_123/users#index

The login works i am able to login with my activeadmin account but on dashboard it breaks with the error,
ActionView::Template::Error (undefined method `abc123_users_path' for ActiveAdmin::Helpers::Routes:Module):
1: insert_tag active_admin_application.view_factory["page"]

It breaks for all the other active admin page too with the same error.
I don't have the 'abc123_users_path' path in my route. Im not getting from where this route is getting added to the active admin page.


text:
Q: ServerSocket times out and exits server program I'm trying to implement a server that accepts connections but times out and closes that specific connection only if it hasn't received anything from that connection after N milliseconds.
From my possible misunderstanding of ServerSocket's setSoTimeout(int milliseconds) method, I thought this behaviour could be accomplished by passing N to setSoTimeout.
What I'm experiencing is once a client makes a connection, and doesn't send anything over that connection for N seconds, the server catches a SocketTimeoutException, but then completely stops execution and ends the process running the server program. Here is my server's listen method:
    private static void listen() throws IOException {
    while(true) {
        try {
            Socket clientSocket = serverSocket.accept();
            Connection connexion = new Connection(clientSocket);
            connexion.start();
        } catch (SocketTimeoutException e) {
            System.out.println("Socket timed out!");
            break;
        }
    }
}

I successfully catch the SocketTimeoutException, ignore it (bad I know!) and assume that the client connection that caused the exception gets closed. Then I just break out of the catch block to continue accepting other client connections. What am I missing here?

A: You need to add continue; instead of break; in the try-catch clause. The server will keep listening.

A:
assume that the client connection that caused the exception gets closed.

Incorrect assumption. The accept() is what has timed out. The client connection hasn't done anything yet.

Then I just break out of the catch block to continue accepting other client connections.

Err, no, you break out of the catch block to stop accepting other client connections. You're breaking out of the accept loop.

What am I missing here?

A continue instead of a break.
If you don't care about the SocketTimeoutException why are you setting a socket timeout on the ServerSocket? Just remove that.


text:
Q: How to move file from on folder to another folder as a different user? how to move file from on folder to another folder as a different user.
I am general user I don't have write access, hence I cant write or modify or paste any file in specific folder (C:\test).
If I login as admin user I can write or modify or paste the files in (C:\test)
I wanted to write python code which can do this activity.
I tried, shutil but not help following is my code:
shutil.move(source+f, dest1)

Could someone help to paste file from one folder to another folder as a different user?


text:
Q: Wordpress query post get Image unless blank Hi I am creating a wordpress custom page theme, I have included the code. Is there a way to dynamically add the list items. In the code I grab each image related to its post with screenshot1 screenshot2 so on...  This all currently works. My problem is at the current moment if I upload 2 screen shots 3 list items will show up and the third will just be blank. So how could I dynamically add them based on the number of images in the post?
query_posts('cat=3'); /*--Query to grab Projects categorie--*/

while (have_posts()) : the_post();  /* --- loop through the posts in that categorie */

<?php
$screen1 = get_post_meta($post->ID, 'screenshot1', true);
$screen2 = get_post_meta($post->ID, 'screenshot2', true);
$screen3 = get_post_meta($post->ID, 'screenshot3', true);
echo "
" . wp_get_attachment_image($screen1, 'large') . "
";
echo  "
" . wp_get_attachment_image($screen2, 'large') . "
";
echo  "
" . wp_get_attachment_image($screen3, 'large') . "
";
?>

A: Loop through the possible meta values and only output it if it's not empty.
Something like:

<?php
$i = 1;
while ($screen = get_post_meta($post->ID, 'screenshot'.$i , true)) {
    echo "
" . wp_get_attachment_image($screen, 'large') . "
"
    $i++;
}
?>


text:
Q: How many different ways are possible Twenty students, including John, Casey and Michelle, are candidates to serve on a
committee of six.
(a) How many different ways of committees are possible if contain three of them?
My attempt(Not sure it is correct)
20C3 - 6C3 = 1120
(b) How many different ways of committees are possible if contain at least one of them?
My attempt(Not sure it is correct)
20C3 - 6C1 = 1134
Please help to check if it's correct, thanks alot...

A: Here are some hints.
For part (a), you know three of the members will be John, Casey, and Michelle.  So how many ways can you choose the other three people from the remaining $17$?
For part (b), one way to do this is to calculate the number of all possible committees, and then subtract out those committees that do not have John, Casey, or Michelle.  What remains will have at least one of them.
How many total possible committees are there?  How many committees don't have John, Casey, or Michelle?


text:
Q: Automatic capitalization of section headings I have a large project (report class) in which I am importing separate files.
What I would like to do is capitalise each word in the titles of chapter/section/subsection in the main document and table of contents just as how normally book titles are organized. How would I achieve the desired outputs (please see at the bottom of the post) within the report class?
\documentclass[a4paper,11pt]{report}
\usepackage[utf8]{inputenc}
\usepackage{import}
% For subsubsection in report class
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}

%%%%%%%%%%%%%%%%%%%%%
% LINE SPACING
\newcommand{\linespacing}{1.5}
\renewcommand{\baselinestretch}{\linespacing}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\pagestyle{plain}
% ANY OTHER DECLARATIONS HERE:
%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HYPERREF
\usepackage[colorlinks,pagebackref,pdfusetitle,urlcolor=blue,citecolor=blue,linkcolor=blue,bookmarksnumbered,plainpages=false]{hyperref}

% For capitalization of all label names throughout the document (not working)

%%%%%%%%%%%%%%%%%%%%%
\begin{document}

% TABLE OF CONTENTS, LISTS OF TABLES & FIGURES
\newpage
\pdfbookmark[0]{Contents}{contents_bookmark}
\tableofcontents
%%%%%%%%%%

\chapter{Introduction}
\input{file1}

\end{document}

In file1.tex, I have these.
    \section{section file1}\label{file1}
    \subsection{capital letter for first letters except for `and', `in', `for', etc.}
    \subsubsection{the theory of everything}
    \subsubsection{how it works}
    \subsubsection{relationship between A and B}

The desired outcome would be


text:
Q: Cant load protobuf message with protobuf.js Im trying to use proto messages with protobuf.js, encode them and send them to a RabbitMQ message broker. I have the following sub-folders inside my project:
- model
    - protos
        - transactions.proto
    - RabitMQ.js
- routes
    - rmq-api.js

I added a route which does the following(Using express) in the rmq-api.js file:
const RabbitMQ = require('../model/RabbitMQ');

router.post('/api/transactions' ,function (req,res,next) {
    RabbitMQ.PublishTransactionsMessage(DummyMessage).then(() => {
      res.status(200).send({message: "OK :)"});
    }).catch((e) => {
        res.status(500).send({error:e.message});
    });
});

In the RabitMQ.js file I have the following code:
module.exports = {
    PublishTransactionsMessage: function(message) {
        return new Promise((resolve, reject) => {
            amqp.connect(RabbitMQConfig.url, function (error, connection) {
                if (error) {
                    console.error("Could not connect to the rabbit message broker on {0} - " +
                        "Check connection please and try again".format(RabbitMQConfig.url));
                    console.error("Error message - {0}".format(error));
                    reject(error)
                }
                connection.createChannel(function(error, channel) {
                    if (error) {
                        console.error("Could Create channel - {0}".format(error.message));
                        reject(error)
                    }
                    const queue = RabbitMQConfig.queue;
                    channel.assertQueue(queue, {
                        durable: true
                    });
                    // Convert Message to protobuff
                    protobuf.load("./protos/transactions.proto").then((err, root) => {
                        if (err) {
                            reject(err);
                        }
                        let ScraperMessageResult = root.lookupType("transactions.ScraperMessageResult");
                        const errMsg = ScraperMessageResult.verify(message);
                        if (errMsg)
                            reject(errMsg);
                        let buffer = ScraperMessageResult.encode(message).finish();
                        channel.sendToQueue(queue, buffer);
                        console.log(`Sent ${message} to queue: ${queue}`);
                        resolve()
                    }).catch((err) => {
                        reject(err);
                    });
                });
            });
        });
    },
};

In the code shown above in the line:
protobuf.load("./protos/transactions.proto").then((err, root) => {
I keep catching the following error:

Inside this catch block:
  }).catch((err) => {
      reject(err);
  });

This seems like a pretty simple problem however I havent found anything on this online so I might be missing something really simple here.
P.S. I tried using __dirname + "/protos/transaction.proto" and still couldnt get this to work.
Please help me figure this out.

A: The problem is that your function doesn't look at the dist directory,
await protocolBuffer.load(__dirname + '/item.proto'); should look there,

and also you need to copy the file manuly by using copy/cp command, you can add it as part of the package json script like so:
 "build": "nest build && COPY src\\reading_list\\protocol_buffer\\*.proto dist\\reading_list\\protocol_buffer\\"


text:
Q: access db.serverStatus() of mongo in mongoose @3.6.20 I want to use db.serverStatus() using mongoose@3.6.20
I have already use this // its working in mongoose updated version which is 5.0 above
mongoose-db-stats
mongoose.connect("mongodb://url");
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.on("open", function() {
  db.db.stats(function(err, stats) {
    console.log(stats);
    callback(stats);
  });
});

something like this but from db.on('open',function(){ this line is not working
I am using node -v 7.10.0
monsoose -v 3.6.20
If anything missing in question then please ask.

A: let db = mongoose.connection;

db.db.command({serverStatus: 1}, function (err, result) { ... });


text:
Q: Find method of moments estimator for $\theta$ in Cauchy$(\theta,1)$ distribution
Given $X_1,X_2,\ldots,X_n \sim $ Cauchy Distribution ${C(\theta,1)}$, what is a method of moments estimator of $\theta$?

$\theta^* = \text{mean}$ is the method of moments estimator for Cauchy Distribution.  For Cauchy Distribution Moment Generating function is not defined so can we calculate the method of moments estimator for it?


text:
Q: Transparent background-color (fillcolor) for textline matchboxes I'm creating business cards with pdflib and php. I'm using PDFLib 9.0.6p4 for Mac with PHP Version 5.6. There is a background image on which the text is displayed. To get it readable I want to have some background-color for my text. Managed to do this with matchbox and fillcolor. Is there a possibility to have a transparent fillcolor for my matchbox?
Already tried to put a transparent rect() as background of my text instead of the matchbox, but it didnt work because I don't know the height and width before printing my text.

    ...
    $textline = "Max Mustermann";
    $p->save();
    $gstate = $p->create_gstate("opacityfill=.8");
    /* Apply the extended graphics state */
    $p->set_gstate($gstate);
    # Place the text in a box on the top right
    $optlist = "position={top left} showborder matchbox={ boxheight={fontsize descender} borderwidth=0.3 offsetleft=-2 offsetright=2 offsetbottom=-2 fillcolor=green}";
    $p->fit_textline($textline, $x, $y-=$yoff, $optlist);   # sample text
    $p->fit_textline($optlist, $xt, $y + 3, "fontsize=12"); # description
    $p->restore();
    ...

unfortunately this doesnt bring the expected effect of a transparent background color for text.

A: you are very close: you should add the gstate handle to the matchbox option list (simplified case):
$gstate = $p->create_gstate("opacityfill=.8");
$optlist = "matchbox={ fillcolor=green gstate=$gstate}";
$p->fit_textline($textline, $x, $y-=$yoff, $optlist);


text:
Q: Android - right side screen button I would like to ask you if it's possible to place a Button "above" another View. What I'm trying to achieve is an activity with ListView and a circle shape Button, which is "coming" from right side of screen. However, if somebody scroll down, button has to stay on it's position, and once he is pressed, new fragment is invoked. In fact, I got stucked at very beginning and have no idea how to do that, so every advice/hint/suggestion is welcome.
PS: Button should be used to add new item into ListView
Also, I've created a sketch for better explanation.
Thanks,
Regards

A: I tried for you and it works fine.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >

<ListView
    android:id="@+id/listAlertItems"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:dividerHeight="1px"
    android:listSelector="@android:color/transparent" />

<ImageView
    android:id="@+id/clickBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerInParent="true"
    android:src="@drawable/ic_img" />

This is the result :