text:
Q: Enable versions in sidebar in sphinx read the docs theme I would like to include the versions.html in the sidebar and could not succeed.
I tried to add versions.html in ** for sidebars, this had no effect:
html_sidebars = {
    '**': ['versions.html']
}

Also how to declare the different versions in conf.py.
I have looked at sphinxcontrib-versioning but it is not exactly what I am looking for.

A: This can be achieved by adding a _templates/versions.html file to override the rtd theme's default jinja template file and adding some variables to the conf.py file.
Execute the following to create a new '_templates/' directory and 'versions.html' file:
mkdir _templates
cat > _templates/versions.html <<'EOF'
{% if READTHEDOCS or display_lower_left %}
{# Add rst-badge after rst-versions for small badge style. #}

       Read the Docs
      v: {{ current_version }}

      {% if languages|length >= 1 %}

{{ _('Languages') }}

        {% for slug, url in languages %}
          {% if slug == current_language %}  {% endif %}

{{ slug }}

          {% if slug == current_language %}  {% endif %}
        {% endfor %}

      {% endif %}
      {% if versions|length >= 1 %}

{{ _('Versions') }}

        {% for slug, url in versions %}
          {% if slug == current_version %}  {% endif %}

{{ slug }}

          {% if slug == current_version %}  {% endif %}
        {% endfor %}

      {% endif %}
      {% if downloads|length >= 1 %}

{{ _('Downloads') }}

        {% for type, url in downloads %}

{{ type }}

        {% endfor %}

      {% endif %}
      {% if READTHEDOCS %}

{{ _('On Read the Docs') }}

            {{ _('Project Home') }}

            {{ _('Builds') }}

      {% endif %}

      {% trans %}Free document hosting provided by Read the Docs.{% endtrans %}

{% endif %}

EOF

And execute the following to append to the conf.py file:
cat >> conf.py <<'EOF'

############################
# SETUP THE RTD LOWER-LEFT #
############################
try:
   html_context
except NameError:
   html_context = dict()
html_context['display_lower_left'] = True

templates_path = ['_templates']

if 'REPO_NAME' in os.environ:
   REPO_NAME = os.environ['REPO_NAME']
else:
   REPO_NAME = ''

# SET CURRENT_LANGUAGE
if 'current_language' in os.environ:
   # get the current_language env var set by buildDocs.sh
   current_language = os.environ['current_language']
else:
   # the user is probably doing `make html`
   # set this build's current language to english
   current_language = 'en'

# tell the theme which language to we're currently building
html_context['current_language'] = current_language

# SET CURRENT_VERSION
from git import Repo
repo = Repo( search_parent_directories=True )

if 'current_version' in os.environ:
   # get the current_version env var set by buildDocs.sh
   current_version = os.environ['current_version']
else:
   # the user is probably doing `make html`
   # set this build's current version by looking at the branch
   current_version = repo.active_branch.name

# tell the theme which version we're currently on ('current_version' affects
# the lower-left rtd menu and 'version' affects the logo-area version)
html_context['current_version'] = current_version
html_context['version'] = current_version

# POPULATE LINKS TO OTHER LANGUAGES
html_context['languages'] = [ ('en', '/' +REPO_NAME+ '/en/' +current_version+ '/') ]

languages = [lang.name for lang in os.scandir('locales') if lang.is_dir()]
for lang in languages:
   html_context['languages'].append( (lang, '/' +REPO_NAME+ '/' +lang+ '/' +current_version+ '/') )

# POPULATE LINKS TO OTHER VERSIONS
html_context['versions'] = list()

versions = [branch.name for branch in repo.branches]
for version in versions:
   html_context['versions'].append( (version, '/' +REPO_NAME+ '/'  +current_language+ '/' +version+ '/') )

# POPULATE LINKS TO OTHER FORMATS/DOWNLOADS

# settings for creating PDF with rinoh
rinoh_documents = [(
 master_doc,
 'target',
 project+ ' Documentation',
 '© ' +copyright,
)]
today_fmt = "%B %d, %Y"

# settings for EPUB
epub_basename = 'target'

html_context['downloads'] = list()
html_context['downloads'].append( ('pdf', '/' +REPO_NAME+ '/' +current_language+ '/' +current_version+ '/' +project+ '-docs_' +current_language+ '_' +current_version+ '.pdf') )

html_context['downloads'].append( ('epub', '/' +REPO_NAME+ '/' +current_language+ '/' +current_version+ '/' +project+ '-docs_' +current_language+ '_' +current_version+ '.epub') )

EOF

See this site for an example:

*

*https://maltfield.github.io/rtd-github-pages/
The whole config to create the above site can be viewed (and easily forked) from the following GitHub repo:

*

*https://github.com/maltfield/rtd-github-pages/
For more information on how I set this up, see this article on how to setup the lower-left Read the Docs menu for navigation between languages and versions and downloads.

A: If the solution above doesn't pan out for anyone I was able to use this extension to add versioning. sphinx-multiversion.  My documentation set up is sphinx with the read-the-docs-theme with private repo for docs on Azure Dev Ops.  Same results with this as code snippet above.  Refer to the Installation, Quickstart, Configuration and Templates pages for all the working parts.


text:
Q: How to assign class with highest frequency to each row of a data.frame in R? i have the following table:
mymatrix <- matrix(c(34,11,65,32,12,9,32,90,21,51,45,23), ncol=3)
colnames(mymatrix) <- c("pos", "neg", "neutr") # class
rownames(mymatrix) <- c("1 -1 0", "-1 -1 0", "0 -1 1", "0 0 1") # patterns
mytable <- as.table(mymatrix)
mytable

#         pos neg neutr
# 1 -1 0   34  12    21
# -1 -1 0  11   9    51
# 0 -1 1   65  32    45
# 0 0 1    32  90    23

now i have new data with three columns. each row contains one of the patterns "1 -1 0", "-1 -1 0", "0 -1 1" and "0 0 1". so for example, my new data looks like this:
one <- c(  1,  1,  0, -1, 0,  1, 1)
two <- c( -1, -1, -1, -1, 0, -1, -1)
three <- c(0,  0,  1,  0, 1,  0, 0)
mydf <- data.frame(one, two, three)
mydf

#   one two three
# 1   1  -1     0
# 2   1  -1     0
# 3   0  -1     1
# 4  -1  -1     0
# 5   0   0     1
# 6   1  -1     0
# 7   1  -1     0

now i want to get a fourth column in mydf that assigns the class (pos, neg, neutr) to each row in mydf. the class with the highest frequency should be assigned.
it should look like this:
#   one two three    four
# 1   1  -1     0    pos  # (because for this pattern (1 1 -1), "pos" gets highest frequency in mytable.)
# 2   1  -1     0    pos
# 3   0  -1     1    pos
# 4  -1  -1     0    neutr
# 5   0   0     1    neg
# 6   1  -1     0    pos
# 7   1  -1     0    pos

how can i do that?
thank you!

A: In the first step you could learn the mapping from triple to label, and then you could look up the mapped value for each row of mydf:
maxes = apply(mytable, 1, function(x) colnames(mytable)[which.max(x)])
mydf$four = maxes[match(paste(mydf$one, mydf$two, mydf$three), rownames(mytable))]
mydf
# mydf
#   one two three  four
# 1   1  -1     0   pos
# 2   1  -1     0   pos
# 3   0  -1     1   pos
# 4  -1  -1     0 neutr
# 5   0   0     1   neg
# 6   1  -1     0   pos
# 7   1  -1     0   pos

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set grid row getSelectionModel data in ext window I am not bale to set row elected data in ext window, can you please give solution for this. my code is here..
var shiftWindow = Ext.create('Ext.window.Window', {
    title: 'Edit Shift',
    resizable: false,
    id: 'shiftwindow',
    width: 465,
    //bodyPadding: 5,
    modal: true,
    store: shiftStorePlanner,

    items: {
        xtype: 'form',
        id: 'idFormShift',
        bodyPadding: 10,
        items: shiftViewModelPlannerData
    },
    buttons: [{
        text: 'Save',
        cls: 'planner-save-button',
        overCls: 'planner-save-button-over',
        handler: function() {
            var wi = this.up('.window')
            var form = Ext.getCmp('idFormShift');
            if (form.isValid()) {
                shiftTimemappingarray = [];
                getShiftTime();
                //this.up('.window').close();
            }
        }
    }, {
        text: 'Cancel',
        handler: function() {
            this.up('.window').close();
        }
    }]
});

    var host1 = Ext.getCmp('plannershifteditor');
    var selection = host1._shiftPlannerGrid.getSelectionModel().getSelection();
    if (selection.length === 0) {

        return;
    }

    Ext.getCmp('shiftWindow').getForm().setValues(selection[0].data);
    shiftWindow.show();
     }

A: Depending on your ExtJS Version:
var selection = grid.getSelectionModel().getSelection();
grid.getForm().loadRecord(selection[0]);

Later you can use updateRecord() to update the model with the form values.
More Infos:

*

*http://docs.sencha.com/extjs/6.0.2/classic/Ext.form.Basic.html#method-loadRecord

*http://docs.sencha.com/extjs/6.0.2/classic/Ext.form.Basic.html#method-updateRecord
ExtJS 5 and later supports also viewmodel binding. This will do the job automatically.


text:
Q: Soap vs Rest over Android I am creating an app in android. It will be calling a webservice to fetch some confidential info. I need to verify that the user is authenticated to access the info and the service shouldn't be called from any other source even if the user has all the required credentails to access the service.
What should be used to ensure the security.... REST or SOAP?

A: For security you should use SSL  with client authentification  and possibility to revoke cvlient certificates (though not every appplication server will support this).  SOAP or REST do not have differences in this context.

A: In my experience REST is easier to build and has less overhead. I used to build soap services with CXF, which is really easy, but now I use Restlet for the server, which is even easier and quicker. Restlet has integration for Json, Guice, JPA, and all the good stuff. At the Android side, I use a simple rest interface with httpClient, Roboguice and Jackson.


text:
Q: Offset function in excel to skip 0s and sum a dynamic range of rows I am trying to use offset function in excel to dynamically calculate sales since launch of products (3 months after, 6 months after etc.). For eg. for item 1 first 3 months of sale is 2557+10000+14487= 27044 and similarly for item 2 first 3 months sale will be 2557+11853+14487=28897
Any guidance on this is super appreciated!!

Items
Item1
Item2

Jan-20
0
0

Feb-20
0
0

Mar-20
0
0

Apr-20
0
0

May-20
0
2557

Jun-20
0
11853

Jul-20
0
14487

Aug-20
0
11375

Sep-20
0
10938

Oct-20
0
10842

Nov-20
0
15132

Dec-20
0
19820

Jan-21
2557
20726

Feb-21
10000
25072

Mar-21
14487
28897

Apr-21
11375
28665

May-21
10938
42358

Jun-21
10842
25619

Jul-21
15132
20575

Aug-21
19820
23315

Sep-21
20726
21346

Oct-21
25072
19377

A: Yes, avoid offset. You could use index/match for example:
=SUM(INDEX(B:B,MATCH(0,B:B)+1):INDEX(B:B,MATCH(0,B:B)+3))


text:
Q: PHP - how to exclude Non-working hours from SLA calculation I want to define SLA for given task excluding weekends, holidays and non working hours in PHP .Workdays Mon-Fri and Worktime 9AM to 5PM.
How can i define SLA and calculate time taken to complete the task in PHP?

A: Edit Question :
Here the code that I tried, i can exclude the weekends and holidays. But want exclude non working time as well
function _getBusinessDayOfMonth($startDate,$businessDays,$holidays)
{
$date = strtotime($startDate);
$i = 0;

while($i < $businessDays)
{
    //get number of week day (1-7)
    $day = date('N',$date);
    //get just Y-m-d date
    $dateYmd = date("Y-m-d",$date);
    $datehis=date("H:i:s",$date);
    if($day < 6 && !in_array($dateYmd, $holidays)){
        $i++;
    }
    $date = strtotime($dateYmd . ' +1 day'.$datehis);
}
$day = date('N',$date);
$d=date("Y-m-d",$date);
if( $day==7||in_array($d, $holidays))
{
    $date = strtotime($d . ' +1 day'.$datehis);
}
elseif($day==6)
{
    $date = strtotime($d . ' +2 day'.$datehis);
}

//return date('Y-m-d H:i:s',$date);
return date('Y-m-d H:i:s',$date);

}


text:
Q: Citation order by year I'm fairly new to LaTeX so this question may come off as trivial, but how would one go about sorting the elements within a citation by year?
For example, my citation would read in alphabetical order as (Frank, 2007; James, 2005; John, 1998). Where/what would I need to change to have it read (John, 1998; James, 2005; Frank, 2007)?
edit: I'm using natbib and a custom bibliostyle. Is it possible to leave the bibliography portion untouched (as the one that's displaying for me is perfect) and only tinker with the elements within the citation?

A: Well, you may see this for further details on answering your question,
I'll summarize some of their answer in here,

*

*there is a user package for sorting references either chronologically or reverse chronologically, plesslweb

*you can also use biblatex for ordering your references by year or

*natbib,

All them may be fairly easy to use considering you are new to latex.
Btw, Welcome to TeX.sx!


text:
Q: Custom root CA not trusted by Chrome on MacOS even after insertion into the keychain I create a root CA and a cert using the following script:
#! /bin/bash

set -e

base_folder="$HOME/.acme-development-certs"
start_dir=$PWD

if test -f "$base_folder/leaf_cert/acme.pem"; then
    echo "ACME development certs already created: skipping CA and cert creation."
    exit 0
fi

mkdir -p $base_folder
cd $base_folder

# create root cert
mkdir -p root_ca/certs root_ca/crl root_ca/newcerts root_ca/private

echo 1000 > root_ca/serial
touch root_ca/index.txt root_ca/index.txt.attr

echo '
[ ca ]
default_ca = CA_default
[ CA_default ]
dir            = root_ca                  # Where everything is kept
certs          = $dir/certs               # Where the issued certs are kept
crl_dir        = $dir/crl                 # Where the issued crl are kept
database       = $dir/index.txt           # database index file.
new_certs_dir  = $dir/newcerts            # default place for new certs.
certificate    = $dir/cacert.pem          # The CA certificate
serial         = $dir/serial              # The current serial number
private_key    = $dir/private/ca.key  # The private key
nameopt        = default_ca
certopt        = default_ca
policy         = policy_match
default_days   = 3650
default_md     = sha512
copy_extensions = copy

[ policy_match ]
countryName            = optional
stateOrProvinceName    = optional
organizationName       = optional
organizationalUnitName = optional
commonName             = supplied
emailAddress           = optional

[req]
utf8 = yes
string_mask = utf8only
x509_extensions = v3_req
distinguished_name = req_distinguished_name
prompt = no

[req_distinguished_name]
CN = ACME Development Root CA
O = ACME
OU = ACME Engineering

[v3_req]
basicConstraints = critical,CA:TRUE
keyUsage = critical,keyCertSign,cRLSign
subjectKeyIdentifier = hash

' > root_ca/openssl.conf

openssl genrsa -out root_ca/private/ca.key 2048
openssl req -config root_ca/openssl.conf -new -x509 -days 3650 -key root_ca/private/ca.key -sha256 -extensions v3_req -out root_ca/certs/ca.crt
openssl x509 -in root_ca/certs/ca.crt -out root_ca/certs/ca.pem -outform PEM

# create leaf cert
mkdir leaf_cert
echo '
[ req ]Development
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn

[ dn ]
CN = ACME
O = ACME
OU = ACME Engineering

[ req_ext ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = acme.com
DNS.2 = *.acme.com
DNS.3 = *.sub.acme.com
DNS.4 = acme2.com
DNS.5 = *.acme2.com
DNS.6 = *.sub.acme2.com
' > leaf_cert/openssl.conf
openssl req -new -keyout leaf_cert/acme.key -out leaf_cert/acme.csr -days 3650 -nodes -newkey rsa:2048 -config leaf_cert/openssl.conf
openssl ca -batch -config root_ca/openssl.conf -keyfile root_ca/private/ca.key -cert root_ca/certs/ca.crt -out leaf_cert/acme.crt -infiles leaf_cert/acme.csr
openssl x509 -in leaf_cert/acme.crt -out leaf_cert/acme-leaf.pem -outform PEM
cat leaf_cert/acme-leaf.pem root_ca/certs/ca.pem > leaf_cert/acme.pem

# trust new CA at the OS level
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain $base_folder/root_ca/certs/ca.pem

# serve HTTPS using the new cert
NGINX_PATH="/usr/local/etc/nginx"
cp leaf_cert/acme.pem $NGINX_PATH/star_acme_com.pem
cp leaf_cert/acme.key $NGINX_PATH/star_acme_com.key
sudo brew services restart nginx

I tried various combinations of parameters for the two .cfg and I also tried to add the cert manually to the keychain but nothing to do:
Chrome rejects it with:

This site can't provide a secure connection
sub.acme.com doesn't adhere to security standards.
ERR_SSL_SERVER_CERT_BAD_FORMAT

Notes:

*

*Safari and curl are fine with the certificate. Firefox has it's own list of CAs and is okay after I add the root CA .pem to the Authorities section of it's internal list.

*Nginx is configured to use the cert $NGINX_PATH/star_acme_com.key and it's probably not the issue as it works perfectly with a paid one.

*In Chrome dev tools, in the security tabs, it displays Certificate - valid and trusted

Output of openssl x509 -noout -text -in <cert>

*

*for the cert

Certificate:
    Data:
        Version: 1 (0x0)
        Serial Number: 4096 (0x1000)
    Signature Algorithm: sha512WithRSAEncryption
        Issuer: CN=ACME Development Root CA, O=ACME, OU=ACME Engineering
        Validity
            Not Before: Jun  7 10:16:14 2019 GMT
            Not After : Jun  4 10:16:14 2029 GMT
        Subject: O=ACME, OU=ACME Engineering, CN=ACME
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    ***
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:acme.com, DNS:*.acme.com, DNS:*.sub.acme.com, DNS:acme2.com, DNS:*.acme2.com, DNS:*.sub.acme2.com
    Signature Algorithm: sha512WithRSAEncryption
         ***

*

*for the root CA

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 11358523417566447898 (0x9da194de4501091a)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=ACME Development Root CA, O=ACME, OU=ACME Engineering
        Validity
            Not Before: Jun  7 10:16:13 2019 GMT
            Not After : Jun  4 10:16:13 2029 GMT
        Subject: CN=ACME Development Root CA, O=ACME, OU=ACME Engineering
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    ***
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Key Usage: critical
                Certificate Sign, CRL Sign
            X509v3 Subject Key Identifier:
                1F:50:BB:C9:85:C4:DB:71:46:E3:0E:B4:B5:48:B4:CF:10:C2:27:54
    Signature Algorithm: sha256WithRSAEncryption
         ***

A: Also you need to check your certificate at Keychain Access.
Double click your certificate and in popup under "Trust" section set "Alway Trust"


text:
Q: AudioSystem downloads partial file I'm trying to download a file using AudioSystem. However, it fails to download the complete file. I've tried with other audio files and can replicate the bug with them. I've also tried various hosting services, and it didn't help.
There are no exceptions thrown. This was working correctly a few weeks ago, so I'm not sure what happened since then.
Would appreciate some help since I'm not too familiar with handling audio files.
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import javax.sound.sampled.AudioSystem

fun main(args: Array<String>) {
    downloadAudio()
}

fun downloadAudio() {
    val localFile = File("/tmp/input_audio.wav")

    val audioUrl = URL("https://srv-store1.gofile.io/download/vj9dHc/my_audio_recording_wav.wav")

    try {
        val audioFileFormat = AudioSystem.getAudioFileFormat(audioUrl)
        val inputAudioStream = AudioSystem.getAudioInputStream(audioUrl)
        inputAudioStream.use {
            AudioSystem.write(inputAudioStream, audioFileFormat.type, localFile)
        }
    } catch (ex: Exception) {
        throw ex
    }
}


text:
Q: How to fix not working calculation in dataframe pandas python hello everyone i have a problem in calculation a data frame in python. i have an equation name is TOC/Total_organic. below is the picture of my equation, code to make new colomns in my data frame, and the result code and result from running the code
def total_organic (resis_log, dens_log, base_resislog, base_denslog, LOM):
delta_log = math.log10((resis_log/base_resislog)) - 2.5*(dens_log - base_denslog)
a = 0.297 - (0.1688*LOM)
TOC = delta_log * (10**a)
return round(TOC,2)

df_2['TOC'] = total_organic(df_2['AT90'], df_2['RHOM'], 0.5, 2.7, 14.2)ode here

A: The problem is that math.log10 cannot handle neither pandas dataframes nor ndarrays. You can use np.log10 instead.
import numpy as np

delta_log = np.log10((resis_log/base_resislog)) - 2.5*(dens_log - base_denslog)


text:
Q: Precalculus angular velocity and linear velocity Can someone help me please? I don't really understand Angular and Linear Velocity. Thank you!
A back wheel on a tricycle has a radius of 8cm and rotates at a rate of 200 times per minute. Approximately what are the angular velocity of the wheel in radians per second and the linear velocity of a point on the wheel in centimeters per second?

A: Angular velocity $\omega$ is measured in radians per second, so in this case $$\omega=2\pi\times\frac {200}{60}$$
Linear velocity $v$ of a fixed point at distance $r$ from the centre of the circle is given by $$v=r\omega$$
I hope this helps

A: The angular velocity corresponds to the radians that the radius sweeps in a second. Let's introduce an intermediate quantity: the period $T$. That is the time it takes for the wheel to complete one spin.
If we know that the wheel takes $T$ seconds to make a complete rotation, then calculating the angular velocity $\omega$ is easy: the angle swept in a whole rotation is $2\pi$ radians. Then we have
$$\omega = \frac{2\pi}{T}\quad\text{[rad/s] or [$\mathrm s^{-1}$]}$$
In your problem there's a different quantity: the frequency. It is measured in $\mathrm s^{-1}$ and indicates how many whole rotations occur in one second. From the problem we know that $f = 200/60\ \mathrm s^{-1}$. You can verify that between frequency and period there exists the relation $T = f^{-1}$. Therefore we obtain another formula for $\omega$:
$$\omega = 2\pi f\quad\text{[rad/s] or [$\mathrm s^{-1}$]}$$
Finally, tangential velocity is directly proportional to the angular velocity, and the constant of proportionality is the radius, i.e.
$$v = \omega r\quad\text{[$\mathrm m\mathrm s^{-1}$]}$$


text:
Q: Nested routes doesn't work how do i make it work?
This is an example url i need:

/name/posts/2

My routes.rb
  get "/:name", to: "categories#show" do
    resources :posts, only: [:show]
  end

A: app/config/routes.rb
scope path: '/:name' do
  resources :posts, only: [:show]
end

resources :posts, except: [:show]

This will pass the :name and :id params into your posts#show function.
app/controllers/posts_controller.rb
def show
  user = User.where(name: params[:name]).first
  @post = Post.where(['id = ? AND user_id = ?', params[:id], user.id])

  render @post
end

NOTE: This can be more Rails 4 friendly by using Strong Parameters.

A: This will catch anything like /:name in the URLs and route it to the categories controller.
Adding :path => "" means it will cut the resource identifier from the URL.
So instead of having /categories/foobar you now get /foobar
Then you just nest your post routes in the parent route.
resources :categories, :path => "" do
  resources :posts, :only => :show
end

Note that this kind of catch-all route is potentially very error prone as it catches everything, including crap you don't expect:)


text:
Q: Outlook : How to get reference of (EntryID, optional & required attendee) newly added item in Appointment.Write event handler I want to capture the information of new created appointment item, For that I hook the event with NewInstpector window & again hook the Write event. I am also using standard outlook item wrapper(from msdn).
The problem is inside the Item_Write event handler  I get the reference of new item however some properties are coming as NULL. For e.g. EntryID, Optional attendees.
The value for EntryID might be null because item is not yet witten on the exchange server, so the question is how to capture the EntryID of newly created appiointment item
Atul Sureka

A: EntryID is not set until the item is saved or sent, because it isn't added to the store otherwise.
You will need to do either of those things before you can read the entry ID.


text:
Q: Django url tags linking i'm new into django. I created a project named marketbook, it has a main templates directory and an app called users. Inside my app (users) i have templates folder as well with a file called login.html (templates/users/login.html.
I want to link this login.html in my app to a link in my file (navbar.html) in my main templates director folder. what should be the url tag to use?
 Log In

A: In the settings.py file, the TEMPLATES variable is set to the field: 'DIRS': ['templates']. This is so that you can find the main home.html template, which is located in the templates folder, which is located in the folder where the application folder is, the manage.py module.
start the server: python manage.py runserve
go to:         http://localhost:8000/users/home/
press the button and go to: http://localhost:8000/users/navbar/
urls.py (urls application)
from django.urls import path
from .views import home, navbar

urlpatterns = [
    path('home/', home),
    path('navbar/', navbar, name='navbar'),
]

views
from django.shortcuts import render

def home(request):
    return render(request, "home.html")

def navbar(request):
    return render(request, "users/navbar.html")

home.html
 Log In

navbar.html
<!DOCTYPE html>

    <meta charset="utf-8" />

This is a navbar template


text:
Q: where to put styles in page with a master page I have a report.master
 <%@ Master Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewMasterPage" %>

 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 <asp:ContentPlaceHolder ID="TitleContent" runat="server" />
 </asp:Content>

 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:ContentPlaceHolder ID="MainContent" runat="server" />
 </asp:Content>

 <asp:Content ID="Content3" ContentPlaceHolderID="SideBarContent" runat="server">

Select Report

JobSorted

<%: Html.ActionLink("JobSorted Report Data", "JobSortedReportData")%>

<%: Html.ActionLink("JobSorted Tradesmen Searches Data", "JobSortedTradesmenSearchesData")%>

<%: Html.ActionLink("JobSorted Signup Summary Report", "JobSortedSignups") %>

<%: Html.ActionLink("JobSorted Jobs Summary Report", "JobSortedJobs") %>

        <%--
Subscription Report
--%>

TradeUK

<%: Html.ActionLink("TradeUK KPI Searches Data", "TradeUKKPISearchesData")%>

<%: Html.ActionLink("TradeUK Job Searches Data", "TradeUKJobSearchesData")%>

<%: Html.ActionLink("Tradesman Signup Summary Report", "Index") %>

<%: Html.ActionLink("Websites Report", "TradeUKWebsitesData")%>

<%: Html.ActionLink("All Tradesman Counter Signup Summary Report", "AllTradesmenCodeRegistrations")%>

<%: Html.ActionLink("Tradesman Counter Signup Summary Report", "TradesmenCodeRegistrations")%>

</asp:Content>

then in my view I have:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Report/Report.Master" Inherits="System.Web.Mvc.ViewPage<TradeUK.Admin.Web.ViewModels.KPIReportsViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
TradeUK KPI Searches Data
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

TradeUK KPI Searches Data

   <%: Html.ActionLink("Export as CSV...", "TradeUKKPIDataExport", "Report", new {@date = ViewBag.jobSortedReportDate }, 0)%>

 </asp:Content>

I have a warning about the style tag within the head tag. Where must I put this? i dont understand?
thanks

A: In your final rendered HTML styles should be declared in the  section. You can completely ignore the warnings that you are getting during design time. If you want something reliable validate your final generated markup here: http://validator.w3.org/


text:
Q: Want to connect dataShort_out of DataConverter to an output file using python I have a waveform that contains a DataConverter and is connected to my node. I want to save the dataShort_out of the DataConverter to a file and write out some data. I am able to do this using the IDE and take a snapshot. I want to do the same thing using python. I am using RH 1.9.
>>> from ossie.utils import redhawk
>>> domain = redhawk.attach('REDHAWK_dev')
>>> devMgr = domain.devMgrs
>>> devMgr = devMgr[1]
>>> device = devMgr.devs
>>> device = devMgr.devs[1]
>>> test_wavform = domain.createApplication("/waveforms/Test/test.sad.xml")
>>> comp1=waveform.comps[0]
>>> comp1.name
'DataConverter'
>>> comp1_port=comp1.getPort('dataShort_out')
>>> comp1.start()
>>> from ossie.utils import sb
>>> sb.start()
>>> output_file = sb.FileSink('~/some_file.tmp')
>>> comp1.connect(output_file)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/redhawk/core/lib/python/ossie/utils/model/__init__.py", line 255, in connect
raise RuntimeError, 'Multiple ports matched interfaces on connect, must specify providesPortName or usesPortName'
RuntimeError: Multiple ports matched interfaces on connect, must specify providesPortName or usesPortName

A: Make sure to specify your port name on the "connect" call:
>>> comp1.connect(output_file, usesPortName='dataShort_out')
>>> output_file.start()


text:
Q: Checking if ARGV is given when running a program with node When running a program with node:
node test.js

How do you check if the program is given an ARGV when run node test.js --example? What I've tried so far is the following:
function say(input){
    console.log(input);
}

if(process.argv[1] !== '')
{
    say('false');
}
else {
    say('success');
}

if(process.argv[1] === null)
{
    say('false');
}
else {
    say('success');
}

However the first solution won't output the else and the second solution only outputs NUL is not defined so with that, what I'm thinking is that I'm making some mistake in my coding?

A: *

*argv[0] is the name of your node inerpretor --> in general node

*argv[1] is the path to your script. So argv[1] is always filled

try this to be very well aware :
console.log(process.argv);

A: Thanks to the answer provided by kevin ternet, and for the information provided by maioman what I ended up doing was this:
if(process.argv[2] === undefined){
    say('false');
} else {
    say('true');
}

Here's what happens when you process ARGV in Node:
ARGV[0]:
if(process.argv[0] === undefined){
    console.log('Failure');
    console.log(process.argv[0]);

} else {
    console.log('Success');
    console.log(process.argv[0]);
}

Output:
Success
C:\Program Files\nodejs\node.exe //Path to node executable

ARGV[1]:
if(process.argv[1] === undefined){
    console.log('Failure');
    console.log(process.argv[1]);

} else {
    console.log('Success');
    console.log(process.argv[1]);
}

Output:
Success
C:\Users\bin\javascript\node\test.js //Path to file

ARGV[2]:
if(process.argv[2] === undefined){
    console.log('Failure');
    console.log(process.argv[1]);

} else {
    console.log('Success');
    console.log(process.argv[2]);
}

Output:
Success
--example //The actual flag that was given

So therefore to check if a flag is actually given, you look for ARGV[2].
Here's an example of the entire ARGV tree ran:
if(process.argv === undefined){
    console.log('Failure');
    console.log(process.argv);

} else {
    console.log('Success');
    console.log(process.argv);
}

Success
[ 'C:\\Program Files\\nodejs\\node.exe' //ARGV[0],
  'C:\\Users\\bin\\javascript\\node\\test.js' //ARGV[1],
  '--example' //ARGV[2] ]

So as you can see the tree is structured as an array, with the first argument being 0.


text:
Q: Hive "Too many Mappers" when using Dynamic Partition I am trying to query data into a partitioned table with dynamic partitions.
set hive.exec.parallel=true;
set hive.exec.dynamic.partition.mode=nonstrict;
SET hive.exec.max.dynamic.partitions=10000;
SET hive.exec.max.dynamic.partitions.pernode=1000;

insert overwrite table reporting.ST_YST_FLATTENED partition (dt)
select * from (
select a.ActivityDate
,to_date(c.datecreated) InstallDate
,lower(a.CountryCode) CountryCode
,a.browserguid
,a.installsource
,p.partner
,sum(a.YSTPageViews) YSTPageViews
,Sum(a.YSTClicks) YSTClicks
,sum(a.YSTSearches) YSTSearches
,a.browser
,dt from X) a
DISTRIBUTE BY dt

When I execute WITHOUT the "insert overwrite table reporting.ST_YST_FLATTENED partition (dt)" the number of mappers is 32438 and I get no error. When I try and insert into the dynamic partitions I get:
Hadoop job information for Stage-7: number of mappers: 32438; number of reducers: 55
org.apache.hadoop.mapreduce.counters.LimitExceededException: Too many counters: 121 max=120

If I reduce the time frame of the sub query, I can reduce the mappers to 200, but I still get the same error. Increasing the default counters used is not an option at this point.
How do I decrease the number of mappers used or otherwise get the dynamic partitions to work?


text:
Q: ERROR: android.content.res.Resources$NotFoundException I recently tried to add a launch(splash) screen to my app, But an error is occurring all the time i try to run the app by the emulator.
this is the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.aidin.workbook, PID: 29714
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aidin.workbook/com.aidin.workbook.SplashActivity}: android.content.res.Resources$NotFoundException: Drawable com.aidin.workbook:drawable/background_splash with resource ID #0x7f07005c
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2892)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027)
                  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
                  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:101)
                  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1786)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6656)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
               Caused by: android.content.res.Resources$NotFoundException: Drawable com.aidin.workbook:drawable/background_splash with resource ID #0x7f07005c
               Caused by: android.content.res.Resources$NotFoundException: File res/drawable/background_splash.xml from drawable resource ID #0x7f07005c
                  at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:821)
                  at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:630)
                  at android.content.res.Resources.getDrawableForDensity(Resources.java:877)
                  at android.content.res.Resources.getDrawable(Resources.java:819)
                  at android.content.Context.getDrawable(Context.java:626)
                  at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:351)
                  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
                  at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:87)
                  at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:128)
                  at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
                  at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
                  at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
                  at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
                  at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
                  at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:198)
                  at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
                  at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                  at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:70)
                  at com.aidin.workbook.SplashActivity.onCreate(SplashActivity.java:13)
                  at android.app.Activity.performCreate(Activity.java:7117)
                  at android.app.Activity.performCreate(Activity.java:7108)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1262)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2867)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027)
                  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
                  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:101)
                  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1786)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6656)
                  at java.lang.reflect.Method.invoke(Native Method)

My Android Studio, Gradle and Build tools all are up to date,
I tried to clean and rebuild the project for many times but it didn't help and non of the related answers out there were useful for this issue; I tried all of theme.
this is my style.xml:
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/background_splash</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

and this is my background_splash.xml in res/drawable directory:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/darker_gray"/>
<item>
    <bitmap
        android:gravity="center"

        android:src="@mipmap/ic_launcher" />
</item>

</layer-list>

and this is the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aidin.workbook">
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".SplashActivity"
        android:label="@string/app_name"
        android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".HomeActivity">

    </activity>
</application>

Finally here is SplashActivity.java:
package com.aidin.workbook;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    setTheme(R.style.SplashTheme);
    super.onCreate(savedInstanceState);
    Intent intent = new Intent(this, HomeActivity.class);
    startActivity(intent);
    finish();
}
}

this the Build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.aidin.workbook"
    minSdkVersion 21
    targetSdkVersion 26
    buildToolsVersion "28.0.0-rc1"
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:2.2.2'
}

A: In your background_splash.xml,you have to change bitmap src file to a drawable file that has to be in png format not in xml format
like this drawbles/ic_launcher.png
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/darker_gray"/>
<item>
    <bitmap
        android:gravity="center"

        android:src="@drawble/ic_launcher" />
</item>

</layer-list>

A: <?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- <item android:drawable="?android:colorBackground" /> -->

    <!-- You can insert your own image assets here -->
    <!-- <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/launch_image" />
    </item> -->
</layer-list>

comment the contents inside  as above


text:
Q: Converting Babylon dictionary to StarDict dictionary After upgrading Ubuntu our administrator at work un-installed GoldenDict and instead of that installed StarDict. I had been using a lot of Babylon dictionaries in GoldenDict.
I have found out that StarDict doesn't support Babylon dictionaries and that I need to convert them. I found dictconv tool to convert Babylon dictionaries into StarDict dictionary. dictconv converts very well but once I add it to StarDict and want to see the result, StarDict shows results along with HTML tags, the result looks like this:
<--- An English-Spanish Dictionary (Granada University, Spain), 10.5 --->
write
 (v.) = escribir, redactar, confeccionar

Def:
Verbo irregular: pasado wrote, participio written.

 Ex: A paraphrase is an interpretation of the concepts featured in a document, written in the language of the writer of the paraphrase.
 ----

Does anybody know other converters? or How can I solve this specific error?
Thanks

A: After searching in google have found finally what I was looking for.
So, in order to convert Babylon dictionary into StarDict I did following instructions:

*

*sudo apt-get install stardict-tools installing stardict-tools

*stardict-editor - openign stardict-editor

*An editor will be opened where you need to browse and select you .BGL file(Babylon Dictionary)

*In the bottom of the opened application you select BGL file and click on Build button

*It will create a file with an extension .babylon.

*Next browse and select this file

*In the bottom of the opened application you select Babylon file and click on Build button

*That's it. It will create 3 files (.dict.dz, .idx, .ifo) in the current directory

*Copy and paste it into one separate directory under StarDict dictionary folder.

That's it.


text:
Q: Why is null std::optional considered less than any value, not more Is there any math sense in having null std::optional being less than any keeping value? Or is it made only for consistency and there would have been no any difference if it was "more" instead of "less"?

A: Directly from the proposal (emphasis mine):

A number of ways of including the disengaged state in comparisons have been suggested. The ones proposed, have been crafted such that the axioms of equivalence and strict weak ordering are preserved: disengaged optional<T> is simply treated as an additional and unique value of T equal only to itself; this value is always compared as less than any value of T.

Further on it says

Value nullopt could have been as well considered greater than any value of T. The choice is to a great degree arbitrary. We choose to stick to what boost::optional does.

Taking a look at boost::optional's take on this, we get from its documentation:

In a similar manner, type optional<T> is LessThanComparable whenever T is LessThanComparable. The optional object containing no value is compared less than any value of T. To illustrate this, if the default ordering of size_t is {0, 1, 2, ...}, the default ordering of optional<size_t> is {boost::none, 0, 1, 2, ...}. This order does not have a practical interpretation. The goal is to have any semantically correct default ordering in order for optional<T> to be usable in ordered associative containers (wherever T is usable).

So no, there is no "maths sense" to this all except for "nothing is less than something". It's an arbitrary choice of no practical consequence only to ensure the type can be used in ordered containers without much hassle.


text:
Q: A-frame not tracking custom image I just started trying the A-frame with AR.js to hopefully get an object to render on a piece of paper. I have tested the object and it is correctly rendered. However, when I try it with a custom image, it no longer works... I am trying to show a gltf file on a pattern. THe pattern is (in image form): and was made using https://jeromeetienne.github.io/AR.js/three.js/examples/marker-training/examples/generator.html
Does anyone see anything wrong with my code as to why that pattern is not being taken by the camera as a match? Is it my code? or is it something to do with the pattern file I am trying to load?
<head>
    <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
    <script src="https://cdn.rawgit.com/jeromeetienne/AR.js/1.6.0/aframe/build/aframe-ar.js"></script>
</head>

<body style='margin : 0px; overflow: hidden;'>
    <a-scene embedded arjs='sourceType: webcam;'>
        <a-assets>
            <a-asset-item id="mesh" src="./data/Camargue.gltf"></a-asset-item>
        </a-assets>
        <a-entity gltf-model="#mesh" rotation="0 180 0" modify-materials></a-entity>
        <a-light type="directional" color="#fff" position="-1 -5 -5" look-at="a-entity"></a-light>
        <a-light type="ambient" color="#fff" intensity="3" look-at="a-entity"></a-light>
        <a-marker-camera type="pattern" patternUrl="data/pattern-logo.patt"></a-marker-camera>
    </a-scene>

    <script>
        AFRAME.registerComponent('modify-materials', {
            init: function () {
                // Wait for model to load.
                this.el.addEventListener('model-loaded', () => {
                    // Grab the mesh / scene.
                    const obj = this.el.getObject3D('mesh');
                    // Go over the submeshes and modify materials we want.
                    obj.traverse(node => {
                        if (node.name.indexOf('Loggia-frame') !== -1) {
                            var environment = new THREE.CubeTextureLoader().setPath('data/HDR/').load(
                                [
                                    'posx.jpg', 'negx.jpg', 'posy.jpg', 'negy.jpg', 'posz.jpg', 'negz.jpg'
                                ]
                            );

                            environment.format = THREE.RGBFormat;
                            environment.mapping = THREE.CubeReflectionMapping;

                            var material = node.material;
                            material.envMap = environment;
                        }
                    });
                });
            }
        });
    </script>
</body>


text:
Q: Insert missing rows in table b and update table a I have 2 tables: user_account and email_validation.
user_account has user_id, email and email_validation_id.
email_validation has email_validation_id, user_account_id, and email.
In normal and correct way, for each user in user_account (for example [user_id="123", email="user@domain.com", email_validation_id="456"]) there is a row in email_validation (for example [email_validation_id="456", user_account_id="123", email="user@domain.com"]).
But, some things got wrong and now I have users with no email validation. So, I would like to add rows manually: for each user from user_account which don't have a row in email_validation (i.e. no row with it's user_id) insert [email_validation_id=<The current max of (email_validation.email_validation_id) + 1>, user_account_id=<user_account.user_id>, email=<user_account.email>] and update the user_account.email_validation_id to <email_validation.email_validation_id>.
I have no idea how to approach this :\
Thank you for your time!

A: If I had understood everything correctly this could help.
Missing email validation
To create/insert missing email validation you can do.
INSERT INTO email_validation(user_account_id, email)
SELECT user_id, email
FROM user_account WHERE email_validation_id is null;

Auto increase the id
To auto increase the id you can do.
Table definition:
CREATE TABLE tablename
(
  id NUMBER(10)
);

ALTER TABLE tablename ADD (CONSTRAINT tbn_pk PRIMARY KEY (id));
CREATE SEQUENCE tbn_seq START WITH 1;

Or you can use Identity Columns is available from Oracle 12c+.
CREATE TABLE tablename
(
   id NUMBER GENERATED ALWAYS AS IDENTITY
);

Trigger definition:
CREATE SEQUENCE tbn_seq START WITH 1;

CREATE OR REPLACE TRIGGER tbn_id_insert BEFORE INSERT ON departments
FOR EACH ROW
BEGIN
    SELECT tbn_seq.NEXTVAL
    INTO :new.id
    FROM dual;
END;
/

Update the user_account
To update the user_account.email_validation_id you can do.
DECLARE
    v_email_validation_id user_account.email_validation_id%TYPE;
BEGIN
    FOR user_account_rec IN (SELECT * FROM user_account WHERE email_validation_id is NULL)
    LOOP
        SELECT email_validation_id
        INTO v_email_validation_id
        FROM email_validation
        WHERE user_account_id = user_account_rec.user_id;

        UPDATE user_account
        SET email_validation_id = v_email_validation_id
        where user_id = user_account_rec.user_id;
    END LOOP;
END;
/

I hope I was able to help you.


text:
Q: synthesis and Implement RTL design in verilog I want to synthesis RTL design which sort data in memory. I am not sure that I need to synthesis the module with test bench or without it?

A: You need to synthesis the module without test bench.


text:
Q: How to suppress multiple plots popup in spyder? I have multiple plt.show() and if I run the script from geany etc, the 2nd plot will not show until I close the first plot. However, in Spyder it will automatically show all the plots.
How can I let Spyder only show one plot and move to 2nd plot after I close the first plot?


text:
Q: Using twitter API get error sometimes I use the following code which works sometimes but its unstable , when I run the program sometimes I got error 420 with json parse error which doesnt give you lot of hints how to solve it. any idea what am I doing wrong ?
The error is :

Error getting tweets: Error: Status Code: 420 Error getting tweets:
  SyntaxError: Unexpected token E in JSON at position 0

var Twitter=require('twitter');
var lclconf = require('../config.json');

var client=new Twitter({
  consumer_key: lclconf.twitter.consumer_key,
  consumer_secret: lclconf.twitter.consumer_secret,
  access_token_key: lclconf.twitter.access_token_key,
  access_token_secret: lclconf.twitter.access_token_secret
});
stream.on("data", function(data){
  console.log(data.id_str);
  var tweet_id="https://api.twitter.com/1.1/statuses/oembed.json?id="+data.id_str;
  request.get(tweet_id)
  .end(function(err,res){
      if(err){
        console.log("Error from Twitter API: " + err);
      }else{
        //console.log(res.body);
        io.emit('tweet',res.body);
      }
  });
});
stream.on('error', function(err){
  console.log("Error getting tweets: "+err);
});
io.on('connection', function(client){
  client.on("join", function(data){
    console.log(data);
  });
  client.emit("join",{"message":"running"});
});

Maybe if there is a way that when the error is occurred ignore it and proceed since now the process is stopped.
Update:
In twitter docs there is info about HTTP 420 but not sure how to fix it ...

A: HTTP 420 is returned when you are being rate limited.
There is a https://publish.twitter.com/oembed resource URL, that is neither rate limited nor requires authentication. I think it returns the same things that your program expects. You can use that if you pass a query parameter url having the link to tweet. Try making the link like:
"https://publish.twitter.com/oembed?url=https://twitter.com/"+data.user.screen_name+"/statuses/"+data.id_str

For sample data returned by Twitter click here

A: As per pii_ke's response you should simply modify tweet_id as follows:
var tweet_id = "https://publish.twitter.com/oembed?url=https://twitter.com/" + data.user.screen_name + "/statuses/" + data.id_str;

Full modified code you can copy paste:
var Twitter=require('twitter');
var lclconf = require('../config.json');

var client=new Twitter({
  consumer_key: lclconf.twitter.consumer_key,
  consumer_secret: lclconf.twitter.consumer_secret,
  access_token_key: lclconf.twitter.access_token_key,
  access_token_secret: lclconf.twitter.access_token_secret
});
stream.on("data", function(data){
  console.log(data.id_str);
  var tweet_id = "https://publish.twitter.com/oembed?url=https://twitter.com/" + data.user.screen_name + "/statuses/" + data.id_str;
  request.get(tweet_id)
  .end(function(err,res){
      if(err){
        console.log("Error from Twitter API: " + err);
      }else{
        //console.log(res.body);
        io.emit('tweet',res.body);
      }
  });
});
stream.on('error', function(err){
  console.log("Error getting tweets: "+err);
});
io.on('connection', function(client){
  client.on("join", function(data){
    console.log(data);
  });
  client.emit("join",{"message":"running"});
});


text:
Q: average raster file value in shapefile area returns multiple outputs - interpreting results So I have my raster file
r <- raster('ras')

and a shapefile
abys <- readShapeSpatial('abys')

I calculated the mean values defined by the shapefile by the following method:
r.vals<- extract(r,abys)
r.mean <- lapply(r.vals,FUN=mean)

However, when using a couple of shapefiles when I return the output I get multiple results, e.g.:
[[1]]
[1] 9321

[[2]]
[1] 6616

[[3]]
[1] 8348

It should just return one which is what I usually get. Is this because of some characterestic of my shapefile or a problem with my methodology?
Thanks for your input

A: Your problem is that there are three polygons in abys.
The best solution is not to average the results but to union the polygon first:
library(rgeos)
abys.single <- gUnaryUnion(abys)
r.vals<- extract(r,abys.single)
r.mean <- lapply(r.vals,FUN=mean)


text:
Q: What happened to QTikZ for Windows? QTikZ is a fabulous little editor that allows you to enter TikZ code and see a real-time preview of your figure. It was available for download for MS Windows at
http://www.hackenberger.at/blog/ktikz-editor-for-the-tikz-language/
but that website now appears to be down. Does anybody know (a) what has become of the QTikZ project, and (b) whether there is an alternative place to obtain a copy of QTikZ for Windows?

A: The source code lives on http://github.com/fhackenberger/ktikz (last update in September 2015), and an archived copy of the website from September 2015 can be found at https://web.archive.org/web/20150921123912/http://www.hackenberger.at/blog/ktikz-editor-for-the-tikz-language/


text:
Q: Which event has a higher probability? Which event has a higher probability?

$24$ rolls of 2 dice at once we get at least 2 $1$s

or

one roll of 4 dice at once we get at least one $1$?

A: Hint. $1$ minus the probability that in 24 rolls of 2 dice we never get 2 ones (at once): $1-\left(\frac{6^2-1}{6^2}\right)^{24}$.
1 minus the probability that in 1 roll of 4 dice we never get one: $1-\left(\frac{6-1}{6}\right)^{4}$.
Which number is greater?
P.S. Both numbers are quite close to $0.5$.

A: For a roll of four dice getting a single 1:

$$\frac{1}{6}+\frac{5}{6^2}+\frac{5^2}{6^3}+\frac{5^3}{6^4}=\frac{671}{1296}$$, since I am doing the chance of it not giving a one all times, then invert that (take it away from one)

For 24 rolls of 2 dice (at once), or 48 rolls of a single dice you get at least 2 'ones':

Well, chances of it happening is , $1-(\frac{25}{6^2})^{24}=$ something very close to $1$. I got these numbers by saying the chance thee is not a one, and taking it to the power of $24$ and finally inverting it.

Well, these results show that $$\frac{671}{1296}< \approx1$$, so we know that:

The chance of getting at least two $1$s in 24 rolls of two dice is greater than getting four rolls of a dice, and we get a single one.


text:
Q: How to make changes to egress rules for AWS security groups? I have a lambda and my script in running on it, it's connecting to a database, I have attached a security group to this lambda, the outbound rules is allow all Protocol and all ports, it seems a bit too permissive, but I'm not sure how to change it to the setting I need, is there any suggestions?
How should I narrow down the permission range and my lambda will also work? Or is it safe to keep it like this?

A: You can use security_groups in egress to limit outgoing traffic to the SG of your database:
egress {
    from_port   = 0
    protocol    = -1
    to_port     = 0
    security_groups = [database_security_group_id]
  }


text:
Q: How to recover data from a corrupt SQLite3 database? I've recovered data from a formatted hard drive for use in a lawsuit. The data is Skype logs, which are stored in SQLite3 databases. Unfortunately, the disk was formatted and a new copy of OS X was installed on the drive. I scanned the drive and found the files I am looking for, but it seems that the database I'm after is corrupt.
I tried the following command I found by searching on SO:
$ sqlite3 mydata.db ".dump" | sqlite3 new.db

Unfortunately, dumping this way excludes the table of records I'm looking for (Messages). Since I can get the format of the DB from Skype by just logging in with another account and generating a new main.db for it, do I have any additional options for extracting the contents of the corrupt DB? Failing that, is there a way to export the raw contents of the database in a text file or something? I only care about grabbing certain messages, which I can search for.

A: When the database is corrupt, the ".dump" command extracts all of the usable information, but then ends with a ROLLBACK because it encountered corruption.
Instead, store the output in a file:
$ sqlite3 mydata.db ".dump" > mydata.dump

Then, you can view the data directly in that file, or you can change the last line from "ROLLBACK" to "COMMIT" using a text editor. After that, you can load the valid portion of the data into a database using:
$ sqlite3 new.db < mydata.dump

A: First check for the PRAGMA integrity_check in command console and click on play button, note down the errors and repair them seperately or try exporting and then importing SQL file to new database and restart the database, it generally removes the slug files stored in the cache. If the above method does not work out then you can try SQLite database recovery tool https://www.recoveryandmanagement.com/repair-sqlite-database-manually/


text:
Q: Is it possible to clone an AST in Clang? I have an AST that I have created by parsing source-code using the Clang library. I would like to clone the AST so that I can parse some other code which might be invalid. If it is invalid, I will return to my clone for parsing further source-code snippets. I don't want to have to parse the same source-code twice for performance reasons.
The Clang AST representation is very rich, and some nodes contain pointers to other nodes.
Does Clang provide a utility for easily cloning ASTs that handles this complexity?


text:
Q: how to inser dash(-) between the given number but i want to enter in between even numbers The program seems like this it is nice but it jumps between 4 and 6 I have not to get the idea?
if anyone sole this.
     **I want to enter dash between the given consecutive even numbers..** * but in my testing, I jump the even number*

**when I check my code is correct but there there is one error I jump my first even numbers **
`
function convertNumber(num) {
        let arr = num.toString().split('').map(Number);
        for (let i = 0; i <= arr.length; i++) {
            let check = arr[i];
            let check2 = arr[i + 1]
            // console.log(check);
            if (check % 2 == 0) {
                console.log(check);
                if (check2 % 2 == 0) {
                    arr.splice(check, 0, "-");
                    // console.log(arr);
                }
                // console.log(check);
                // console.log(-1);
            }
        }
        console.log(arr);
        // console.log(typeof (arr));
    }
    convertNumber(025468)

;`

A: Are you trying to get [2, 5, 4, '-', 6, '-', 8]?
You should create a new array and push elements in there. I recommend against doing splice on the array on which you are looping. Rule of thumb, don't change the array where you do the for loop.
function convertNumber(num) {
  let newArr = [];
  let arr = num.toString().split("").map(Number);
  for (let i = 0; i <= arr.length; i++) {
    let check = arr[i];
    let check2 = arr[i + 1];
    // console.log(check);
    if (check % 2 == 0) {
      console.log(check);
      newArr.push(check);
      if (check2 % 2 == 0) {
        newArr.push("-");
        // console.log(arr);
      }
      // console.log(check);
      // console.log(-1);
    }
  }
  console.log(newArr);
  // console.log(typeof (arr));
  return newArr;
}

convertNumber(025468);

Note: I added return newArr

A:

function convertNumber(num) {
        let arr = [];
        const str = num.toString();

        for(let i = 0; i < str.length; i++) {
          arr.push(Number(str[i]))
          if (Number(str[i]) % 2 === 0 && Number(str[i + 1]) % 2 === 0) {
            arr.push('-');
          }
        }
        console.log(arr);
        // console.log(typeof (arr));
    }
    convertNumber(025468)


text:
Q: Changing variable to draw on Canvas I'm having a few issues with canvas and changing a variable to assign a different mousestate. I have shown a section of my code below.
$("#shape").click(function() {  //Runs the drawbackground function on click
    mouse_state = "fill_shape";
    console.log("shape: " + mouse_state);
});

$("#paint").click(function() {  //Runs the drawbackground function on click
    console.log('hi');
    mouse_state = "paint";
    console.log("paint: " + mouse_state);
});

var mouse_state = "paint";

if (myCanvas) { //Checks is canvas exists and/or is supported by the browser
    var isDown = false;  //Stores the current status of the mouseclick, default is not down
    var ctx = myCanvas.getContext("2d"); //Stores the 2d context of the canvas
    var canvasX, canvasY;  //Initialises variables canvasX and canvasY

    if (mouse_state == "paint"){
    $(myCanvas).mousedown(function(e) { //When the user clicks on the canvas, this function runs
        e.preventDefault();  //Prevents the cursor from changing when clicking on the canvas
        isDown = true; //Sets the mouseclick variable to down
        ctx.beginPath(); //Begins the path
        canvasX = e.pageX - myCanvas.offsetLeft; //Stores the mouse position on the x axis by subtracting the distance from the left edge of the canvas from the position from the left edge of the document.
        canvasY = e.pageY - myCanvas.offsetTop; //Stores the mouse position on the y axis by subtracting the distance from the top edge of the canvas from the position from the top edge of the document.
        ctx.moveTo(canvasX, canvasY);  //Sets the position which the drawing will begin
    }).mousemove(function(e) {
        if (isDown != false) { //On the mousemouse the line continues to be drawn as the mouseclick variable will still be set as false
            canvasX = e.pageX - myCanvas.offsetLeft; //Similar to above
            canvasY = e.pageY - myCanvas.offsetTop;
            ctx.lineTo(canvasX, canvasY); //Stores the information which should be drawn
            ctx.strokeStyle = current_colour; //Sets the colour to be drawn as the colour stored in the current colour variable
            ctx.stroke();  //Draws the path given
        }
    }).mouseup(function(e) {  //When the mouse click is released, do this function...
        isDown = false; //Sets the mouseclick variable to false
        ctx.closePath();  //Closes the path
    });
}

    else if(mouse_state == "fill_shape"){
    //Checks is canvas exists and/or is supported by the browser

    $(myCanvas).mousedown(function(ev) { //When the user clicks on the canvas, this function runs
         console.log("1" + mouse_state);
        ev.preventDefault();  //Prevents the cursor from changing when clicking on the canvas
        isDown = true; //Sets the mouseclick variable to down
        ctx.beginPath(); //Begins the path
        canvasX = ev.pageX - myCanvas.offsetLeft; //Stores the mouse position on the x axis by subtracting the distance from the left edge of the canvas from the position from the left edge of the document.
        canvasY = ev.pageY - myCanvas.offsetTop; //Stores the mouse position on the y axis by subtracting the distance from the top edge of the canvas from the position from the top edge of the document.
        ctx.moveTo(canvasX, canvasY);  //Sets the position which the drawing will begin
    }).mousemove(function(ev) {
        if (isDown != false) { //On the mousemouse the line continues to be drawn as the mouseclick variable will still be set as false
            canvasX = ev.pageX - myCanvas.offsetLeft; //Similar to above
            canvasY = ev.pageY - myCanvas.offsetTop;
            ctx.lineTo(canvasX, canvasY); //Stores the information which should be drawn
            ctx.strokeStyle = current_colour; //Sets the colour to be drawn as the colour stored in the current colour variable
            ctx.stroke();  //Draws the path given
        }
    }).mouseup(function(ev) {  //When the mouse click is released, do this function...
        ctx.fillStyle = current_colour;
        ctx.fill();
        isDown = false; //Sets the mouseclick variable to false
        ctx.closePath();  //Closes the path
    });

}};

The drawing of the canvas works fine and the two different 'mouse_states' work fine with the first (paint) simply drawing the lines or shapes and the second (fill_shape) drawing shapes and then filling them in using ctx.fill.
The mouse_state variable is initialised as "paint" so the paint function runs and when I change it to "shape_fill" the shape fill function runs fine.  The problem arises when changing between the two states using the buttons to change the variable name.  The console log shows that the variable name changes as expected but it just doesn't seem to take any affect and sticks with the initial value of the mouse_state variable.  I would appreciate any help or tips with this.

A: You're running the if statements at the wrong time - they're executing on page load, and subsequently only binding the first set of events.
Instead, bind only one set of events, and check the variable within them and run the corresponding code:
if (myCanvas) { //Checks is canvas exists and/or is supported by the browser
  var isDown = false; //Stores the current status of the mouseclick, default is not down
  var ctx = myCanvas.getContext("2d"); //Stores the 2d context of the canvas
  var canvasX, canvasY; //Initialises variables canvasX and canvasY

  $(myCanvas).mousedown(function(e) { //When the user clicks on the canvas, this function runs
    if (mouse_state == "paint") {
       //code for paint
    } else if (mouse_state == "fill_shape") {
       //code for fill_shape
    }
  }); //etc, for other events
}


text:
Q: eyeball comparison Is it correct to use the term "eyeball comparison" to say that two things have been compared by eye?
In the specific case, I am comparing two statistical distributions without doing any quantitative test to compare the two distributions.

A: In math, we might say

By inspection

So something like

The two distributions appear to follow the same distribution by inspection.

In an informal setting, you might say

I eye-balled it and they look the same.

A: Instead of using 'eyeball comparison', why not use:

visual comparison - to compare two or more things by eye. This might be done by placing them side by side; by overlaying them; by alternating an image or by presenting each image to a separate eye.

A: An "eyeball comparison" is typically meant that something "looks close enough for what we're doing" when no actual measurement was taken since it wasn't needed.

I "eyeballed" which book on my shelf would help eliminate the wobble in the table.

Does it really matter that the book you chose was 75cm thick vs the one next to it being 82cm? Not really. It's "close enough".
Since you said

I am comparing two statistical distributions without doing any
  quantitative test to compare the two distributions

That would be the correct term.


text:
Q: Programatically change display of the sort icon in datagrid column header I asked this question previously and did not get an answer but now I have more detail.
Basically I want to programatically display the column sort icon in a wpf datagrid column.
I have the following code to do this:
private void dtgMain_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            dtgMain.Columns[0].SortDirection = ListSortDirection.Ascending;
        }

This seems to set the sort order of the column but when the grid is drawn the icon does not show.
When I add a message box into the method it works fine. My question is twofold. Why would the message box cause the method to work? And how can I get it to work without the use of a messagebox?
This is the method working with the messagebox in it:
private void dtgMain_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    MessageBox.Show("Here");
    dtgMain.Columns[0].SortDirection = ListSortDirection.Ascending;
}

edit
Here is the method that is setting the datacontext of the datagrid
public void processLoad(string response)
        {
            XmlDataProvider provider = new XmlDataProvider();

            if (provider != null)
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(response);
                provider.Document = doc;
                provider.XPath = "/moo/response/data/load/panel";
                dtgMain.DataContext = provider;

            }

        }

Please let me know if you need anymore information.

A: OK, I suspect what is happening is that the data layout changes caused by the DataContext update are being completed after your call to set the direction arrow, and it is therefore being erased after you set it. Interestingly, in my case it failed to work even when I put the messagebox in, perhaps because that was hanging up the UI thread while it displayed.
Could you try replacing the line that sets the sort direction with a similar call put on the dispatcher queue:
    dtgMain.Dispatcher.BeginInvoke(new Action(() =>
    {
        dtgMain.Columns[0].SortDirection = ListSortDirection.Ascending;
    }), DispatcherPriority.ApplicationIdle);

and see if that works?


text:
Q: Pass css ::after content as specific word from class name I want to pass CSS ::after content as a specific word from its class element.
If class names are "language-css", "language-html", etc, in this case, I want to pass the content as the word after the "-".

code::before {
  content: attr(class);
}
 some code here
 some code here
 some code here

I know this returns the whole text from the CSS class, does CSS support any split function as JavaScript does?

A: In this particular case, you can hack is with some negative text-indent if the prefix is always the same. The code element is using a monospace font so it's easy using ch unit

code::before {
  content: attr(class);
  display:inline-block;
  text-indent:-9ch; /* adjust this based on your real case */
  clip-path:inset(0); /* hide the overflow */
}
 some code here
 some code here
 some code here


text:
Q: Pyomo: "No value for uninitialized NumericValue object", trying to evaluate a Binary constraint Working with Pyomo and GLPK 4.65, I'm trying to optimize the production of several factories for several products.
One of the costs to be reduced in the optimization is associated to the fact that if a factory must be started, there is a Starting Cost of $100.
# I define the Binary Constraint to know if the factory was producing, by seeing a 'factories_list', and by using 'big M'
model.factory_was_producing = Var(model.T, model.i, model.k, domain=Binary)
def factory_was_producing_rule(model, T, i, k):
    return factories_list[0, i, k] <= model.factory_was_producing[T,i,k] * 1000000
model.factory_was_producing_constraint = Constraint(model.T, model.i, model.k, rule=factory_was_producing_rule)

# I try to define the Starting costs, by multiplying the $100 by the binary constraing 'factory_was_producing_constraint'
def f_Factory_Starting_Costs(model, T, i, k):
    return 100 * value(model.factory_was_producing_constraint[T,i,k])
model.Factory_Starting_Costs = Param(model.T, model.i, model.k, rule=f_Factory_Starting_Costs)

However, I get the following error:
ValueError: No value for uninitialized NumericValue object factory_was_producing[1,Boston,Product_A]

The 'factory_was_producing' constraint seems to return righ values:
factory_was_producing : Size=24, Index=factory_was_producing_index
    Key                             : Lower : Value : Upper : Fixed : Stale : Domain
         (1, 'Boston', 'Product_A') :     0 :   0.0 :     1 : False : False : Binary
        (1, 'Florida', 'Product_A') :     0 :   1.0 :     1 : False : False : Binary
       (1, 'New York', 'Product_A') :     0 :   0.0 :     1 : False : False : Binary

I've been browsing solutions for this common error, dealing with 'either-or' constraints and conditional constraints, but I'm not able to understand them to be used in my problem.

A: You are popping that error because in this statement:
# I try to define the Starting costs, by multiplying the $100 by the binary constraing 'factory_was_producing_constraint'
def f_Factory_Starting_Costs(model, T, i, k):
    return 100 * value(model.factory_was_producing_constraint[T,i,k])
model.Factory_Starting_Costs = Param(model.T, model.i, model.k, rule=f_Factory_Starting_Costs)

You are using value() during the creation of the model and at that point the variable value is unknown*.  Also...  You cannot make this into a Param which is a fixed value inside the model.  I'm not sure what you are trying to accomplish there.  If you capture the value of the startup cost in the previous constraint, you can just use that in your objective function.  In pseudocode:
obj = <some cost summation stuff> + model.start_factory[...] * 100

I do think you probably have some more thinking to do regarding your time indexing.  :)  Is it possible to "start" the factory in every tilmestep independently or maybe just not index that variable by time.... ?
*yes, you could initialize the value and get something here, but that would be only a snapshot and incorrect structure.


text: Q: Regulator of an algebraic number field and regulator of units. Let $K$ be an algebraic number field. I would like to know why in totally real fields regulator is at most equal to regulator of a set of $n-1$ independent units. What happens in the case of $K$ not being totally real?


text:
Q: Codeanywhere can't find editor for Rails 5.2.1 app I am having difficulty accessing the command: rails credentials:edit using the Codeanywhere environment. I am running Rails 5.2.1 and Ruby 2.5.1.
I receive the following response from the terminal:
No $EDITOR to open file in. Assign one like this:

EDITOR="mate --wait" bin/rails credentials:edit

For editors that fork and exit immediately, it's important to pass a
wait flag, otherwise the credentials will be saved immediately
with no chance to edit.

I don't seem to be able to get this working.
Can someone please help?
Thank you.

A: This means that you haven't set the environment variable that determines your editor. The example in the output will make TextMate your default editor.
Not sure what editors are available in CodeAnywhere, but most systems have access to VIM, so you might try running:
EDITOR="vim --wait" bin/rails credentials:edit
You may not need to pass the --wait option.


text:
Q: Sqlx join table with same fields I'm using Go 1.17 with Sqlx but I don't understand how I can join my table correctly.
Here is my structs (my join isn't logic I'm just testing jointure with sqlx)
Table album:
package album

import ".../api/v1/movie"

type Album struct {
    ID      string  `json:"id"`
    Title   string  `json:"title"`
    Artist  string  `json:"artist"`
    Price   float64 `json:"price"`
    MovieId int     `json:"movie_id" db:"movie_id"`
    movie.Movie
}

Table movie:
package movie

type Movie struct {
    ID         string `json:"id"`
    Year       uint16 `json:"year"`
    RentNumber uint32 `json:"rent_number" db:"rent_number"`
    Title      string `json:"title"`
    Author     string `json:"author"`
    Editor     string `json:"editor"`
    Index      string `json:"index"`
    Bib        string `json:"bib"`
    Ref        string `json:"ref"`
    Cat1       string `json:"cat_1" db:"cat_1"`
    Cat2       string `json:"cat_2" db:"cat_2"`
}

And this is how I do my join:
albums := []Album{}
r.db.Select(&albums, "SELECT * FROM album a INNER JOIN movie m ON (m.id=a.movie_id)")

The problem is that these 2 tables have the same id field so the album id is overridden by the movie id and I lost it.
How can I do to ignore the movie id field (because I got it in the movie_id field and keep the field id for the album id ?

A: You can give one of your id fields an id tag like:
type Album struct {
    ID      string  `json:"id" id:"album_id"`
    Title   string  `json:"title"`
    Artist  string  `json:"artist"`
    Price   float64 `json:"price"`
    movie.Movie
}

and then make a query which aliases the id field to album_id like:
SELECT movie.id as id, album.id as album_id, ... FROM album ...

Just keep in mind that you now need to use this column name in your named queries as well.


text:
Q: String Comparison in C++ with IF Statements? I'm very new to C++, just started learning using an online course about 30 minutes ago. I'm a little confused as to why this string comparison isn't working in a basic math script:
#include <iostream>
#include <string>
using namespace std;

int main() {
  int one, two, answer;
  char *oper;

  cout << "Add two numbers\n\nEnter your first number" << endl;
  cin >> one;
  cout << "Choose an operator: +  -  *  /  %%" << endl;
  cin >> oper;

  cout << "Enter your second number" << endl;
  cin >> two;

  if (oper == "+") {
    answer = one + two;
  }
  else if (oper == "-") {
    answer = one - two;
  }
  else if (oper == "*") {
    answer = one * two;
  }
  else if (oper == "/") {
    answer = one / two;
  }
  else if (oper == "%%") {
    answer = one % two;
  }

  cout << one << " " << oper << " " << two << " = " << answer << endl;

  return 0;
}

The values for one, oper, and two are 1, "+", and 1 respectively, but in the end, 1 + 1 = 4201435 is printed out. None of the if/else if statements are being executed. What's causing this?

A: You're comparing char * using operator==. Either let oper be a std::string instead
std::string oper
To use the string comparison listed here: http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp
or if you need to use a char * for some restriction, use strcmp:
if (!strcmp(oper, "+")) {
// ...

You also need to have your operand variable point at some buffer too, for the stream to read into. This is a little bit more complicated and I just recommend changing the type of oper to std::string.
The problem with the code you have is that it's comparing pointers to char arrays. What you get from your input methods is going to be a new string from the input stream and will never have the same address as the readonly strings in your program.
So since none of the condition is true, ans hasn't been assigned. So output it accounts for an undefined behavior.


text:
Q: Xamarin Forms Facebook Authentication I'm trying to use OAuth Facebook Authentication to login into my Xamarin.Forms application.
This is my athentication:
try
{
    var auth = new OAuth2Authenticator(
                clientId: Constants.FacebookAndroidClientId,
                scope: "email",
                authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html"));

                auth.Completed += Auth_Completed;
                auth.Error += Auth_Error;
                auth.BrowsingCompleted += Auth_BrowsingCompleted;
}
catch(Exception ex)
{

}

But no event is firing. The authentication is created and nothing more happens.
Can anyone help me?

A: You may missed some steps when using Xamarin.Auth to authenticate users, the code you shared is not enough. You also need to Presenting the Sign-In User Interface in specific platform and do some configurations.
Here is the document you can read: Authenticate Users with an Identity Provider
Here is the sample project of Xamarin.Auth, there are also detailed steps you can follow.
BTW, you should also be attention to your Facebook Login settings as mentioned in this thread.


text:
Q: Restart JS function (endless scroll) when used in different pages, to avoid accumulated results I have an endless scroll JavaScript function working fine for different pages when loading each page for the first time.
The problem: The function gets called again when visiting the other pages, resulting in duplicate repeated results (2x) for the secondly visited page's endless scroll, and 3x for the next one, and so on, when clicking the page's links, though it works fine when manually refreshing each page.
I can not move the JS code from each view, to the main Layout view because it requires other JS code running within each view.
My question: How can I refresh/clear the JS function upon visiting each page so it starts fresh? Or which alternatives do I have?
This is the code on each page with pagination:
$(document).on('ready page:load', function () {
var isLoading = false;
var num = 2;
  if ($('.pagination').length) {
    $(window).scroll(function(e) {
      var url = $('.pagination .next_page').attr('href');
   if (!isLoading) {
      if (url && $(window).scrollTop() > $(document).height() - $(window).height() - 1500) {
      isLoading = true;
        var newUrl = url.replace("page="+num-1, "page="+num);
        $('#loader').html('<img src="/assets/gmloader.gif" alt="loading..." />');
        setTimeout(function(){isLoading=false},1000);
        num++;
        return $.getScript(newUrl);
      }
    }
    });
    return $(window).scroll();
  }
});

I appreciate your help.


text:
Q: sys.excepthook in multiprocessing.Process ignored? Suppose we have the two files namely mymanger.py and mysub.py.
mymanager.py
import time
from multiprocessing import Process

import mysub  # the process file

def main():

    xprocess = Process(
        target=mysub.main,
        )

    xprocess.start()
    xprocess.join()

    time.sleep(1)
    print(f"== Done, errorcode is {xprocess.exitcode} ==")

if __name__ == '__main__':
    main()

mysub.py
import sys

def myexception(exc_type, exc_value, exc_traceback):
    print("I want this to be printed!")
    print("Uncaught exception", exc_type, exc_value, exc_traceback)

def main():
    sys.excepthook = myexception  # !!!
    raise ValueError()

if __name__ == "__main__":
    sys.exit()

When executing mymanager.py the resulting output is:
Process Process-1:
Traceback (most recent call last):
  File "c:\program files\python\3.9\lib\multiprocessing\process.py", line 315, in _bootstrap
    self.run()
  File "c:\program files\python\3.9\lib\multiprocessing\process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\lx\mysub.py", line 11, in main
    raise ValueError()
ValueError
== Done, errorcode is 1 ==

When the output i expected would be something like:
I want this to be printed!
Uncaught exception <class 'ValueError'>  <traceback object at 0x0000027B6F952780>

which is what i get if i execute main from mysub.py without the multiprocessing.Process.
I've checked the underlying cpython (reference) and the problem seems to be that the try-except in the _boostrap function takes precedence over my child processes sys.excepthook but from my understanding, shouldn't the excepthook from the childs process fire first and then trigger the except from the _boostrap?
I need the child process to handle the exception using the sys.excepthook function.
How can i achieve that?

A: sys.excepthook is invoked when an exception goes uncaught (bubbling all the way out of the running program). But Process objects run their target function in a special bootstrap function (BaseProcess._bootstrap if it matters to you) that intentionally catches all exceptions, prints information about the failing process plus the traceback, then returns an exit code to the caller (a launcher that varies by start method).
When using the fork start method, the caller of _bootstrap then exits the worker with os._exit(code) (a "hard exit" command which bypasses the normal exception handling system, though since your exception was already caught and handled this hardly matters). When using 'spawn', it uses plain sys.exit over os._exit, but AFAICT the SystemExit exception that sys.exit is implemented in terms of is special cased in the interpreter so it doesn't pass through sys.excepthook when uncaught (presumably because it being implemented via exceptions is considered an implementation detail; when you ask to exit the program it's not the same as dying with an unexpected exception).
Summarizing: No matter the start method, there is no possible way for an exception raised by your code to be "unhandled" (for the purposes of reaching sys.excepthook), because multiprocessing handles all exceptions your function can throw on its own. It's theoretically possible to have an excepthook you set in the worker execute for exceptions raised after your target completes if the multiprocessing wrapper code itself raises an exception, but only if you do pathological things like replace the definition of os._exit or sys.exit (and it would only report the horrible things that happened because you replaced them, your own exception was already swallowed by that point, so don't do that).

If you really want to do this, the closest you could get would be to explicitly catch exceptions and manually call your handler. A simple wrapper function would allow this for instance:
def handle_exceptions_with(excepthook, target, /, *args, **kwargs)
    try:
        target(*args, **kwargs)
    except:
        excepthook(*sys.exc_info())
        raise  # Or maybe convert to sys.exit(1) if you don't want multiprocessing to print it again

changing your Process launch to:
    xprocess = Process(
        target=handle_exceptions_with,
        args=(mysub.myexception, mysub.main)
    )

Or for one-off use, just be lazy and only rewrite mysub.main as:
def main():
    try:
        raise ValueError()
    except:
        myexception(*sys.exc_info())
        raise  # Or maybe convert to sys.exit(1) if you don't want multiprocessing to print it again

and leave everything else untouched. You could still set your handler in sys.excepthook and/or threading.excepthook() (to handle cases where a thread launched in the worker process might die with an unhandled exception), but it won't apply to the main thread of the worker process (or more precisely, there's no way for an exception to reach it).


text:
Q: Resharpers smart code completion CodeRush equivalent I am currently switching from Resharper to CodeRush.
One thing I used a lot in Resharper is the "smart code completion" (Ctrl+Alt+Space) so that in e.g. switch case I could hit the shortcut and Resharper would automatically provide a list of the type that I was switching (typically enums).
Does Coderush have a similar feature?

A: *

*Copy the enum variable you wish to switch on, to the clipboard.

*Type sw[space]
CodeRush will build you a switch statement with cases for each enum value.


text:
Q: fire treeloader with new url on node click extjs 3 I am trying append child nodes to a tree node when the node is clicked. It is required to fire a tree loader with desired url whenever a particular node is clicked.
I tried something like this
tree.dataUrl = '/zport/clusterSysReg?args=/directory/'+node.attributes.name;
//alert(tree.dataUrl);
node.reload();

whenever I click on a node the child nodes are created but not with the new url, but with the old url, I also tried node.load instead of node.reload(), but I am getting an error .........
Any idea how to proceed

A: Here is the solution to the above problem (took me whole day to solve this)
Inside the listner function added the following lines
listeners: {
   'render': function(tp){

            tp.getSelectionModel().on('selectionchange', function(tree, node){

            tp.getLoader().dataUrl = '/zport/clusterSysReg?args='+node.attributes.name;
            tp.getLoader().load(node);
            ......................
            ......................
            }
}


text:
Q: Can't use rvm install rails 5 gem I tried to create gemset rails500 by ruby-2.3.1 and I got :

Using /Users/ChamperWu/.rvm/gems/ruby-2.3.1 with gemset rails500
jiaqideMacBook-Pro:unispot ChamperWu$ gem install rails
Fetching: i18n-0.7.0.gem (100%)
Successfully installed i18n-0.7.0
Fetching: thread_safe-0.3.5.gem (100%)
Successfully installed thread_safe-0.3.5
Fetching: tzinfo-1.2.2.gem (100%)
Successfully installed tzinfo-1.2.2
Fetching: concurrent-ruby-1.0.2.gem (100%)
Successfully installed concurrent-ruby-1.0.2
Fetching: activesupport-5.0.0.1.gem (100%)
Successfully installed activesupport-5.0.0.1
Fetching: rack-2.0.1.gem (100%)
Successfully installed rack-2.0.1
Fetching: rack-test-0.6.3.gem (100%)
Successfully installed rack-test-0.6.3
Fetching: mini_portile2-2.1.0.gem (100%)
Successfully installed mini_portile2-2.1.0
Fetching: nokogiri-1.6.8.1.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing rails:
  ERROR: Failed to build gem native extension.

    current directory: /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/nokogiri-1.6.8.1/ext/nokogiri
/Users/ChamperWu/.rvm/rubies/ruby-2.3.1/bin/ruby -r ./siteconf20161026-41490-k9it32.rb extconf.rb
checking if the C compiler accepts ... yes
checking if the C compiler accepts -Wno-error=unused-command-line-argument-hard-error-in-future... no
Building nokogiri using packaged libraries.
Using mini_portile version 2.1.0
checking for iconv.h... yes
checking for gzdopen() in -lz... yes
checking for iconv using --with-opt-* flags... yes
************************************************************************
IMPORTANT NOTICE:

Building Nokogiri with a packaged version of libxml2-2.9.4.

Team Nokogiri will keep on doing their best to provide security
updates in a timely manner, but if this is a concern for you and want
to use the system library instead; abort this installation process and
reinstall nokogiri as follows:

    gem install nokogiri -- --use-system-libraries
        [--with-xml2-config=/path/to/xml2-config]
        [--with-xslt-config=/path/to/xslt-config]

If you are using Bundler, tell it to use the option:

    bundle config build.nokogiri --use-system-libraries
    bundle install

Note, however, that nokogiri is not fully compatible with arbitrary
versions of libxml2 provided by OS/package vendors.
************************************************************************
Extracting libxml2-2.9.4.tar.gz into tmp/x86_64-apple-darwin16.0.0/ports/libxml2/2.9.4... OK
Running 'configure' for libxml2 2.9.4... OK
Running 'compile' for libxml2 2.9.4... ERROR, review '/Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/nokogiri-1.6.8.1/ext/nokogiri/tmp/x86_64-apple-darwin16.0.0/ports/libxml2/2.9.4/compile.log'

to see what happened. Last lines are:
      ========================================================================
          unsigned short* in = (unsigned short*) inb;
                               ^~~~~~~~~~~~~~~~~~~~~
      encoding.c:815:27: warning: cast from 'unsigned char *' to 'unsigned short ' increases required alignment from 1 to 2
  [-Wcast-align]
          unsigned short out = (unsigned short*) outb;
                                ^~~~~~~~~~~~~~~~~~~~~~
      4 warnings generated.
        CC       error.lo
        CC       parserInternals.lo
        CC       parser.lo
        CC       tree.lo
        CC       hash.lo
        CC       list.lo
        CC       xmlIO.lo
      xmlIO.c:1450:52: error: use of undeclared identifier 'LZMA_OK'
          ret =  (__libxml2_xzclose((xzFile) context) == LZMA_OK ) ? 0 : -1;
                                                         ^
      1 error generated.
      make[2]: * [xmlIO.lo] Error 1
      make[1]:  [all-recursive] Error 1
      make:  [all] Error 2
      ========================================================================
      * extconf.rb failed ***
      Could not create Makefile due to some reason, probably lack of necessary
      libraries and/or headers.  Check the mkmf.log file for more details.  You may
      need configuration options.
Provided configuration options:
  --with-opt-dir
  --with-opt-include
  --without-opt-include=${opt-dir}/include
  --with-opt-lib
  --without-opt-lib=${opt-dir}/lib
  --with-make-prog
  --without-make-prog
  --srcdir=.
  --curdir
  --ruby=/Users/ChamperWu/.rvm/rubies/ruby-2.3.1/bin/$(RUBY_BASE_NAME)
  --help
  --clean
  --use-system-libraries
  --enable-static
  --disable-static
  --with-zlib-dir
  --without-zlib-dir
  --with-zlib-include
  --without-zlib-include=${zlib-dir}/include
  --with-zlib-lib
  --without-zlib-lib=${zlib-dir}/lib
  --enable-cross-build
  --disable-cross-build
/Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:366:in

block in execute': Failed to complete compile task (RuntimeError)
        from /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:337:in
  chdir'
        from /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:337:in
  execute'
        from /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:111:in
  compile'
        from /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:150:in
  cook'
        from extconf.rb:365:inblock (2 levels) in process_recipe'
        from extconf.rb:258:in block in chdir_for_build'
        from extconf.rb:257:inchdir'
        from extconf.rb:257:in chdir_for_build'
        from extconf.rb:364:inblock in process_recipe'
        from extconf.rb:263:in tap'
        from extconf.rb:263:inprocess_recipe'
        from extconf.rb:556:in `'
To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/extensions/x86_64-darwin-16/2.3.0/nokogiri-1.6.8.1/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/gems/nokogiri-1.6.8.1

for inspection.
      Results logged to /Users/ChamperWu/.rvm/gems/ruby-2.3.1@rails500/extensions/x86_64-darwin-16/2.3.0/nokogiri-1.6.8.1/gem_make.out

I tried to uninstall and install it again, but I got the same info
how can I fix it?

A: It might help:
brew uninstall xz
gem install nokogiri -v 1.6.8 or gem install rails (command you are running)