text:
Q: Encontrei o erro AttributeError: 'DataFrame' object has no attribute 'media_url' como posso ajustar? obrigada import pandas as pd
import numpy as np
from datetime import datetime, date, timedelta
import time
from google.cloud import storage
import io
import re
import requests
import gcsfs

def bq_date(x):
    if len(str(x.day)) == 1:
        day = "0" + str(x.day)
    else:
        day = str(x.day)

    if len(str(x.month)) == 1:
        month = "0" + str(x.month)
    else:
        month = str(x.month)

    return "{0}{1}{2}".format(x.year, month, day)

def list_gcs_objs(bucket, prefix):
    storage_client = storage.Client()
    bucket_check = storage_client.get_bucket(bucket)
    blob_list = list(bucket_check.list_blobs(prefix=prefix))
    obj_paths = list()
    if len(blob_list) <= 1:
        print("Folder empty\n")
        return obj_paths
    else:
        count = 1
    while count < len(blob_list):
        obj_paths.append(blob_list[count].name)
        count += 1
    return obj_paths

def upload_to_gcs(bucket, object_key, data):
    storage_client = storage.Client(bucket)
    bucket_up = storage_client.get_bucket(bucket)
    blob_up = bucket_up.blob(object_key)
    response = blob_up.upload_from_string(data)
    return (response)

def getInstagramStoriesFeed(base_url):
    fields = "?fields=id,caption,media_type,media_url,permalink,timestamp,username"
    return base_url + fields

def getStories_Insights(post_id, access_token):
    base = "https://graph.facebook.com/v3.2/"
    arequest = "{0}/insights?access_token={1}&metric=".format(post_id, access_token) + \
               "impressions,reach,replies,exits,taps_forward,taps_back"
    return base + arequest

def scrapeInstagramStories(page_id, access_token, since_date, until_date):
    global ndf, sf
    from datetime import date
    scrape_starttime = date.today()
    base_url = "https://graph.facebook.com/v3.2"
    node = "/{}/stories?fields=".format(page_id)
    fields = "id,caption,media_type,permalink,timestamp,username"
    parameters = "&limit=100&access_token={0}".format(access_token)
    anchor = since_date
    after = ''

    print("Scraping {} Instagram Page: {}\n".format(page_id, scrape_starttime))
    ctr = 1
    count = 0
    while (anchor >= since_date) & (count < 10):
        after = '' if after is '' else "&after={}".format(after)
        url = base_url + node + fields + parameters + after

        content = requests.get(url).json()
        sf = pd.DataFrame.from_dict(content['data'])

        if len(sf) > 0:
            sf['timestamp'] = pd.to_datetime(sf.timestamp, infer_datetime_format=True)
            sf['data'] = sf.timestamp.apply(lambda x: x.date())
            anchor = sf.data.min()

        # if there is no next page, we're done.
        if 'paging' in content:
            after = content['paging']['cursors']['after']
            if ctr == 1:
                ndf = sf.copy()
            else:
                ndf = pd.concat([sf, ndf], sort=False)
            ctr += 1
        else:
            pass

        count += 1

    if ndf.empty:
        return ndf

    date_index = list(pd.date_range(start=since_date, end=until_date))
    ndf['timestamp'] = pd.to_datetime(ndf.timestamp, infer_datetime_format=True)
    ndf['data'] = ndf.timestamp.apply(lambda x: x.date())

    ndf['data'] = np.where(ndf.data.isin(date_index),
                           np.nan,
                           ndf.data)

    ndf.dropna(subset=['data'], inplace=True)
    ndf['data'] = pd.to_datetime(ndf.data, infer_datetime_format=True)

    impressions = {}
    reach = {}
    replies = {}
    exits = {}
    tf = {}
    tb = {}

    for post in ndf.id.unique():
        aux_url = getStories_Insights(post, access_token)
        insights = requests.get(aux_url).json()
        if len(insights) > 0:
            impressions.update({post: insights['data'][0]['values'][0]['value']})
            reach.update({post: insights['data'][1]['values'][0]['value']})
            replies.update({post: insights['data'][2]['values'][0]['value']})
            exits.update({post: insights['data'][3]['values'][0]['value']})
            tf.update({post: insights['data'][4]['values'][0]['value']})
            tb.update({post: insights['data'][5]['values'][0]['value']})
        else:
            impressions.update({post: 0})
            reach.update({post: 0})
            replies.update({post: 0})
            exits.update({post: 0})
            tf.update({post: 0})
            tb.update({post: 0})

    ndf['impressions'] = ndf.id.map(impressions)
    ndf['reach'] = ndf.id.map(reach)
    ndf['replies'] = ndf.id.map(replies)
    ndf['exits'] = ndf.id.map(exits)
    ndf['taps_forward'] = ndf.id.map(tf)
    ndf['taps_back'] = ndf.id.map(tb)

    ndf['id'] = ndf.id.astype('category')
    # ndf['caption'] = ndf.caption.astype('category')
    # ndf['media_type'] = ndf.media_type.astype('category')
    # ndf['permalink'] = ndf.permalink.astype('category')
    # ndf['username'] = ndf.username.astype('category')

    ndf['impressions'] = ndf.impressions.astype('int64')
    ndf['reach'] = ndf.reach.astype('int64')
    ndf['replies'] = ndf.replies.astype('int64')
    ndf['exits'] = ndf.exits.astype('int64')
    ndf['taps_forward'] = ndf.taps_forward.astype('int64')
    ndf['taps_back'] = ndf.taps_back.astype('int64')

    return ndf

def st_scrapper(request):
    global ndf
    since_date = (date.today() - timedelta(1))
    until_date = date.today()
    today = date.today().strftime("%Y%m%d")

    mybucket = "gdata-dn-gshow-sandbox"
    mainprefix = "AD/INS/"

    # List FB Avaiable Data

    maindata = list_gcs_objs(mybucket, mainprefix)
    ins_dates = [x[-12:-4] for x in maindata]

    # Queries
    query_tags = "SELECT * FROM `globoid.AD_gshow_hashtags`"

    dtags = pd.read_gbq(query_tags, dialect='standard', index_col="Hashtag")
    tags = dtags['Produto'].to_dict()

    user_token = ""

    gshow_pages = {'',
                   }

    gshow_pagelist = list(gshow_pages.keys())

    ctr = 1
    for page in gshow_pagelist:
        print("{0} | Date Range {1} - {2}".format(gshow_pages[page],
                                                  since_date.strftime("%Y-%m-%d"),
                                                  until_date.strftime("%Y-%m-%d"))
              )
        if ctr == 1:
            df = scrapeInstagramStories(page_id=page, access_token=user_token,
                                        since_date=since_date, until_date=until_date)

            if df.empty:
                print("{0} is empty!".format(gshow_pages[page]))
                pass
            else:
                ndf = df.copy()

            ctr += 1
        else:
            df = scrapeInstagramStories(page_id=page, access_token=user_token,
                                        since_date=since_date, until_date=until_date)

            if df.empty:
                print("{0} is empty!".format(gshow_pages[page]))
                pass
            else:
                ndf = pd.concat([ndf, df], sort=False)

            ctr += 1

    ndf['timestamp'] = pd.to_datetime(ndf.timestamp, infer_datetime_format=True)
    ndf['timestamp'] = ndf.timestamp.dt.tz_localize('UTC')
    ndf['timestamp'] = ndf.timestamp.dt.tz_convert('America/Sao_Paulo')

    ndf.caption.fillna("None", inplace=True)
    ndf['completion_rate'] = 1 - (ndf.exits + ndf.taps_forward - ndf.taps_back) / (ndf.impressions)
    ndf.drop('data', axis=1, inplace=True)

    ndf['hashtag'] = ndf.caption.apply(lambda x: "#" + re.findall(r"#(\w+)", x)[0]
    if len(re.findall(r"#(\w+)", x)) > 0
    else "None")

    ndf['hashtag2'] = ndf.caption.apply(lambda x: "#" + re.findall(r"#(\w+)", x)[1]
    if len(re.findall(r"#(\w+)", x)) > 1
    else "None")

    pagen = {'bbb': 'Big Brother Brasil', 'gshow': 'GSHOW',
             'caldeiraodohuck': 'Caldeirão do Huck', 'oficialzorra': 'Zorra',
             'popstar': 'Popstar', 'thevoicebrasil': 'The Voice Brasil',
             'conversacombial': 'Conversa com Bial', 'malhacao': 'Malhação - Toda Forma de Amar'}

    ndf['produto'] = np.where(ndf.username == "gshow", ndf.hashtag.map(tags), np.nan)
    ndf['produto'] = np.where((ndf.username == "gshow") & (ndf.produto.isnull()),
                              ndf.hashtag2.map(tags), ndf.produto)

    ndf['produto'] = np.where((ndf.username != "gshow") & (ndf.produto.isnull()),
                              ndf.username.map(pagen), ndf.produto)

    ndf['produto'] = np.where(ndf.produto.isnull(), "GSHOW", ndf.produto)
    ndf.drop(['hashtag', 'hashtag2'], axis=1, inplace=True)

    ndf['caption'] = ndf.caption.astype('category')
    ndf['id'] = ndf.id.astype('category')
    ndf['media_type'] = ndf.media_type.astype('category')
    ndf['media_url'] = ndf.media_url.astype('category')
    ndf['permalink'] = ndf.permalink.astype('category')
    ndf['username'] = ndf.username.astype('category')
    ndf['produto'] = ndf.produto.astype('category')

    ndf = ndf[['timestamp', 'username', 'id', 'caption', 'permalink', 'media_type', 'impressions',
               'video_views', 'like_count', 'comments_count', 'saved', 'reach', 'interactions', 'produto']]

    ndf['timestamp'] = ndf.timestamp.apply(bq_date)
    ndf['timestamp'] = ndf.timestamp.astype("category")

    df = ndf.copy()

    for dtx in df[df.timestamp != today].timestamp.unique():
        print(dtx)

        s = io.StringIO()
        aux = df[df.timestamp == dtx].copy()
        aux.to_csv(s, sep=",", encoding="utf-8", index=False)

        response = upload_to_gcs('gdata-dn-gshow-sandbox',
                                 'AD/INS/instagram_stories_ad_{0}.csv'.format(dtx),
                                 s.getvalue())

        print("{0} - {1}".format(dtx, response), end="\r", flush=True)

ERRO ENCONTRADO
nsertId:  "000000-df33f5d7-a462-4357-bd60-15a52f1b66c5"    labels: {…}
  logName:
  "projects/gdata-dn-gshow-sandbox/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
  receiveTimestamp:  "2019-08-07T17:39:07.365346300Z"    resource: {…}
  severity:  "ERROR"    textPayload:  "Traceback (most recent call
  last):   File
  "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
  line 346, in run_http_function
      result = _function_handler.invoke_user_function(flask.request)   File
  "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
  line 217, in invoke_user_function
      return call_user_function(request_or_event)   File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
  line 210, in call_user_function
      return self._user_function(request_or_event)   File "/user_code/main.py", line 262, in st_scrapper
      ndf['media_url'] = ndf.media_url.astype('category')   File "/env/local/lib/python3.7/site-packages/pandas/core/generic.py", line
  5180, in getattr
      return object.getattribute(self, name) AttributeError: 'DataFrame' object has no attribute 'media_url' "    timestamp:
  "2019-08-07T17:39:01.147Z"    trace:
  "projects/gdata-dn-gshow-sandbox/traces/a1448d780d796c9f70f4903775329c7

7"


text:
Q: Solve $\int_{0}^{\infty} \frac{dx}{x^3(e^{1/x} - 1)}$ Solve that the following integral
$$ \int_{0}^{\infty} \frac{dx}{x^3(e^{1/x} - 1)}. $$
I just know this is $\pi^2/6$. I think it's related to $\zeta(2)$, but I cannot figure this integral out.

A: Sub $x=1/u$, $dx = -du/u^2$ to get
$$\int_0^{\infty}du \frac{u}{e^u-1} = \int_0^{\infty} du \frac{u \, e^{-u}}{1-e^{-u}}$$
Taylor expand the denominator, switch order of summation and integration:
$$\sum_{k=0}^{\infty} \int_0^{\infty} du \, u \, e^{-(k+1) u} = \sum_{k=0}^{\infty} \frac1{(k+1)^2} = \frac{\pi^2}{6}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Postgresql pg_profile getting error while creating snapshot I am referring https://github.com/zubkov-andrei/pg_profile for generating awr like report.
Steps which I have followed are as below :
1) Enabled below parameters inside postgresql.conf (located inside D:\Program Files\PostgreSQL\9.6\data)
track_activities = on
track_counts = on
track_io_timing = on
track_functions = on

shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.max = 1000
pg_stat_statements.track = 'top'
pg_stat_statements.save = off

pg_profile.topn = 20
pg_profile.retention = 7

2) Manually copied all the file beginning with pg_profile to D:\Program Files\PostgreSQL\9.6\share\extension
3) From pgAdmin4 console executed below commands successfully
CREATE EXTENSION dblink;
CREATE EXTENSION pg_stat_statements;
CREATE EXTENSION pg_profile;

4) To see which node is already present I executed SELECT * from node_show();
which resulted in
node_name as local
connstr as dbname=postgres port=5432
enabled as true

5) To create a snapshot I executed SELECT * from snapshot('local');
but getting below error
ERROR:  could not establish connection
DETAIL:  fe_sendauth: no password supplied

CONTEXT:  SQL statement "SELECT dblink_connect('node_connection',node_connstr)"
PL/pgSQL function snapshot(integer) line 38 at PERFORM
PL/pgSQL function snapshot(name) line 9 at RETURN
SQL state: 08001

Once I am able to generate multiple snapshot then I guess I should be able to generate report.

A: just use SELECT * from snapshot()
look at the code of the function. It calls the other one with node as parameter.


text:
Q: Subset of training set produces good results while full training set produces poor results I have an extremely unbalanced data set: around 200 positive samples and 70,000 negative samples. To overcome this problem I have tried to over-sample the minority class as suggested in previous questions here.
Since training the classifier (in my case I am using SVM) takes a long time on my computer I first trained a classifier on a small subset of my data picked randomly, the classifier gave solid results when tested on the test set, yet when I trained a classifier using the full training data the classifier produced very poor results. Does anyone have insight into why this is happening and what should i do? I have also tried using weights but it did not produce a different result.

A: You can try F1 score that is specifically designed for skewed classes. The idea is to measure both precision and recall, because usual error ratio doesn't work for skewed classes. E. g. in your case you could always predict "negative" and yet have 99.7% correct answers.
$$F_1 = 2\frac {precision * recall}{precision + recall}$$
More info on wiki: F1 score


text:
Q: jquery simple slider not working as meant too im new at javascript and i can get this slider to work but not exact to what i am after, what am i doing wrong?
Basically the slider is ment to fade in and out nicely, in mine it just shows up bluntly lol.
Here is the code
    $(function() {
    setInterval("rotateDiv()", 5000);
});

    function rotateDiv() {
    var currentDiv=$("#simlpeslider div.current");
    var nextDiv= currentDiv.next ();
    if (nextDiv.length ==0)
        nextDiv=$("#simlpeslider div:first");

    currentDiv.removeClass('current').addClass('previous');
    nextDiv.addClass('current').fadeIn('3000',function() {
        currentDiv.removeClass('previous').fadeOut('1000');});

}

The html is as follows:

Title 1

Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc, nec sagittis tellus. Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc

iusdhfisd sdf

Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc, nec sagittis tellus. Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc

eco sodalirity ltd

Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc, nec sagittis tellus. Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc

asd

Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc, nec sagittis tellus. Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc

ec234234234

Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc, nec sagittis tellus. Lorem ipsum dolor sit amet, consectetur elit. Maecenas non ipsum nunc

The css is:
    #simlpeslider{
    width:100%;
    float:left;
    height:150px;
    overflow:hidden;
}

#simlpeslider div {
    position:absolute;
    display:none;
    }

#simlpeslider div.previous {
    display:none;
    }
#simlpeslider div.current {
    display:block;
}
#simlpeslider div.normal {
    display:none;
}

Thanks

A: Simply, you need call fadeOut() before removing the class!
currentDiv.removeClass('previous').fadeOut('1000');

This will first remove your class "previous" from the element so that it will get back its default style inherited by the style for the id simpleslider (note your typo) which is display:none; so that fadeOut() will have no effect.
What you want is:
currentDiv.fadeOut('1000', function () {
   currentDiv.removeClass('previous');
});

Same goes for the fade-in. If you first add the class, which contains display:block; the element will turn visible immediately, with fadeIn having no effect.


text:
Q: Poi Formula evaluation I am facing difficulties while reading formula cell values with POI
I have created formula cell as follows:
cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula("SUM(D8..F8)");

And I am reading it as follow:
double formulaCellValue = row.getCell((short) 7).getNumericCellValue();

When read this way(using getNumericCellValue()), I am always getting the value of 0.0.
Any quick help in this regard would be highly appriciated.

A: After you're done setting all your formulas, you need to trigger a recalculation. See the why evaluate docs for the background on why you need to do it, and the Evaluation docs for details. Quick answer is you'd likely want to do something like:
HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);

Don't call it until you're done adding / editing all your cells though! You can also trigger the evaluation of just one cell, see the docs for details of the various options if you need full control.


text:
Q: How to construct makefile to compile AND run the binary? I would like to compile and run in one rule. Now I have :
CC = g++

%: %.o
    $(LINK.c) $^ -o $@;
    ./$@

But the make only compiles the source to binary, but do not run it. How to construct make to do this in one step?
Having file foo.cpp. Applying the makefile:
user@Host:~/Desktop/bin/2$ make foo
g++     foo.cpp   -o foo
user@Host:~/Desktop/bin/2$

Compilation is done. After which I want to run it (and see the output of that program), but that will not happen.
EDIT:
Please use patterns, I will not accept solution with explicit filenames.

A: I suspect you are being tripped up by the implicit rules in make. It already knows how to a) make an object file from a C++ source and b) how to link.
So I suggest to rewrite the Makefile to be more explicit.  One example would be
all:
    g++ -c hello.cpp
    g++ -o hello hello.o
    ./hello

where I redefine the default all target and (for simplicity) make the steps explicit.  With a trivial file such as this
#include <iostream>

int main() {
  std::cout << "Hello, world." << std::endl;
  exit(0);
}

it works as expected:
$ make
g++ -c hello.cpp
g++ -o hello hello.o
./hello
Hello, world.
$

You can refine and adapt as needed, i.e. with the $^ and $@ variables as needed.
Edit:  Here is a second variant. It does "nothing" as building a executable from (same-named) source file is known to make. So here I just do three things:

*

*establish the names of all sources

*derive the names of all programs from all sources

*tell the all target to run the programs one-by-one

The following (minimal) Makefile does that:
sources :=  $(wildcard *.cpp)
programs := $(sources:.cpp=)

all:    $(programs)
        ./$^

Works as expected:
$ ls -l
total 8
-rw-rw-r-- 1 edd edd 94 Nov 15 16:36 hello.cpp
-rw-rw-r-- 1 edd edd 88 Nov 15 17:13 Makefile
$ make
g++     hello.cpp   -o hello
./hello
Hello, world.
$

I actually use that very same pattern in an example directory with 18 or so example in this repo.
Edit 2:  The above actually run one command over all targets in programs; I copied it from strip invocation where that makes sense.  One may to have them all run after they have been built is to use this:
sources :=  $(wildcard *.cpp)
programs := $(sources:.cpp=)

all:    $(programs)
        for p in $(programs); do ./$$p; done


text:
Q: how to open an url and return data from there in odoo 10? I have developed simple custom odoo module. on button click action I wrote a simple method that should simply display data on the odoo screen. Module is getting installed successfully, but not performing required action so please help me. Thanks in advance.
my button code in header tags
*<header>
  <button name="get_data" type="object" string="Click" class="oe_highlight" />
</header>*

my python method inside model.py
*from odoo import models, fields, api
import requests
class gabzilAi(models.Model):
    _name = 'ai.gabzil'
    _description = 'Gabzil Odoo Module'
    fileName = fields.Text("File content")
    @api.one
    def get_data(self):
        myreq = requests.get("http://cake.gabzil.com/api/customers")
        textdata = myreq.text
        return textdata*

I am new to Odoo so not that much familiar with the things where i am making silly mistake...


text:
Q: Create button with dropdown menu in application toolbar of custom screen I'm trying to create a button in the application toolbar which when clicked displays a drop down menu. This is a custom screen with no ALV grid though so I can't use the ALV class methods. I create the button and fcode in my GUI status and set it when I call my custom screen but I can't find any way to turn it into a drop down menu. Is there any other way I can do it?
I thought I might be able to use the cl_gui_toolbar methods add_button and set_static_ctxmenu but I'm not sure how I'd get a reference to my running toolbar instance?
My code so far:
*----------------------------------------------------------------------*
*&     Form     f_handle_menu_button
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM f_handle_menu_button.

DATA: go_toolbar TYPE REF TO cl_gui_toolbar,
    go_menu    TYPE REF TO cl_ctmenu.

CALL METHOD go_toolbar->add_button
EXPORTING
  fcode       = '&APPLY'
  icon        = ''
  is_disabled = ''
  butn_type   = 1 "Pushbutton with Menu
  text        = 'Apply Status'.

CREATE OBJECT go_menu.

CALL METHOD go_menu->add_function
  EXPORTING
   fcode       = '&STATUS1'
   text        = 'Status1'
   icon        = ' '
   disabled    = ' '
   checked     = ' '
   hidden      = ' '.

CALL METHOD go_menu->add_function
  EXPORTING
   fcode       = '&STATUS2'
   text        = 'Status2'
   icon        = ' '
   disabled    = ' '
   checked     = ' '
   hidden      = ' '.

CALL METHOD go_toolbar->set_static_ctxmenu
  EXPORTING
   fcode   = '&APPLY'
   ctxmenu = go_menu.

ENDFORM.      "F_HANDLE_MENU_BUTTON

A: Triggering a modal dialog from the application toolbar is simpler to implement and fits established UI patterns, such as selecting an ALV layout or selecting a financial, material, or purchasing document in those respective modules.  And as you can see from the code, the signature of add_function is hardcoded to accept icons and text only.
As much as I would like to see this happen, I recommend using a modal dialog instead of a drop-down menu.


text:
Q: Regular expression test This regular expression in javascript
var foo = RegExp("^https?:\/\/(\w+\.)*youtube\.([a-zA-Z0-9])+");

will match strings like: [The below statements returns true]
foo.test("http://www.youtube.com");
foo.test("https://www.youtube.com");
foo.test("http://youtube.com");

But the same test fails if the expression is:
var foo_fail = RegExp("^https?:\/\/(\w+\.)*youtube\.\w+");

This RegExp should have passed the above tests but I see:
foo_fail.test("http://www.youtube.com"); returns false on chrome/firebug console. This should have returned true. What's wrong in this expression?
The similar expression if run on perl returns successful match which is expected.

A: You're missing a backslash before the w:
\.\w+

Further, for static regular expressions, never use the [new] RegExp() syntax, but rather regular expression literals:
var foo = /^https?:\/\/(\w+\.)*youtube\.\w+/;


text:
Q: How can consistent scaling of ∧, ∨, etc., be accomplished? I've added two examples of what the expressions I wish to reproduce look like:
Here ∧ serves both as a binary operator and as the universal quantifier.  I know there are ∀ and ∃, but I want to reproduce what is in the book.

In this image ∨ serves as the existential quantifier.

This is what Mathematica produces when I input the same expressions into an equation cell:

The same kind of thing happens with the set theoretical connectives ⋃ and ⋂, etc. It makes sense for some operator symbols to scale. For example, summation and integral symbols.  But for these operators, I want to control their appearance with a minimal number of keyboard or mouse actions. What I really want are upper case and lower case variants of these symbols which act in the same way as do letters and numerals regarding spanning.
Is there a way to accomplish something like this without impacting the behavior of other symbols that automatically scale? As it stands, the scaling of these symbols in complex expressions is arbitrary and inconsistent.  Exactly the same expression will often be scaled differently depending on the order in which it is typed.
I also want the formatting to persist when saving as PDF.
Cell[BoxData[
 FormBox[
  RowBox[{
   UnderscriptBox["\[Or]", "p"],
   UnderscriptBox["\[Or]", "q"],
   RowBox[{"(",
    RowBox[{"2", "\[InvisibleComma]",
     RowBox[{
      SuperscriptBox["q", "2"], "=",
      RowBox[{
       SuperscriptBox["p", "2"], "\[And]",
       RowBox[{"\[Not]",
        RowBox[{"(",
         RowBox[{
          RowBox[{
           UnderscriptBox["\[Or]", "s"],
           RowBox[{"2", "s"}]}], "=",
          RowBox[{
           RowBox[{
            RowBox[{"p", "\[And]"}],
            UnderscriptBox["\[Or]", "s"],
            RowBox[{"2", "s"}]}], "=", "q"}]}], ")"}]}]}]}]}], ")"}]}], TraditionalForm]], "Equation",
 CellChangeTimes->{{3.755520330280187*^9, 3.755520443924959*^9}, {3.757609467459089*^9, 3.757609620292385*^9}}]


text:
Q: No instala el apk en Android studio Al darle en run app en android studio para probar la app en mi dispositivo físico no termina de instalar el apk, no sube la barra de carga y el spinner no para de girar. Antes si lo hacia, ¿Alguien sabe a que puede ser debido? Ya que no he tocado ni cambiado nada, además que la app si se visualiza en el dispositivo, aunque en Android studio pase lo comentado anteriormente. Gracias.

A: Tienes activado Instant run? A mi a veces me da problemas y al desactivarlo suele funcionar todo. Puedes comprobarlo en File->Settings->Build, Execution, Deployment

A: comentas que si muestra la aplicación pero la barra de progreso no sube.
Puede ser que el .apk generado lo suba ya que no detecto cambio en el código.
si deshabilitaste la opción Instant Run , File >Settings > Build, Execution, Deployment.
reconstruye el proyecto mediante: Build > Clean project > Build Project
esto obligara a subir una nueva versión del .apk

Algo pudiera esta fallando probablemente con el cable de tu dispositivo pero pudiera ser el ADB, puedes probar reiniciando Android Studio, o directamente en este Tools > Android > Android Device Monitor. Selecciona la opción que muestro en la imagen para resetear el ADB (Android Debug Bridge):


text:
Q: Deploy Error: Failed to configure trigger GCS Bucket: undefined I am an iOS developer and I've started to develop my apps with Firebase. Recently firebase received new feature, cloud functions.
I want to create my first cloud function which generates thumbnail from uploaded photo to storage. I copied sample code from here.
So my index.js looks like this:
const functions = require('firebase-functions');
const mkdirp = require('mkdirp-promise');
const admin = require('firebase-admin');
const gcs = require('@google-cloud/storage')();
const spawn = require('child-process-promise').spawn;
const _ = require('lodash');
const LOCAL_TMP_FOLDER = '/tmp/';

// Max height and width of the thumbnail in pixels.
const THUMB_MAX_HEIGHT = 200;
const THUMB_MAX_WIDTH = 200;
// Thumbnail prefix added to file names.
const THUMB_PREFIX = 'thumb_';

admin.initializeApp(functions.config().firebase);

exports.generateThumbnail = functions.storage.object().onChange(event => {
  const filePath = event.data.name;
  const filePathSplit = filePath.split('/');
  const fileName = filePathSplit.pop();
  const fileDir = filePathSplit.join('/') + (filePathSplit.length > 0 ? '/' : '');
  const thumbFilePath = `${fileDir}${THUMB_PREFIX}${fileName}`;
  const tempLocalDir = `${LOCAL_TMP_FOLDER}${fileDir}`;
  const tempLocalFile = `${tempLocalDir}${fileName}`;
  const tempLocalThumbFile = `${LOCAL_TMP_FOLDER}${thumbFilePath}`;

    // Exit if this is triggered on a file that is not an image.
  if (!event.data.contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return;
  }

    // Exit if the image is already a thumbnail.
  if (fileName.startsWith(THUMB_PREFIX)) {
    console.log('Already a Thumbnail.');
    return;
  }

    // Create the temp directory where the storage file will be downloaded.
  return mkdirp(tempLocalDir).then(() => {
    // Download file from bucket.
    const bucket = gcs.bucket(event.data.bucket);
    return bucket.file(filePath).download({
      destination: tempLocalFile
    }).then(() => {
      console.log('The file has been downloaded to', tempLocalFile);
      // Generate a thumbnail using ImageMagick.
      return spawn('convert', [tempLocalFile, '-thumbnail', `${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}>`, tempLocalThumbFile]).then(() => {
        console.log('Thumbnail created at', tempLocalThumbFile);
        // Uploading the Thumbnail.
        return bucket.upload(tempLocalThumbFile, {
          destination: thumbFilePath
        }).then(() => {
          console.log('Thumbnail uploaded to Storage at', thumbFilePath);
        });
      });
    });
  });
});

My package.json:
{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {
    "@google-cloud/storage": "^0.8.0",
    "child-process-promise": "^2.2.0",
    "firebase-admin": "^4.1.2",
    "firebase-functions": "^0.5.1",
    "lodash": "^4.17.4",
    "mkdirp": "^0.5.1",
    "mkdirp-promise": "^4.0.0"
  },
  "private": true
}

And after firebase deploy --only functions I got this:
i  deploying functions
i  functions: ensuring necessary APIs are enabled...
i  runtimeconfig: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
✔  runtimeconfig: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (2.64 KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
⚠  functions[generateThumbnail]: Deploy Error: Failed to configure trigger GCS           Bucket: undefined

What am I doing wrong?
PS.
Im JS newbie. Maybe this problem is trivial. :?


text:
Q: Add to Array of wildcards in Powershell I am new to powershell and looking to test something for a POC.
There are multiple files stored on the cloud inbox (File_1.txt, File_2.txt and so on).
I want to add these files using a wildcard to an array and then run some commands (specific to the cloud) for each file.
I cannot specify the -Path in the code as the files are located on cloud and I do not have the path.
The below code works:
 $files = @("File_1.txt","File_2.txt","File_3.txt")
 foreach ($file in $files) {
   Run commands on cloud like...delete inbox/$file
 }

However I cannot hard code the file names. I am looking to add file names using wildcard.
  $files=@("File*.txt")
   foreach ($file in $files) {
     Run commands on cloud like...inbox/$file
   }

But this does not work as in the log it is taking File*.txt as the name of the file.
Thanks in advance

A: You should use dir equivalent of PowerShell, Get-ChildItem (In fact dir and ls are aliases for the Cmdlet) to search files using wildcards:
$files = Get-ChildItem file*.txt
foreach($file in $files) {
    DoSomeStuffWithFile $file
}

Get-ChildItem returns FileInfo objects. If you want to use the filename String in the loop, you should refer to the Name property of the object:
DoSomeStuffWithFileName $file.Name

A: You can easily update the file number using string interpolation.  Here is a basic example of how this might work:
1 .. 10 |
    ForEach-Object {
        "hello" | Out-File -Path "File_$_.txt"
    }

Here we generate an array of the numbers from 1 to 10 (using the range operator ..), then this is piped to our command (and hence placed in the $_ variable).  As each number comes through, the path is constructed with the current value of $_, so you get File_1.txt, File_2.txt, etc.
You can use other looping techniques, but the key is that you can build the filename/path on-the-fly by having PowerShell replace the variables for you.


text:
Q: Can you push codes from one branch to another, a different downstream to a different upstream I am working on a different branch in my local machine, but I want to push the codes to a different branch upstream. How can this be done. I am trying to push to nicholas-dev
This is the error message I am getting
C:\Users\njoca\Documents\BoTest\boegisexternal (dev-samuel -> origin)
λ git push nicholas-dev
fatal: 'nicholas-dev' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

A: You need to use:
git push origin dev-samuel:nicholas-dev

where origin is the name of the remote, dev-samuel the name of the local branch, and nicholas-dev the name of the branch on the remote.


text:
Q: How do I load an image stored as a string into a numpy array? There are several examples of loading an image file into a numpy array, but I do not have an image in a file on the local file system. Instead, I have a string variable img that contains the data that makes up an image. For example:
# Currently here:
with open("imageFile.png") as f:
    img = f.read()

# Would like to accomplish this:
npArray = loadStringToArray(img)

Writing this file back to the disk and calling one of the more common load functions seems impractical, so how do I "load" this image-as-a-string into a numpy array?
A bit of background - in my application, this image-as-a-string is delivered from a client via python sockets. The image isn't on the local machine; the example above is just that - an example. While writing the file to the local file system and then reading it back in is possible,
I'd like to avoid doing that if I can.

A: I think what you want to do is to convert the string into a numpy array as you already have the image as a string.
You can use numpy.fromstring() for that task.
Examples:-
np.fromstring('\x01\x02', dtype=np.uint8) -----> array([1, 2], dtype=uint8)
np.fromstring('1 2', dtype=int, sep=' ') -----> array([1, 2])
np.fromstring('1, 2', dtype=int, sep=',') -----> array([1, 2])
np.fromstring('\x01\x02\x03\x04\x05', dtype=np.uint8, count=3) -----> array([1, 2, 3], dtype=uint8)

A: Without going into too much detail the io module provides "file-like" objects, in particular StringIO and BytesIO that equip in-memory objects such as strings with a file-like interface. Many functions that expect a file argument will happily accept a StringIO or BytesIO instead.


text:
Q: remove part of jQuery base uri when changing src of an img tag In a multilanguage website when changing the img.src attribute in jQuery, it looks for base url + src which becomes something like http://localhost/app/en/resources/images/img.jpg assuming base url is http://localhost/app/en/ and src is resources/images/img.jpg
In fact the img.jpg file is not under en folder so this should be omitted from the above location. How can I do this?

A: You have two options:

*

*Give the absolute URL: http://www.google.com/...../image.png

*Give relative URL, two folders up: ../../image.png


text:
Q: Writing a Custom Hive Provider using objects as datasource Im trying to create a hive provider that would be able to work towards some objects.
An object may look something like this
public class MyContent
{
    public System.Collections.Generic.List Content { get; set; }
}

public class ContentExample
{
    public string Title { get; set; }
    public string Text { get; set; }
}

public class MyFiles
{
    public System.Collections.Generic.List Files { get; set; }
}

public class FileExample
{
    public System.IO.FileInfo File { get; set; }
}

I've downloaded and checked the two Hive providers from the Visual Studio Gallery (Umbraco 5 Hive Provider and Umbraco 5 Simple Hive Provider), but the lack of documentation is a bit disturbing. I also downloaded some of the other example hives, like the Wordpress hive provider, but that one is rather different from the ones in the Visual Studio Gallery.
The Idea
Im used to working with stuff like ObjectDataSource, the example above could be complemented with full CRUD if required.
Now, I assume one Hive provider would be able to serve different parts of Umbraco with content (right?). Just set up a new Repository and go? I have now clue how to connect all parts or even how to get the data into the provider yet.
Any help in how I could bring all pieces together?
Thanks

A: The first step is to take a step back and evaluate your business requirements. Will you allow for users to be updating the information with forms in the frontend? Do you need a tree editor for the content in the backoffice? Do you need to be work with data outside of the built-in ORM?
If the answer to these is no, a hive provider is overkill. Evaluate solutions using either a simple surface controllers, or just a custom document type. Umbraco 5 is a full EAV/CR system, so unlike some CMS products, you'll be able to represent any rdbs structure you can imagine
ContentExample could be represented be a document type called 'Article', which has properties Title and Text. Just by defining this document type we're instantly given add and edit forms for our back office users in our content section. We can even restrict which nodes are able to have children of type 'Article', e.g News.
In the same way, an upload control is a field type that allows you to attach files to your document.
So what's point of a custom hive provider?
The goal of a custom hive provider is to unify CRUD actions for data access layers.
As a result data can be stored in the baked-in nhibernate orm, custom tables, rss feeds, or even flat files, while still using a common interface to retrieve and update it. If this sounds like what you're aiming for, read on.
Going back to the business requirements, specifically, where do you want to actually store the data?--Given that you have some fields and properties related to flat file storage, let's say that one TypedEntity (a model) is equivelant to one file and write some pseduocode:
The first step, is as you say 'get the data into the repository.' This involves going back to that VS template and filling in the 'not implemented' methods with your logic for storing and retrieving data.
    protected override void PerformAddOrUpdate(TypedEntity entity)
    {
        // step 1: serialize the typed entity to xml
        // step 2: write the file to the hdd, making sure that the file name is named using the                 hive id so that we can pull it back later.
    }

Once you've written the data access layer, or DAL, you can hook it up in the hive config, giving it url to match. e.g. rather than matching content:\\, yours might match on file-manager:\\
We can allow our backoffice users to be able to add new entities (indirectly, new files) by writing a custom tree, and we can display the results to our front-end users via macros.


text:
Q: How do you create a function progress bar in react? I have a button in react that when I press it, it simulates an inputted number of roulette games. This is to see how much you can expect to make back from roulette bonuses offered by casinos. Anyway, when the number of simulations is set to a large number like 1000000 simulations, it takes 10+ seconds to complete and display the results. I want to add a progress bar, so for every 1% of the simulations that are completed the progress bar updates to be another 1% completed. This will give the user a better idea of how long the simulation will take, as well as let them know there computer hasn't crashed.
Here is the roulette function, in case you need it...
const SimulateEuroRoulette = (starting_balance, wagering, bet_size, simulations) => {
    let results = []
    for(let i = 0; i < simulations; i++){
        let balance = starting_balance
        let wagering_complete = 0
        let bust_out = false

        while(bet_size <= balance && wagering_complete < wagering){
            const random_int = random.int(0, 36)
            balance -= bet_size
            if(random_int > 18){
                balance += bet_size * 2
            }

            wagering_complete += bet_size
        }

        if(balance < bet_size && wagering > wagering_complete){ bust_out = true }

        results.push({ balance, wagering_complete, bust_out })
    }

    let bust_out_count = 0
    let balance_total = 0
    let wagering_total = 0
    let simulated = 0
    for(let i = 0; i < simulations; i++){
        if(results[i].bust_out){ bust_out_count++ }
        if(!results[i].bust_out){
            balance_total += results[i].balance
        }
        wagering_total += results[i].wagering_complete
        simulated++
    }

    return { ev: balance_total / simulations, average_wagered: wagering_total / simulations, bust_out_rate: ((bust_out_count / simulations) * 100), simulated }
}

A: You would need to refactor your function, so that it updated state variables as it iterates (probably using useReducer, as you want to update multiple state variables simultaneously). One of your variables would be the percentage of simulations completed. This would be the variable that you would then tie to the value of your progress bar.
<label for="progress">progress:</label>
<progress id="progress" value={state.progress} max="100"> {state.progress}% </progress>

In your reducer, you probably want logic to only update progress when your percentage is a whole number or put in rounding. Don't make your SimulateEuroRoulette method reliant on state, just have it dispatch your state updates needed. You probably want the function definition to be outside of your component, so you'll need to pass in dispatch to call it.


text:
Q: Invariant Violation Invalid hook call / cross-origin error So after making this function work I started to create a loop that would give me feedback from the backend after SSR, I wanted to use hooks so I made it a functional component and started to write but the hook (even with nothing in it) is throwing 2 errors. Invalid Hook Call and A cross origin error was thrown.
I tried changing the file name to jsx, moving the file out of the folder I had because there was a second node modules in there (I thought it was using two versions of React), I also read somewhere just to clear local storage and it was just a in development using localhost problem.
*Edit So i've found that its not even calling the fn: reactToPdfUtils.savePDFNOW(sourceElement, true, undefined, cb) its stopping here

//reactToPdf.js

import React, {useEffect} from 'react';
import { savePDF } from '@progress/kendo-react-pdf';
import { drawDOM, exportPDF } from '@progress/kendo-drawing';
var ClassInstancesStore = require('../libs/goggles/reflux/classInstances-store');
var ClassInstancesActions = require('../libs/goggles/reflux/classInstances-actions');

export const savePDFNOW = (sourceElement, willSaveToDB, pageTemplate, cb) => {
    //this hook broke the program as soon as i put it in even with nothing inside
    useEffect(() => {
        //Functionthat gets called after sending the pdf to the backend
        // function onClassInstancesStoreChange(opInfo){
        //     var e = cloneDeep(opInfo);
        //     if (e.op === 'Call::StorePassportPDFToDisk') {
        //         if(e.error){
        //             console.log(e.ret)
        //             setPdf({ pdfErrors: e.ret })
        //         } else {
        //             console.log(e.ret)
        //             setPdf({ inProgress: true })
        //             alert('Successfully created: ' + e.ret.fileName)
        //             // onSubmit()
        //         }
        //     }
        // };
        // let listeners = [];
        // listeners.push(ClassInstancesStore.listen(onClassInstancesStoreChange));

        // return function cleanup() {
        //     _.each(listeners, function(listener) {listener();}); //NOTE: destroy listeners
        // }

    }, [])

    try {
      //do all the my functions that make my pdf perfect
    } catch (error) {
        //snap something went wrong all my awesome error handling
    }
};

//previewer.jsx
var React = require('react');
var _ = require('underscore');
var reactToPdfUtils = require('../../../../../components/reactToPdf.js');

    handleSave = (sourceElement) => {
        reactToPdfUtils.savePDFNOW(sourceElement, true, undefined, cb)
        function cb(sendDataContent){
            if(sendDataContent.err){
                console.log(sendDataContent.message)
            } else {
                console.log('sucess')
            }
        }
    };

A: My understanding of the code is that the function handleSave will call the external hook savePDFNOW. If this is what happens, then this will break regardless of the useEffect logic.
The reason for that is that hooks that are extracted outside of the component require their name to start with use
So to allow the hook to run you change its name to useSavePDFNOW.
That being said, I believe this is not a valid use case for useEffect, think of useEffect as componentDidMount/Update. This is relevant to component render cycle rather than event listeners. It makes more sense to do away with the useEffect and keep it a regular function.
A few more things, if you are using the latest react version you don't need to import react. Also it's recommended to use const/let instead of var as well.


text:
Q: using .find() method to find productId as a parameter base on the productId click Right now, am getting the productId at match.params.id but when I used the find method to compare the item.id and match.params.id it return product not found....below is the code
const DetailsPage = (props) => {
    console.log(props.match.params.id)
    const product = data.products.find((item) => item.id === props.match.params.id)
    console.log(product);
    if (!product) {
        return (

Product Not Found

        )
    }
    return (

            DetailsPage
                {product.name}

    )

As you can see I console.log(props.match.params.id) which gave me the product parameterId but nothing exist in my declaration of the function

A: This is because id retrieved from the route will be of type string. Since you are doing === strict equals find will fail .
You can type cast your params.id to Number.
const product = data.products.find((item) => item.id === Number(props.match.params.id))

Also react-router now provides a useParams hook to retrieve the params .
let { id } = useParams();


text:
Q: getting error in android i have parsed data successfully using sax parser and output is coming properly in logcat but i have to arrange that data systematically. But the problem is my question length and index is 2 so options are also coming 2. instead they are 4 for each question. please suggest
code snippet is
for (int i = 0; i < categorylist.getTitle().size(); i++) {

            TableRow tr = new TableRow(this);
            tr.setPadding(2, 2, 2, 2);

            TableLayout.LayoutParams tableRowParams=
                  new TableLayout.LayoutParams
                  (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.FILL_PARENT);

            int leftMargin=0;
            int topMargin=2;
            int rightMargin=0;
            int bottomMargin=1;

            tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

            tr.setLayoutParams(tableRowParams);

            name[i]= new TextView(this);
            name[i].setText(categorylist.getTitle().get(i));
            name[i].setTextColor(Color.WHITE);
            name[i].setTextSize(12);
            name[i].setPadding(10,0,0,0);
            name[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
            tr.addView(name[i]);
            t1.addView(tr, tableRowParams);

            LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                    RadioGroup.LayoutParams.WRAP_CONTENT,
                    RadioGroup.LayoutParams.WRAP_CONTENT);

            rad1[i]= new RadioButton(this);
            rad1[i].setText(categorylist.getValue().get(i));
            rad1[i].setTextColor(Color.WHITE);
            rad1[i].setTextSize(12);
            rad1[i].setPadding(10,0,0,0);
            rad1[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
            rgrp.addView(rad1[i], 0, layoutParams);

        }

and xml is
<Values>
<Question>

<Description><![CDATA[Some Question]]></Description>

                    <Options>

                        <option value="correct"><![CDATA[All of these]]></option>

                        <option value="incorrect"><![CDATA[Ok]]></option>

                        <option value="incorrect"><![CDATA[Fine]]></option>

                        <option value="incorrect"><![CDATA[Good one]]></option>

                    </Options>

            </Question>

</Values>

logcat output is:
05-14 15:22:27.228: INFO/This is the title:(559): Which of the following are called celestial bodies?
05-14 15:22:27.248: INFO/This is the option:(559): All of these
05-14 15:22:27.248: INFO/This is the option:(559): Sun
05-14 15:22:27.248: INFO/This is the option:(559): Planets
05-14 15:22:27.248: INFO/This is the option:(559): Moon
05-14 15:22:27.258: INFO/This is the title:(559): In our solar system, _________ planets revolve around the Sun.
05-14 15:22:27.258: INFO/This is the option:(559): eight
05-14 15:22:27.258: INFO/This is the option:(559): five
05-14 15:22:27.258: INFO/This is the option:(559): ten
05-14 15:22:27.258: INFO/This is the option:(559): nine

A: I think You should have two loop for example
int l;
    for (int i = 0; i < categorylist.getTitle().size(); i++){
    for(int j= 0; j < optionlist.size()/categorylist.getTitle().size(); j++){
    //add option to question
l=l++;
//use l;
    }
    }


text:
Q: Python + Selenium: How to find elements by using contains(text(),'') if some words contains space and some words not I have a page like below:
Apple
Apple
Apple
Apple

I use this code to find out all elements that contains Apple:
driver.find_elements_by_xpath('//*td[contains(text(),"Apple")]')
but sometimes the page will change to below:
Apple
Apple
   Apple
  Apple

So, How to find out all elements that contain Apple (even if the word have spaces).

A: Contains function in XPath is used when there is partial attributes value of an element to be match.
Exa.
 Hello ! Welcome to Stackoverflow.
driver.find_elements_by_xpath('//td[contains(text(),"Welcome")]')

By referring 'Welcome' keyword, We can achieve target element with the
  help of contains keyword.

So your xpath should work as expected.
driver.find_elements_by_xpath('//*td[contains(text(),"Apple")]')


text:
Q: Access an AD attribute in a first-time logon scenario? I have been tasked with improving our current image deployment. Right now we do a fair amount of manual setup after imaging to reduce the work for users who get a newly imaged machine. I would like to automate this as much as possible. We have a lot of short-time volunteers and interns so time-savings here will add up quickly.
One task is setting up the default save locations in Word and Excel. Some users have the User HomeDrive environment variable set, but not all (and none of the short time students). All users have the UserSharedFolder ActiveDirectory attribute set. This is not saved as an environment variable. Ideally the default save location would be set to the value of this AD attribute. It is different for each user.
Any suggestions on how to manage this?
I determined that the Default Save location is in the registry. I would like to use Group Policy Preferences to set it, but I can't access an Active Directory attribute from GPP.
How would I access this in a script? It will need to run in the user's context. I won't have access to the Powershell ActiveDirectory module on most machines.
Is there an alternate way to do this that makes more sense?

A: In Group Policy Preferences, you can do an LDAP Query in the Item Level Targeting and store the result in an Environment variable.  That Environment variable can be referenced by a Registry Preference item.  (Or referenced by a script that runs later, e.g. a user logon script).
To set the Environment variable using Group Policy:

*

*Edit the GPO (or create a new one)

*Go to User Config -> Preferences -> Windows Settings -> Environment

*Create a new Environment variable

*Name = MYSAVELOCATION

*Value = %_MYSAVELOCATION%

*In this case, it should be a User Variable

*Under Common, check Item-level Targeting

*Click Targeting...

*New Item -> LDAP Query

*Filter = (&(objectClass=user)(sAMAccountName=%USERNAME%))

*Binding = LDAP:

*Attribute = userSharedFolder (I think this is the AD attribute you want.  Double-check it!)

*Environment variable name = _MYSAVELOCATION

*Click OK

You can then create a Registry Group Policy Preference item that references %MYSAVELOCATION%.  You could also reference the environment variable in a batch file or script that runs after the GPO has applied.
If you wanted to do the equivalent thing in PowerShell, you could do this (e.g. in a user logon script).  This has no dependency on the PowerShell AD modules:
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry
$searcher.Filter = "(&(objectClass=user)(sAMAccountName=$env:USERNAME))"
$searcher.SearchScope = "Subtree"

# I am assuming userShareFolder is the AD attribute you want
# Double-check that and update this lin accordingly.
$searcher.PropertiesToLoad.Add("userSharedFolder") | Out-Null

$result = $searcher.FindOne()

# All of $result.Properties must be lower-case!
$user_shared_folder = $result.Properties.usersharedfolder

Write-Output "User Shared Folder = $user_shared_folder"

# Update the Environment Variables (two-step process)
# Call SetEnvironmentVariable to make the change persistent.
# Update $env:variable so the change affects the current process.
[Environment]::SetEnvironmentVariable("MYSAVELOCATION", $user_shared_folder, "User")
$env:MYSAVELOCATION = $user_shared_folder

From there, it is in an environment variable just like Group Policy Preferences.  You could also just take the value of $user_shared_folder and write it directly to the registry with Set-ItemProperty, no environment variable needed.  However, keeping it in an environment variable can be handy if you have a script or application which may need to reference it later.
For reference, I use the techniques described above to get Full Name and E-Mail address out of Active Directory and use them for application setup (e.g. personalizing Office).  You can also do a similar query with WMI to get the computer model and serial number.


text:
Q: AIX 7.1 Create another user with equal privileges as root and then disable root user I've got a weird, stupid question. I've used linux for a long time, but I know AIX is different in certain places, so my question is if I wanted to disable the root user at least from remote login I could, but can I create another user with equal privileges to use instead of root?
Thanks,
Corey

A: As with any other UNIX you can edit /etc/passwd and change the UID and GID of any other user to 0. This de facto creates a second root user. Depending on your remote access method you can then disable root login by explicitly prohibiting the "root" user, do not block all root users with some global method.
But seriously, use sudo. AIX knows that also.


text:
Q: Rounding off a float value without decimal points in python 2 Problem is to round-off the resulting value without any decimals after summation of percentage values using Python 2. provided 3 inputs
Input 1 (meal cost) : 10.25
Input 2 (tip  percentage) : 17
Input 3 (tax percentage) : 5
I have to calculate tip amount and tax amount and added the result with meal cost.
I tried below code:
def solve(meal_cost, tip_percent, tax_percent):
 tip_amt = (meal_cost * tip_percent)/100
 tax_amt =(meal_cost * tax_percent)/100
 total_bill = (meal_cost + tip_amt + tax_amt)
 print int (total_bill)

if name == 'main':
meal_cost = float(raw_input())

tip_percent = int(raw_input())

tax_percent = int(raw_input())

solve(meal_cost, tip_percent, tax_percent)

Right answer is 13. But above code gives 12.
Please guide me to get the expected result with solution.
Thanks in Advance

A: you should be using round off.
tip_amt = meal_cost * tip_percent/100
tax_amt =meal_cost * tax_percent/100
total_bill = meal_cost + tip_amt + tax_amt
print round(total_bill)

A: Converting the rounded-off sum value to integer gives expected value without decimals.
def solve(meal_cost, tip_percent, tax_percent):
     tip_amt = (meal_cost * tip_percent)/100
     tax_amt =(meal_cost * tax_percent)/100
     total_bill = (meal_cost + tip_amt + tax_amt)
     round_total = round(total_bill)
     return int(round_total)


text:
Q: rhythmbox-metadata uses 100% cpu Everytime I start rhythm box the process rhythmbox-metadata starts up and uses 100% cpu on one core, causing the computer to heat up and the fans to start rotating hard.  I have an external drive with about 450GB of music. rhythmbox-metadata will remain active at 100% cpu for an hour and then stop consuming cpu. This happens everytime I open rhythm box even if nothing changed in the music folder.
How can I stop this behaviour ?

A: I had to deselect "Watch my library for new files" in Edit/Preferences to prevent rythmbox from using 100% cpu.


text:
Q: TypeError: Function.prototype.apply was called on #, which is a object and not a function I was working on a heist command for my bot but wehn i try it i get this error
(node:2253) UnhandledPromiseRejectionWarning: TypeError: Function.prototype.apply was called on #<Object>, which is a object and not a function
My code is this and I dont know where it is coming from I wanted to make a heist command for my boy like dank memer.
const Discord = require('discord.js');
const db = require('quick.db')

module.exports.run = async (bot, message, args) => {
let member = message.mentions.members.first()
if (!member) return message.reply(`You you wanna hiest`)

let user = message.author;

let money = await db.fetch(`mon_${user.id}`)
if(money < 2000) return message.reply(`You need atleast 2000 coins to try and rob someone!`)

let money2 = await db.fetch(`b_${member.id}`)
if (money2 < 3000) return message.reply(`This fella does not have atleast 3000 coins in his bank not worth it!`)

message.channel.send(`${user.username} Is Starting a heist on ${member}\nType \`GG JOIN\` To join them!`).then(() => {
 message.channel.awaitMessages({ max: 7, time: 70000, errors: ['time'] })
    .then(message => {
       message = message.first()
       if (message.content.toUpperCase() == 'GG JOIN' || message.content.toUpperCase() == 'JOIN HEIST') {
         message.react("")
         db.fetch(`heistname_${message.guild.id}`)
         db.push(`heistname_${message.guild.id}`, -user.username)
         db.fetch(`heist_${message.guild.id}`)
         db.push(`heist_${message.guild.id}`, -user.id)
         db.fetch(`heistmem_${message.guild.id}`)
         db.add(`heistmem_${message.guild.id}`, 1)
       } else {
         return;
       }
     })
     .catch(collected => {
         message.channel.send('Allirght These Many Users Are joining the hesit.The Result will be given shortly!');
     });
 })
 setTimeout( async function() {
 let memjoined = await db.fetch(`heistmem_${message.guild.id}`)
let userbank = await db.fetch(`b_${member.id}`)
let bankdev = (userbank / memjoined)
let joined = await db.fetch(`heist_${message.guild.id}`)
let join2 = joined.split('-')
let jointot = join2.join('\n')
let joinname = await db.fetch(`heistname_${message.guild.id}`)
let joinnamesp = joinname.split('-')
let joinnametot = joinnamesp.join('\n')
db.add(`mon_${join2[0]}`, bankdev)
db.add(`mon_${join2[1]}`, bankdev)
db.add(`mon_${join2[2]}`, bankdev)
db.add(`mon_${join2[3]}`, bankdev)
db.add(`mon_${join2[4]}`, bankdev)
db.add(`mon_${join2[5]}`, bankdev)
db.add(`mon_${join2[6]}`, bankdev)
message.channel.send(`\`\`\`${joinnametot}Joined the heist and everyone came out with a total of ${bankdev} Money!\`\`\``)
}, 100000);

 setTimeout( async function(){
await db.delete(`heistmem_${message.guild.id}`)
await db.delete(`heistname_${message.guild.id}`)
await db.delete(`heist_${message.guild.id}`)
}, 10000);
}
module.exports.help = {
name: "bankrob",
aliases: ["heist"]
}

A: The first parameter of TextChannel#awaitMessages should be a filter function, not an object. This filter function accesses the incoming message as a parameter, and decides whether to let it pass. A common use of this function is making sure the message author is the author of the original command:
message.channel.awaitMessages(
  (m) => m.author.id === message.author.id,
  { /* options */ }
)

If you don't need any filter, you can just use () => true.


text:
Q: qooxdoo qx.data.Array replace Is there a way to replace a qx.data.Array?  I see methods for a whole lot of other options in the API but not that. I know I can do a removeAll() and then append new items, but that fires some events in my controller that I wish wouldn't fire. Thanks!

A: Check out the splice method which will work out fine. You can delete the whole content of the array and append new items in one call.


text:
Q: I need a little suggetion in ov7670+arduino+ethernet shield I am doing a project using Arduino Uno + Ethernet Shield + OV7670 camera(16 pins). I have solved the part with ethernet shield but I am quite confused about the camera part. How do I exactly connect the camera with the ethernet shield. I have the camera only. nothing with it. Can anyone help me to find a way out?

A: You will need some duponts. (or cables)DUPONTS and also breadboard BREADBOARD


text:
Q: ValueError : Random forest classification by scikit learn I am solving a classification problem using Random Forests. I transformed a sentence to num by BOW. And I put a label into it, and built a tree.
data_train = [[1.0, 1.0], [2.0, 2.0]]

label_train = [1,2]

estimator = RandomForestClassifier()

estimator.fit_transform(data_train, label_train)

and I prepared a test_data which was a sentence to try prediction. But it didn't work.
test_data = [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]]

label_predict = estimator.predict_proba(test_data)

ValueError: Number of features of the model must match the input. Model n_features is 2 and input n_features is 12

I know it says the number of element doesn't match. But the number of words in the sentence is different, it must be different, I think. How should I solve this?

A: In your example your train data has two features/dimensions/columns (the number of rows is irrelevant for this issue):
[[1.0, 1.0],
 [2.0, 2.0]]

and you have a label for each of the rows/samples.
[1,
 2]

Your test data has to look similar, i.e, it must have the same number of features/dimension/columns. For example this would be ok:
[[1.0, 1.0],
 [1.0, 1.0],
 [1.0, 1.0],
 [1.0, 1.0],
 [1.0, 1.0],
 [1.0, 1.0]]

You can have different number of rows but the number of columns has to be the same. In this case you have 2 columns and 6 rows, so you will get 6 labels as a result of predict_proba.


text:
Q: Linear Differential Equation using Reduction of Order I have this differential equation : $$4x^{2}y''+8x^{3}y'+(4x^{2}-3)y = 0$$ and it is given that the equation has a solution $$y_{1}(x)=x^{r}.$$
I set $y_2$ as $$ y_{2}=x^{r}v(x).$$
When I'm trying to find the first and second derivative I start to fail.
I get $$ y'_2=x^{r-1}(xv'+rv)$$ but the second is always long and makes no sense when I keep on with the problem. After I have put derivatives for the $y$, $y'$ and $y''$ in the original equation I get complex equations where i see no way to use reduction of order.
Can someone please help me and tell me what I'm doing wrong.

A: Let's assume that we have the following equation: $y''+a(x)y'+b(x)y=0$.
If we know that $y_1(x)$ is a solution and we search our general solution in the form of $y_2(x)=y_1(x)v(x)$, then we get the following:
$y'_2=y'_1v+y_1v'$ and  $y''_2=y''_1v+y'_1v'+y'_1v'+y_1v''=y_1''v+2y'_1v'+y_1v''$
Then by putting those values in the equation, we get
$y''_1v+2y'_1v'+y_1v''+a(x)(y'_1v+y_1v')+b(x)y_1v=0$
or
$(y''_1+a(x)y'_1+b(x))v+(2y'_1+a(x)y_1)v'+y_1v''=0$
As we know that $y_1$ is a solution therefore we have that
$y''_1+a(x)y'_1+b(x)=0$
So from our equation we get
$(2y'_1+a(x)y_1)v'+y_1v''=0$
$v''+(2y'_1/y_1+a(x))v'=0$
which is already order reducible.
Now, in our example by putting $y=x^r$ in the equation we get
$4r(r-1)x^r+8rx^{r+2}+4x^{r+2}-3x^r=0$ from where we get $r=-1/2$.
From here it follows that solving our equation is the same as solving the following equation:
$y''+2xy'+y-3y/{4x^2}=0 => a(x)=2x$. Thus by taking $y=x^rv$ we get
$v''+(2(x^{-1/2})'/(x^{-1/2})+2x)v'=0 =>$
$v''+(x^{-1}+2x)v'=0=>$
Take $w=v'$ and get $w'+(x^{-1}+2x)w=0$ we are done.
I think the continuation is simple.
Sincerely,
Tigran

A: It's probably easier if you first determine the (unique) value of $r$ which makes $y_1$ a solution.


text:
Q: Potentially corrupted external hard-drive freezing MacBook Pro I was copying some files from my old Macbook onto my external hard-drive, but at some point the file transfer completely stopped (no progress for 15+ minutes). I decided to stop the file transfer and try again. However, when I tried to stop the transfer anything connected to Finder disappeared - e.g. all icons on my desktop. Other programmes were still working, so I decided to quit everything while I could and reboot. However, this seems to have corrupted the external hard drive. I tried plugging it back in and it couldn't be mounted anymore. I tried it on a different MacBook Pro, and started running first aid from the disk utility. It was all going fine, but it is now at the "Checking catalog file" stage, and has completely frozen the Macbook. The colorful wheel just keeps spinning and nothing is responding.
What should I do to avoid further damage? Just wait?

A: *

*If your drive is formatted HFS+, try DiskWarrior.

*If #1 does not help: In the unlikely event that the root cause of the failure lies in the drive controller/interface, rather than data corruption on the drive itself, you may wish to buy an empty HDD enclosure and try moving the physical drive into it.

*If #1 and #2 fail or do not apply, you'll need to erase your drive and restore your data from a backup.

*If all of the above fail, you have no backup and your data is worth the cost, use a professional data recovery service.

Whatever you do, try to minimize the amount of time that the damaged drive is connected to power in order to reduce the chance for further corruption.


text:
Q: how is datacontractserializer performance 10% better than xmlserializer? I came across this in many articles recently and they didnt explain anything about this.
How is datacontractserializer performance 10% better ? Is this 10% figure mentioned by Microsoft anywhere ?
Can anyone tell me on what parameters is this figure based on, does this depend on the size of the object also. And will xmlserializer perform 10% worse in every scenario ?


text:
Q: Why use pattern matching in OCaml Let's consider this small function
let f x =
     match x with
         0 -> 1 |
         _ -> x ;;

This is logically equivalent to
let f x =
   if x = 0 then 1 else x ;;

What's then the purpose of pattern matching if we can achieve the same using if/else?

A: In your precise example, a pattern matching does not bring a lot, because you have only 2 cases, and more importantly because your pattern does not have any variable. Just write this example with if/then/else, you will understand:
let rec map f = function
    [] -> []
  | a::l -> let r = f a in r :: map f l

Note also that pattern matching warns you if you have redundant cases or if you forgot some cases.

A: A partial pattern matching is detected :
type number = Zero | One | Two;

let f= function
    Zero -> 0
  | One  -> 1 ;;

Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
Two
val f : number -> int = <fun>

A: Usually pattern matching allows a compiler to apply more aggressive optimization techniques. In the if/then/else expression the condition is an arbitrary expression, that can contain side effects. For example, the equality operator may do anything, so the compiler cannot, in general, rely that x=0 means that x is equal to zero. In pattern matching clauses are always constants, and matching means syntactic equality, that cannot be overloaded, so it can be easily compiled directly to assembly comparison operation. In the example with if, comparison will be in general compiled to a function call (but afaik in this case the compiler is clever enough, and the generated code would be the same).
But the main difference between if/then/else and pattern matching is that the latter is run in parallel and compiles into binary search trees embedded into the assembly, when if/then/else is just a linear sequence of comparisons (see this for more information).
Update
To satisfy OP curiosity I added some assembly output. It is not required to understand x86 assembler, one can just compare a number of instructions, to get a basic idea. You will see.
As I predicted, indeed, compiler emitted nearly the same code, that has the same performance for you example:
Function with_match has compiled into efficient code (notice that 0 in OCaml parlance is 1)
with_match:
.L101:
    cmpq    $1, %rax
    je  .L100
    ret
.L100:
    movq    $3, %rax
    ret

For function with_if compiler also emitted optimal code. The only difference is that in with_if function, the condition in jump instruction is inverted.
with_if:
.L103:
    cmpq    $1, %rax
    jne .L102
    movq    $3, %rax
    ret
.L102:
    ret

This was possible, because compiler uses a trick, that allows him to treat
= as a special function, with some theory attached to it. But in general this is not possible, as = can be arbitrary function. We can easily confuse compiler, by adding the following line to the start of the file:
let (=) x y = x = y

Now all tricks are disabled, and compiler emits this inefficient code.
with_if:
    subq    $8, %rsp
.L105:
    movq    %rax, 0(%rsp)
    movq    $1, %rsi
    movq    %rax, %rdi
    movq    _caml_equal, %rax
    call    _caml_c_call
.L106:
    movq    _caml_young_ptr, %r11
    movq    (%r11), %r15
    cmpq    $1, %rax
    je  .L104
    movq    $3, %rax
    addq    $8, %rsp
    ret
.L104:
    movq    0(%rsp), %rax
    addq    $8, %rsp
    ret

With all that said, I would like to stress, that one shouldn't prefer match over if or vice verse. A construct that is more clean and results in more readable code should be chosen. And ocaml compiler is rather good, and will emit efficient code for you.
I personally lean to more to matches, because this reflects my way of thinking. It is harder for me to reason in terms of if/then/else constructs, and whenever I read them, I mentally translate them into match with clauses. But this is my personal issue. Feel free to use whatever construct, that suits you better.


text:
Q: Creative json tree structure in postgres I'm trying to create a JSON representing an arbitrarily deep and wide hierarchy, for example of creatures:
CREATE TABLE creatures (
    name text PRIMARY KEY,
    parent text REFERENCES creatures(name)
);

INSERT INTO creatures(name,parent)
VALUES
('amoeba',NULL),
('beetle','amoeba'),
('coelacanth','amoeba'),
('salmon','coelacanth'),
('tuna','coelacanth'),
('lizard','coelacanth'),
('t-rex','lizard'),
('plant',NULL);

I want to turn this into a JSON like this:
[{"name":"amoeba",
  "children": [{"name": "beetle",
                "children": []},
               {"name": "coelacanth",
                "children": [{"name": "tuna",
                              "children": []},
                             {"name": "salmon",
                              "children": []}
                             {"name": "lizard",
                              "children": [{"name": "t-rex",
                                            "children": []}]}
                             ]}]},
 {"name": "plant",
  "children": []}]

Is this possible to do in Postgres?
So far I've tried
WITH RECURSIVE r AS
    -- Get all the leaf nodes, group by parent.
    (SELECT parent,
            json_build_object('name', parent,
                              'children', array_agg(name)) AS json
     FROM creatures c
     WHERE parent NOTNULL
         AND NOT EXISTS
             (SELECT 1
              FROM creatures c2
              WHERE c.name = c2.parent)
     GROUP BY parent

     UNION

     -- Recursive term - go one step up towards the top.
     SELECT c.parent,
            json_build_object('name', c.parent,
                              'children', array_agg(c.name)) AS json
     FROM r
     JOIN creatures c ON r.parent = c.name
     GROUP BY c.parent)
SELECT *
FROM r;

But it fails with
ERROR:  aggregate functions are not allowed in a recursive query's recursive term
LINE 19:                            'children', array_agg(c.name)) AS...

Is there any way to work around this, or another solution that can make me my nice tree?

A: First you should use the jsonb format instead of the json format in postgres, see the documentation here :

In general, most applications should prefer to store JSON data as
jsonb, unless there are quite specialized needs, such as legacy
assumptions about ordering of object keys..

Then, here below is a way to get your result converting jsonb into text, because the  jsonb replace function jsonb_set is unconfortable in your case :
CREATE VIEW parent_children (parent, children, root, cond) AS
(   SELECT jsonb_build_object('name', c.parent, 'children', '[]' :: jsonb) :: text AS parent
         , jsonb_agg(jsonb_build_object('name', c.name, 'children', '[]' :: jsonb)) :: text AS children
         , array[c.parent] AS root
         , array[c.parent] AS cond
      FROM creatures AS c
     GROUP BY c.parent
) ;

WITH RECURSIVE list(parent, children, root, cond) AS
(   SELECT children, children, root, cond
      FROM parent_children
     WHERE root = array[NULL]   -- start with the root parents
    UNION
    SELECT p.parent
         , replace(p.children, c.parent, replace(c.parent, '[]', c.children))
         , p.root
         , p.cond || c.cond
      FROM list AS p
     INNER JOIN parent_children AS c
        ON position(c.parent IN p.children) > 0
       AND NOT p.cond @> c.root -- condition to avoid circular path
)
SELECT children :: jsonb
  FROM list AS l
  ORDER BY array_length(cond, 1) DESC
  LIMIT 1 ;

The result is :
[
  {
    "name": "amoeba",
    "children": [
      {
        "name": "beetle",
        "children": []
      },
      {
        "name": "coelacanth",
        "children": [
          {
            "name": "salmon",
            "children": []
          },
          {
            "name": "tuna",
            "children": []
          },
          {
            "name": "lizard",
            "children": [
              {
                "name": "t-rex",
                "children": []
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "name": "plant",
    "children": []
  }
]


text:
Q: how to register com components inside docker as regsvr32 command executes successfully but the com components are not getting registered? We have deployed our .net application along with some COM components in docker but when we are trying to register COM dlls using regsvr32 the command gets executed without any error. But when we search for the CLS ID in the registry it is not available. Is it possible to register COM components in docker?

A: After copying a dll named msvbvm60.dll into System folder inside container, dll registrations started working.


text:
Q: Sequelize Query to get sum group by some specific values in one column Model
const Productions=sequelize.define("Productions",{
        rpt_date:{
            type:DataTypes.DATE,
        },
        unit:{
            type:DataTypes.STRING,
            allowNull:false
        },
        commodity:{
            type:DataTypes.STRING,
            allowNull:false
        },
        quantity:{
            type:DataTypes.INTEGER,
        },
    })

    return Productions;
}

Inside unit field there are 8 values like
'KRB','MBR','GUA','MPR','BOL','BAR','TAL','KAL'.

I want to get sum of amount for any specific day by grouping the unit field for 'KRB', 'MBR', 'GUA', 'MPR' AS JGOM and 'BOL', 'BAR', 'TAL', 'KAL' AS OGOM


text:
Q: How to rearrange numbers using SED (transposition) I have a line:
The ID number for product is 721- 971-4321.`

I want to swap the area code and exchange it for the number inside, like so: 971- 721-4321
Here is what I have:
17s/\([654]\)-\([817]\)/\2-\1/

So the number is on line 17 in a .txt file. There is other stuff on the line but I want to only change the number.
Whenever I run the script nothing happens. Any advice how to fix this.

A: Could you please try following.
sed 's/\([^0-9]*\)\([^-]*\)\([^0-9]*\)\([^-]*\)\(.*\)/\1\4\3\2\5/' Input_file

Explanation: I am using here back reference capability of sed here. Where by using regex I am creating 5 temporary buffers and then accessing them in reorder to make output as per OP's request.
Output will be as follows.
The ID number for product is 971- 721-4321.

A: This might work for you (GNU sed):
sed -E 's/([0-9]+-) ([0-9]+-)/\2 \1/' file


text:
Q: rational points of a hyperelliptic curve of genus 3 Let $K=\mathbb{Q}(\sqrt{-1}).$ I have the following hyperelliptic curve of genus 3:
$$ C : y^2 = (x^2-x+1)(x^6+x^5-6x^4 -3x^3+14x^2-7x+1) $$
I want to find $C(K)$. My first attempt was to compute the Jacobian of the curve $J(\mathbb{Q})$. By Magma, $J(\mathbb{Q})$ has rank 0 and the torsion subgroup is isomorphic to $\mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/52\mathbb{Z}.$ (generated by the root of one of the factors on the right side of the hyperelliptic curve equation and the difference of two points at infinity.) One can see that the reduction of $J$ modulo 5 has this group type.
In order to find the rank of $J(K)$, I need to compute the rank of the quadratic twist $J^{-1}(\mathbb{Q})$. According to Magma, it is impossible to obtain an upper bound for the rank so I got unlucky. When the rank is positive, I don't think it is computationally feasible to extract $K$-points on the curve. Is there another method for finding rational points generally on a hyperelliptic curves of even degree and odd genus $3?$ Any help would be appreciated.

A: It turns out that $C(K) = C(\mathbb Q) = \{\infty_+, \infty_-, (0,1), (0,-1), (1,1), (1,-1)\}$.
To see this, consider a point $P \in C(K)$ and write $\bar{P}$ for its image under the nontrivial automorphism of $K$. Then $P + \bar{P}$ is an effective divisor of degree 2 on $C$, which is defined over $\mathbb Q$ (this is what Xarles is alluding to in his comment). So for any effective rational divisor $D$ of degree 2 on $C$, the linear equivalence class of $P + \bar{P} - D$ is a rational point on $J$. As you state correctly, $J(\mathbb Q)$ is finite and is isomorphic to ${\mathbb Z}/2 \times {\mathbb Z}/52$; it is generated by differences of rational points on $C$ together with the point of order 2 corresponding to the given factorization of the polynomial in the equation, which makes it easy to enumerate all these 104 points (in Magma, say). Magma represents these points as effective divisors in Mumford representation (minus a multiple of one of the points at infinity). So we look at all these points and check if these divisors are of degree 2 with points in the support defined over $K$. The only such divisors we find are sums of two rational points. This shows that there are no ``exceptional'' $K$-points, i.e., no $K$-points with $x$-coordinate not in $\mathbb Q$. If $x(P) \in \mathbb Q$ and $P \notin C(\mathbb Q)$, then $P + \bar{P}$ is in the class of pull-backs of a point on ${\mathbb P}^1$; such points all give the same point on $J$. To deal with these, we observe that such points correspond bijectively to rational points on the quadratic twist $C^{(-1)}$. However, there are no such points, since the polynomial on the right hand side of the equation of $C$ is always positive. This finishes the proof.
The business with the exceptional points is related to the fact that the map from the symmetric square $C^{(2)}$ (there is an unfortunate clash of notations with the quadratic twist) to $J$ is not injective: there is a $\mathbb P^1$ contained in $C^{(2)}$ coming from pulling back points on $\mathbb P^1$ under the hyperelliptic double cover, and this $\mathbb P^1$ gets contracted to one point, whereas the map is injective otherwise.
Since every quadratic point on $C$ gives rise to a rational point on $C^{(2)}$, the computation above actually shows that there are the following exceptional quadratic points on $C$.
$$ (\tfrac{1\pm\sqrt{-3}}{2}, 0), (\pm\sqrt{2}, \pm 4\sqrt{2}-5),
   (\pm\sqrt{2}, \mp 4\sqrt{2}+5),
   (\tfrac{2\pm\sqrt{2}}{2}, \tfrac{-5\mp4\sqrt{2}}{4}),
   (\tfrac{2\pm\sqrt{2}}{2}, \tfrac{5\pm4\sqrt{2}}{4}),
   (-1\pm\sqrt{2}, -11\pm8\sqrt{2}), (-1\pm\sqrt{2}, 11\mp8\sqrt{2})
$$
(The signs correspond in each pair of coordinates.)


text:
Q: Problem in implementing Stack using Vector In a class say:
class X
{
     int _top;
     vector<int> _stack;
public:
     X() { } // SOME CONSTRUCTOR
};

Why does a constructor of this form works:
X( int capacity )
     : _stack( capacity ), _top( 0 ) { }

But these do not work:
1.
X( int capacity )
{ _stack( capacity );  _top=0; }

2.
X( int capacity )
     {_stack = capacity;  _top=0;}

Please Explain.

A: The first one works, because you're initializing _stack in initialization list, while the second form doesn't use initialization list.
Read the comments in this code to understand what is initialization list!
struct sample
{
    int a,b,c;
    vector<int> _stack;
    sample(int capacity) : _stack(capacity), a(1), b(10), c(100) {}
           // ^^^^^^^^^^^^^^^^^^^^^ this is called initialization list

    sample(int capacity, int x)
    {
       _stack(capacity); //wrong!

       a = b = c = x; // this is called assignment
       //here, inside the constructor body you cannot
       //initialize member variables, because members has been
       //constructed and initialized already by the time executions comes here!
    }
};

Basically, the syntax _stack(capacity) invokes the constructor. And constructor can be invoked only when the object is constructed. Once the object is constructed, you cannot invoke the constructor. In the second form, you're trying to invoke the constructor by writing _stack(capacity) in the constructor body, but by that time _stack is already constructed, that is why your code doesn't work!
For detail on initialization list, read this FAQ:
[10.6] Should my constructors use "initialization lists" or "assignment"?

A: In the first form you are calling a constructor, but not the second and the third.
In 1 you are calling vector<T>::operator ()(int), which is not defined for vector<T>.
In 2 you are assigned an int to vector<T> which is not defined either.
Also please keep in mind that std::vector<int>(size_t n) constructor doesn't just reserve memory, but rather populates the vector with n zeroes.  If you need to set the capacity without actually adding any values to the vector, call vector<T>::reserve(size_t).
And if that's not the goal in itself to implement the stack via vector, there's the std::stack container adaptor already available to use in the Standard Library.
stack<int> myStack;

Or
stack<int, vector<int> > myVectorBasedStack;

A: This form works, because it calls the constructors of the class members.
X( int capacity )
    : _stack( capacity ), //calls vector(int) constructor
    _top( 0 ) // calls int(int) constuctor
{ }

1.This does not work, because as soon as you are inside the constructor body, the constructors  should be called using other syntax.
X( int capacity )
{
    _stack( capacity ); //this is not a constuctor call. But this is vector operator()(int) call. And vector does not have this operator defined.
    //the proper constructor call in this place would be _stack = vector<int>( capacity );
    _top=0;
}

You may have mixed up this with shortened form of declaration and constructor call. If you declare _stack to be vector and initialize at the same time you can write:
vector<int> _stack( capacity );

But this is just a short form of:
vector<int> _stack = vector<int>( capacity );

2.This is wrong, obviously because you cannot just assign integer to vector
X( int capacity ){ _stack = capacity;  _top=0; }

A: The working form uses the vector's constructor - this is permitted in the initializer list.
The first non-working looks like you try to explicitly call the vectors constructor - that's not allowed, the vector has already been constructed. The initializer list allows you to replace default construction of super classes and member variables with explicit constructor calls.
The third doesn't work becase vector doesn't implement an assignment operator taking an int. It could be modified to _stack.resize(capacity)


text:
Q: SelectList in PageBlock Table is not working as expected I have created a SelectList inside of a PageBlock Table and when I add a new row to the table and use the select list it will hold the same value in all of the lists instead of just for that one row. Does Anyone have any thoughts on this? Below are pictures and code.

As you can see, both rows are set to "Red Pepper Jelly" even though I only selected that within the first row.
Here is my VF Page Code:
<apex:page controller="CommunityQuoteNowController" showHeader="true" sidebar="false" lightningStylesheets="true">

<apex:outputPanel id="messagePanel">
    <apex:pageMessages />
</apex:outputPanel>

<!-- Quote Now Form -->
<apex:form id="quoteNowForm" >
    <apex:pageBlock title="Quote Now">
        <apex:pageBlockButtons location="bottom">
            <apex:commandButton action="{!GetRates}" value="Get Rates"/>
            <apex:commandButton action="{!clearPage}" value="Clear" immediate="true" html-formnovalidate="formnovalidate" onclick="if(!confirm('Are you sure you would like to clear this page?')){return};" />
        </apex:pageBlockButtons>
        <apex:pageBlockSection id="CustomerProfile" columns="2" >
            <apex:inputField label="Customer Profile" value="{!load.rtms__Customer__c}" />
            <apex:selectList value="{!selectedMode}" title="Select" multiselect="false" size="1" id="selectModes" label="Mode">
                <apex:selectOptions value="{!ModesList}" />
            </apex:selectList>
        </apex:pageBlockSection>
        <apex:pageBlockSection title="Details" columns="2">
            <apex:inputField label="Ship Date" value="{!load.rtms__Order_Date__c}" />
            <apex:inputField label="Payment Terms" value="{!load.rtms__Payment_Terms__c}" />
            <apex:inputField label="Origin Zip Code" value="{!originStop.rtms__Postal_Code__c}" />
            <apex:inputField label="Destination Zip Code" value="{!destinationStop.rtms__Postal_Code__c}" />
        </apex:pageBlockSection>
        <hr />
        <apex:pageBlockSection id="FreightDetails" columns="1">
            <apex:outputLabel for="freightDetails" value="Freight Details"/>
            <apex:actionRegion immediate="true">
                <apex:selectList value="{!selectedFreightDetail}" title="freightDetails" multiselect="false" size="1" id="selectFreightDetails" label="Freight Details" >
                    <apex:selectOptions value="{!FreightDetails}" />
                    <apex:actionSupport event="onchange" reRender="FreightDetailsWrapper" />
                </apex:selectList>
            </apex:actionRegion>
        </apex:pageBlockSection>
        <apex:outputPanel layout="none" id="FreightDetailsWrapper" >
            <apex:pageBlockSection columns="2" id="ClassAndWeight" rendered="{!IF(selectedFreightDetail = 'Class_and_Weight',True,False)}">
                <apex:variable value="{!0}" var="index" />
                <apex:pageBlockTable value="{!lineItems}" var="items" >
                    <apex:column headerValue="Row #">
                        <apex:outputText>
                            <apex:variable value="{!index + 1}" var="index" />
                            {!index}
                        </apex:outputText>
                    </apex:column>
                    <apex:column headerValue="Select Commodity">
                        <apex:actionRegion>
                            <apex:selectList value="{!selectedCommodity}" title="Select" multiselect="false" size="1" id="selectCommodities" label="Commodity">
                                <apex:selectOptions value="{!Commodities}" />
                                <apex:actionSupport event="onchange" reRender="FreightDetailsWrapper" action="{!commoditySelected}" />
                            </apex:selectList>
                        </apex:actionRegion>
                    </apex:column>
                    <apex:column headerValue="NMFC Class" >
                        <apex:inputField label="NMFC Class" value="{!items.rtms__NMFC_Class__c}"/>
                    </apex:column>
                    <apex:column headerValue="Weight" >
                        <apex:inputField label="Weight" value="{!items.rtms__Weight__c}"/>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            <apex:pageBlockSection columns="4" id="Density"  rendered="{!IF(selectedFreightDetail = 'Density',True,False)}">
                <apex:repeat value="{!lineItems}" var="items">
                    <apex:inputField label="Length (in)" value="{!items.rtms__Length__c}"/>
                    <apex:inputField label="Width (in)" value="{!items.rtms__Width__c}"/>
                    <apex:inputField label="Height (in)" value="{!items.rtms__Height__c}"/>
                    <apex:inputField label="Weight (lbs)" value="{!items.rtms__Weight__c}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection columns="3" id="Pallet" rendered="{!IF(selectedFreightDetail = 'Pallet',True,False)}">
                <apex:repeat value="{!lineItems}" var="items">
                    <apex:inputField label="Handling Units" value="{!items.rtms__Handling_Units__c}"/>
                    <apex:inputField label="Handling Unit Count" value="{!items.rtms__Handling_Unit_Count__c}"/>
                    <apex:inputField label="Weight (lbs)" value="{!items.rtms__Weight__c}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:commandButton value="Add Line Item" Action="{!AddRow}" immediate="true" id="addRowButton"/>
        </apex:outputPanel>
    </apex:pageBlock>
</apex:form></apex:page>

And here is my Controller:
public class CommunityQuoteNowController {

// Variables
public rtms__Load__c load { get; set; }
public rtms__Stop__c originStop { get; set; }
public rtms__Stop__c destinationStop { get; set; }
public List<rtms__Load__c> loadList { get; set; }
public List<rtms__LineItem__c> lineItems { get; set; }
public List<rtms__LineItem__c> deleteLineItems { get; set; }
public String selectedMode { get; set; }
public List<SelectOption> availableModes { get; set; }
public String selectedFreightDetail { get; set; }
public List<SelectOption> options { get; set; }
public String selectedCommodity { get; set; }
public List<SelectOption> availableCommodities { get; set; }

public rtms__Load__c getLoad() {
    return load;
}

public CommunityQuoteNowController() {
    load = new rtms__Load__c();
    originStop = new rtms__Stop__c();
    destinationStop = new rtms__Stop__c();
    lineItems = new List<rtms__LineItem__c>();
    AddRow();
    selectedFreightDetail = 'Class_and_Weight';
}

public PageReference AddRow() {
    lineItems.add(new rtms__LineItem__c());
    return null;
}

public PageReference commoditySelected() {
    lineItems[0].rtms__NMFC_Class__c = selectedCommodity;
    return null;
}

public List<selectOption> getModesList() {
    List<rtms__Mode__c> modes = new List<rtms__Mode__c>();

    modes = [Select Id, Name from rtms__Mode__c];

    List<SelectOption> availableModes = new List<SelectOption>();

    availableModes.add(new SelectOption('','--None--'));

    for(rtms__Mode__c m : modes) {
        availableModes.add(new SelectOption(m.Id,m.Name));
    }
    return availableModes;
}

public List<selectOption> getCommodities() {
    List<rtms__Commodity__c> commodities = new List<rtms__Commodity__c>();

    commodities = [Select Id, Name, rtms__NMFC_Class__c, rtms__Description__c from rtms__Commodity__c WHERE Id = 'a1B02000000egveEAA'];

    List<SelectOption> availableCommodities = new List<SelectOption>();

    availableCommodities.add(new SelectOption('','--None--'));

    for(rtms__Commodity__c c : commodities) {
        availableCommodities.add(new SelectOption(c.rtms__NMFC_Class__c,c.rtms__Description__c));
        system.debug(availableCommodities);
    }
    return availableCommodities;
}

public List<selectOption> getFreightDetails() {
    List<SelectOption> options = new List<SelectOption>();

    options.add(new SelectOption('Class_and_Weight','Class and Weight'));
    options.add(new SelectOption('Density','Density'));
    options.add(new SelectOption('Pallet','Pallet'));

    return options;
}

/* Attempt at displaying a total weight for line items
public Decimal getTotalWeight(){
    Decimal totalWeight = 0;
    for(rtms__LineItem__c li : lineItems) {
        totalWeight += (li.rtms__Weight__c);
    }
    return totalWeight;
} */

public PageReference clearPage() {
    PageReference newpage = new PageReference(System.currentPageReference().getURL());
    newPage.getParameters().clear();
    newpage.setRedirect(true);
    return newpage;
}

public PageReference GetRates() {
    load.rtms__Mode__c = selectedMode;
    load.rtms__Total_Weight__c = 1;
    upsert load;

    if(load != null) {
        originStop.rtms__Load__c = load.Id;
        originStop.rtms__Number__c = 1;
        originStop.rtms__Is_Pickup__c = True;
        upsert originStop;
    }

    if(load != null) {
        destinationStop.rtms__Load__c = load.Id;
        destinationStop.rtms__Number__c = 2;
        destinationStop.rtms__Is_Dropoff__c = True;
        upsert destinationStop;
    }

    List<rtms__LineItem__c> items = new List<rtms__LineItem__c>();
    if(load != null) {
        for(rtms__LineItem__c i : lineItems) {
            i.rtms__Load__c = load.Id;
            i.Name = 'Line Item From Quote';
            i.rtms__Item_Description__c = 'From Quote';
            i.rtms__Pickup_Stop__c = originStop.Id;
            i.rtms__Delivery_Stop__c = destinationStop.Id;
            items.add(i);
        }
    }
    if(items != null) {
        upsert lineItems;
   }
   return null;
}}

Any help would be greatly appreciated.
Best,
Chad

A: The issue you are having is here:
<apex:pageBlockTable value="{!lineItems}" var="items" >
      ...
      <apex:column headerValue="Select Commodity">
         <apex:actionRegion>
           <apex:selectList value="{!selectedCommodity}" title="Select" multiselect="false" size="1" id="selectCommodities" label="Commodity">
             <apex:selectOptions value="{!Commodities}" />
                <apex:actionSupport event="onchange" reRender="FreightDetailsWrapper" action="{!commoditySelected}" />
           </apex:selectList>
         </apex:actionRegion>
      </apex:column>
  ...
</apex:pageBlockTable>

You are iterating over {!lineItems} yet binding the selected Commodity to a top-level property called selectedCommodity defined as:
public String selectedCommodity { get; set; }

Thus, when you refresh the page, that property is picked up by every row.
What you want is for each row's selectedCommodity to come from either:
Option 1:
A field on the iterated collection {!lineItems} - it looks like you could use rtms__NMFC_Class__c for this.
Or ...
Option2
Use a wrapper class that wraps each lineItem and the selected Commodity. Then your pageBlockTable iterates over a collection of Wrapper class objects. You can find many examples of Wrapper classes on Stackexchange or via a search engine


text:
Q: designer.cs not showing in solution I'm using Visual Studio Community 2015 and need to view the designer.cs file for one of my webforms.  However, when I expand the aspx file in the solution explorer, it does not show up.  How do I force Visual Studio to show me the designer.cs file?
Here's what I see in Solution Explorer:

Also, I seem unable to edit the project file (.csproj) by hand so that it will show the designer.cs file because I can't find the project file in the folder containing the code.  Here's a screenshot of that folder:
Folder Contents

A: In order for a designer file to show up beneath a source code file within the Project Explorer, the project file (.csproj) must have an entry as follows:
<Compile Include="page.aspx.cs">
  <DependentUpon>page.aspx</DependentUpon>
  <SubType>ASPXCodeBehind</SubType>
</Compile>
<Compile Include="page.aspx.designer.cs">
  <DependentUpon>page.aspx</DependentUpon>
</Compile>

Please open your ProjectName.csproj file and check to see that this pattern exists for your source file (.cs) and designer source file (.designer.cs).
You will have to unload and then reload your project from Visual Studio for changes to the Project File to take effect.

A: Per Dave in the comments above - It appears that your project is configured as a web site instead of a web application. I would recommend that you convert your project to a web application by creating a new project and re-adding the files. You can read up on the differences between the two models here on MSDN