text:
Q: gcc C/C++ assume no pointer aliasing Having recently read that the main reason why fortran is faster than c/c++ in numerical computations is because there is no pointer aliasing.
Apparently, using restrict or __restrict__ keywords allows on a case by case basis to indicate the absence of pointer aliasing for a given memory element.
The icc compiler apparently has an option -fno-alias which allows one to globally assume that no aliasing is present. On gcc there is -fno-strict-aliasing, which applies only to a subset of all the aliasing situations.
Is there an option present in gcc, or are there some cases where no aliasing is assumed, when using certain optimization flags?

A: GCC has the option -fstrict-aliasing which enables aliasing optimizations globally and expects you to ensure that nothing gets illegally aliased. This optimization is enabled for -O2 and -O3 I believe.
C++ has well defined aliasing rules, though, and standard-compliant code will not conflict with strict aliasing. In particular this means you're not allowed to access one variable through a pointer to a different type:
float f;
int * p = reinterpret_cast<int*>(&f);  // uh-oh
*p = 0x3FF00000;                       // breaks strict aliasing

The crucial exception to this rule is that you can always access any variable through a pointer to char. (This is necessary for serializing through IO operations.)
The aliasing rules do not help the compiler to know whether any pointers of the same type alias each other. Consider this:
void add(float * a, float * b, float * c) { *c = *a + *b; }

Here the compiler cannot know whether c points to different memory than a or b and has to be careful. I think this is where restrict makes a difference, essentially by promising that float * restrict c means that nobody aliases c.


text:
Q: C# program does not have take ownership privileges when UAC is disabled Basically I'm writing a tool for my job that replaces a broken file copied incorrectly by a software installation with a working version of the file from another computer.
Part of this tool requires me to take ownership of the folder containing the target file (by default this folder is owned by SYSTEM). I am an admin so I can do this through Explorer with no problem, but the tool that I created is unable to take ownership from SYSTEM, but can take ownership without error if the owner is anyone else (another admin for example)
I already have built a manifest which uses requireAdministrator, and this tool is able to take ownership from SYSTEM on my home computer, but not on my work computer.
I believe this is because UAC is disabled via group policy. Is there any way for me to run this program with admin privileges? Thanks for the help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot start a new React Native CLI project in WebStorm The react-native-cli is generating the project fine when I use this command in terminal:
react-native init myapp

But for some reason WebStorm cannot create new React Native project. When I try I get this error:
/home/sagar/.nvm/versions/node/v8.9.1/bin/node
/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js init bookip
/bin/sh: 1: npm: not found
This will walk you through creating a new React Native project in /tmp/1512313270685-0/bookip
Installing react-native...
Consider installing yarn to make this faster: https://yarnpkg.com
{ Error: Command failed: npm install --save --save-exact react-native
    at checkExecSyncError (child_process.js:601:13)
    at execSync (child_process.js:641:13)
    at run (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:294:5)
    at createProject (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
  error: null,
  cmd: 'npm install --save --save-exact react-native',
  file: '/bin/sh',
  args:
   [ '/bin/sh',
     '-c',
     'npm install --save --save-exact react-native' ],
  options:
   { stdio: [ [Object], [Object], [Object] ],
     shell: true,
     file: '/bin/sh',
     args:
      [ '/bin/sh',
        '-c',
        'npm install --save --save-exact react-native' ],
     envPairs:
      [ 'PATH=/home/sagar/bin:/home/sagar/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin',
        'LC_MEASUREMENT=ne_NP',
        'XAUTHORITY=/home/sagar/.Xauthority',
        'XMODIFIERS=@im=ibus',
        'LC_TELEPHONE=ne_NP',
        'XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop',
        'GDMSESSION=ubuntu',
        'MANDATORY_PATH=/usr/share/gconf/ubuntu.mandatory.path',
        'LC_TIME=ne_NP',
        'GTK_IM_MODULE=ibus',
        'DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-Sq2eReOVZr',
        'DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path',
        'XDG_CURRENT_DESKTOP=Unity',
        'LD_LIBRARY_PATH=/home/sagar/apps/WebStorm-172.3757.55/bin:',
        'UPSTART_SESSION=unix:abstract=/com/ubuntu/upstart-session/1000/1240',
        'QT4_IM_MODULE=xim',
        'LC_PAPER=ne_NP',
        'QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1',
        'LOGNAME=sagar',
        'JOB=unity-settings-daemon',
        'PWD=/tmp/1512313270685-0',
        'IM_CONFIG_PHASE=1',
        'LANGUAGE=en_US',
        'SHELL=/bin/bash',
        'LC_ADDRESS=ne_NP',
        'GIO_LAUNCHED_DESKTOP_FILE=/home/sagar/.local/share/applications/jetbrains-webstorm.desktop',
        'GTK2_MODULES=overlay-scrollbar',
        'INSTANCE=',
        'OLDPWD=/home/sagar/apps/WebStorm-172.3757.55/bin',
        'GNOME_DESKTOP_SESSION_ID=this-is-deprecated',
        'UPSTART_INSTANCE=',
        'GTK_MODULES=gail:atk-bridge:unity-gtk-module',
        'CLUTTER_IM_MODULE=xim',
        'XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0',
        'COMPIZ_BIN_PATH=/usr/bin/',
        'SESSIONTYPE=gnome-session',
        'XDG_SESSION_DESKTOP=ubuntu',
        'SHLVL=0',
        'LC_IDENTIFICATION=ne_NP',
        'LC_MONETARY=ne_NP',
        'COMPIZ_CONFIG_PROFILE=ubuntu',
        'QT_IM_MODULE=ibus',
        'UPSTART_JOB=unity7',
        'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64',
        'XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
        'LANG=en_US.UTF-8',
        'GNOME_KEYRING_CONTROL=',
        'XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0',
        'XDG_SESSION_ID=c2',
        'XDG_SESSION_TYPE=x11',
        'DISPLAY=:0',
        'LC_NAME=ne_NP',
        'GDM_LANG=en_US',
        'XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/sagar',
        'UPSTART_EVENTS=xsession started',
        'GPG_AGENT_INFO=/home/sagar/.gnupg/S.gpg-agent:0:1',
        'DESKTOP_SESSION=ubuntu',
        'SESSION=ubuntu',
        'USER=sagar',
        'XDG_MENU_PREFIX=gnome-',
        'GIO_LAUNCHED_DESKTOP_FILE_PID=20103',
        'QT_ACCESSIBILITY=1',
        'LC_NUMERIC=ne_NP',
        'SSH_AUTH_SOCK=/run/user/1000/keyring/ssh',
        'XDG_SEAT=seat0',
        'QT_QPA_PLATFORMTHEME=appmenu-qt5',
        'XDG_VTNR=7',
        'XDG_RUNTIME_DIR=/run/user/1000',
        'HOME=/home/sagar',
        'GNOME_KEYRING_PID=' ],
     killSignal: undefined },
  envPairs:
   [ 'PATH=/home/sagar/bin:/home/sagar/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin',
     'LC_MEASUREMENT=ne_NP',
     'XAUTHORITY=/home/sagar/.Xauthority',
     'XMODIFIERS=@im=ibus',
     'LC_TELEPHONE=ne_NP',
     'XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop',
     'GDMSESSION=ubuntu',
     'MANDATORY_PATH=/usr/share/gconf/ubuntu.mandatory.path',
     'LC_TIME=ne_NP',
     'GTK_IM_MODULE=ibus',
     'DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-Sq2eReOVZr',
     'DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path',
     'XDG_CURRENT_DESKTOP=Unity',
     'LD_LIBRARY_PATH=/home/sagar/apps/WebStorm-172.3757.55/bin:',
     'UPSTART_SESSION=unix:abstract=/com/ubuntu/upstart-session/1000/1240',
     'QT4_IM_MODULE=xim',
     'LC_PAPER=ne_NP',
     'QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1',
     'LOGNAME=sagar',
     'JOB=unity-settings-daemon',
     'PWD=/tmp/1512313270685-0',
     'IM_CONFIG_PHASE=1',
     'LANGUAGE=en_US',
     'SHELL=/bin/bash',
     'LC_ADDRESS=ne_NP',
     'GIO_LAUNCHED_DESKTOP_FILE=/home/sagar/.local/share/applications/jetbrains-webstorm.desktop',
     'GTK2_MODULES=overlay-scrollbar',
     'INSTANCE=',
     'OLDPWD=/home/sagar/apps/WebStorm-172.3757.55/bin',
     'GNOME_DESKTOP_SESSION_ID=this-is-deprecated',
     'UPSTART_INSTANCE=',
     'GTK_MODULES=gail:atk-bridge:unity-gtk-module',
     'CLUTTER_IM_MODULE=xim',
     'XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0',
     'COMPIZ_BIN_PATH=/usr/bin/',
     'SESSIONTYPE=gnome-session',
     'XDG_SESSION_DESKTOP=ubuntu',
     'SHLVL=0',
     'LC_IDENTIFICATION=ne_NP',
     'LC_MONETARY=ne_NP',
     'COMPIZ_CONFIG_PROFILE=ubuntu',
     'QT_IM_MODULE=ibus',
     'UPSTART_JOB=unity7',
     'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64',
     'XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
     'LANG=en_US.UTF-8',
     'GNOME_KEYRING_CONTROL=',
     'XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0',
     'XDG_SESSION_ID=c2',
     'XDG_SESSION_TYPE=x11',
     'DISPLAY=:0',
     'LC_NAME=ne_NP',
     'GDM_LANG=en_US',
     'XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/sagar',
     'UPSTART_EVENTS=xsession started',
     'GPG_AGENT_INFO=/home/sagar/.gnupg/S.gpg-agent:0:1',
     'DESKTOP_SESSION=ubuntu',
     'SESSION=ubuntu',
     'USER=sagar',
     'XDG_MENU_PREFIX=gnome-',
     'GIO_LAUNCHED_DESKTOP_FILE_PID=20103',
     'QT_ACCESSIBILITY=1',
     'LC_NUMERIC=ne_NP',
     'SSH_AUTH_SOCK=/run/user/1000/keyring/ssh',
     'XDG_SEAT=seat0',
     'QT_QPA_PLATFORMTHEME=appmenu-qt5',
     'XDG_VTNR=7',
     'XDG_RUNTIME_DIR=/run/user/1000',
     'HOME=/home/sagar',
     'GNOME_KEYRING_PID=' ],
  stderr: null,
  stdout: null,
  pid: 20527,
  output: [ null, null, null ],
  signal: null,
  status: 127 }
Command `npm install --save --save-exact react-native` failed.
Done

It says npm not found when I know it is there.
I have Node 8.9.1 & npm 5.5.1

A: Looks like npm is not on your $PATH. Do you launch WebStorm from terminal, or from desktop/System menu? In the latter case, WebStorm only sees environment variables configured in .profile (login shell), but not in interactive shell configuration files (like ~/.bashrc). Plus, NVM alters interactive shell configuration files only during installation phase (https://github.com/creationix/nvm/blob/v0.28.0/install.sh#L126)
Possible workarounds:

*

*Workaround 1: make required variables available in a login shell (i.e. for Bash, move them from .bashrc to .bash_profile or .profile).

*Workaround 2: run IDE from a terminal

*Workaround 3: edit WebStorm desktop launcher and set command to /bin/bash -l -i -c  "/path/to/webstorm.sh" (for bash)

A: Try pointing to your usr/local/bin/node folder.  These are my settings with WebStorm 2017.3 and it worked for me.

A: Consider installing yarn to make this faster: https://yarnpkg.com
After yarn was installed error is gone.


text:
Q: Change bar color based on value I am currently using plotly to generate some simple graphs in python.
The graphs represent the predicted energy consumption of a large area each hour. What i want to do is change the color of each individual bar if the predicted energy consumption of that area is high to red, and if it is low to green. The high- and low-values are calculated for each day, so they are not constant.
Is there any way i could do this using plotly?

A: Seemed like a fun task to practice plotly and python on.
Here is a plotly plot using some faked up data:
import plotly.plotly as py
import plotly.graph_objs as go
import random
import datetime

# setup the date series
#  we need day of week (dow) and if it is a weekday (wday) too
sdate = datetime.datetime.strptime("2016-01-01", '%Y-%m-%d').date()
edate = datetime.datetime.strptime("2016-02-28", '%Y-%m-%d').date()
ndays = (edate - sdate).days + 1
dates = [sdate + datetime.timedelta(days=x) for x in range(ndays)]
dow   = [(x + 5) % 7 for x in range(ndays)]
wday  = [1 if dow[x]<=4 else 0 for x in range(ndays)]

# now some fake power consumption
# weekdays will have 150 power consumption on average
# weekend will have 100 power consumption on average
# and we add about 20 in random noise to both
pwval  = [90 + wday[x] * 50 + random.randrange(0, 20) for x in range(ndays)]
# limits - higher limits during the week (150) compared to the weekend (100)
pwlim  = [150 if dow[x] <= 4 else 100 for x in range(ndays)]

# now the colors
clrred = 'rgb(222,0,0)'
clrgrn = 'rgb(0,222,0)'
clrs  = [clrred if pwval[x] >= pwlim[x] else clrgrn for x in range(ndays)]

# first trace (layer) is our power consumption bar
trace0 = go.Bar(
    x=dates,
    y=pwval,
    name='Power Consumption',
    marker=dict(color=clrs)
)
# second trace is our line showing the power limit
trace1 = go.Scatter(
    x=dates,
    y=pwlim,
    name='Power Limit',
    line=dict(
        color=('rgb(0,0,222)'),
        width=2,
        dash='dot')
)
data = [trace0, trace1]
layout = go.Layout(title='Power')
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='power-limits-1')

And this is what it looks like:


text:
Q: Reading Excel for MAC formatting Previously I was working on reading the MACs and formatting the output. I'm trying to do it using Pandas and Excel file now with the macaddress module. I'm pretty close but hitting a snag at the end.
def readfile_excel():
    df = pd.read_excel('ap_macs.xlsx', usecols=['apmac'], index_col=False)
    df_csv = pd.DataFrame.to_string(df,index=0,header=None)
    df_split = df_csv.splitlines()
    #print(df_split)
    for i in df_split:
        data = (i)
        print(data)
        mac_data = macaddress.MAC(data)
        print(mac_data)

Getting the following error:

ValueError: ' D0D3E0C19A54' cannot be parsed as MAC

So it looks like when I split the lines, ' ' this extra stuff in there is not going away

[' D0D3E0C19A54', ' D0D3E0C19A55', ' D0D3E0C19A56']

Even though if I print out the "data" it doesn't show up there. Any tips/pointers? Thank you


text:
Q: Stack memory is being referred by dynamically allocated object member variable I have following code
class Test
{
public:
    int &ref;
    int a;

    Test(int &x)
        :ref(x)
    {
        cout<<"Address of reference "<<&ref<<endl;
        cout<<"&a : "<<&a<<endl;
        cout<<"this = "<<this<<endl;
    }
};

int main()
{
    Test *pObj = NULL;
    {
        int i = 10;
        cout<<"Address of referent "<<&i<<endl;
        pObj = new Test(i);
    }
    pObj->ref++;
    cout<<pObj->ref;
}

Output is :

Address of referent 002DFB3C

Address of reference 002DFB3C

&a : 00734C94

this = 00734C90

As you can see, Test object is being created dynamically. variable i which is stored on stack is being sent as parameter to constructor of Test class. I printed the address of variables i, ref and a.
Question: variable i will be destroyed once program control exits the block in which it is declared. But dynamically allocated object's member variable ref would still be refering to the stack address(Address of i). Able to use ref after the death of i.
Why heap object has reference to stack memory ? Why is this allowed ?

A:
Why [does the] heap object have a reference to stack memory?

Because you passed the local variable i by reference into the constructor of the Test object that you created dynamically, then the constructor stored that reference.

Why is this allowed?

In C++, you the programmer are responsible for ensuring that any pointers you use point to valid objects.  The language doesn't have any guards to "protect" you from doing dumb things like this (there are, of course, good programming practices that exist to help you ensure that code you write shouldn't have issues like this).
An attempt to use an object after its lifetime has ended results in undefined behavior.


text:
Q: Using ACF with GraphQL and Gatsby, flexible content is not returning the order of it's child blocks I have a Gatsby site that is hooked up to use Wordpress as a headless CMS. I am using ACF to create dynamic layouts in Wordpress then rendering the modules I add to page to the frontend(Gatsby). I am using the flexible content feature in ACF to dynamically create layouts in the cms that can be easily rendered in React. Normally I do this with next.js and Wordpress's REST API which returns the "flexible content" data as an array of objects I can easily iterate over and render the appropriate content with.
My issue is that with using GraphQL and Gatsby, my "flexible content" data  I get it back from the API is just a bunch of objects within the parent page's object body. This means there is no relationship to what order the modules/children were placed in the flexible content block since they aren't part of an array. My workaround, for the time being, is to add an extra field to the child modules that specify its' order on the page based on a number value.....but this is gross and would be a horrible experience for a client so I am not happy with that.
Is there a way to either return a value for each item in an AFC flexible content block that directly relates to its index/position. Or is there a way to return the children items in an array when using the Gatsby plugin for returning data.
Currently, my query looks a little like this:
allWordpressPage {
  edges {
    node {
      id
      slug
      status
      template
      title
      childWordPressAcfFeaturedShowcaseCarousel {
        id
        title
        other_stuff
      }
      childWordPressAcfIphonesAndContent {
        id
        title
        other_stuff
      }
      childWordPressAcfContentAndImageSlideShow {
        id
        title
        other_stuff
      }
    }
  }
}

That will return something like:
{
  id: 123,
  slug: 'hello',
  template: 'default',
  title: 'Help Me',
  childWordPressAcfFeaturedShowcaseCarousel: {
    id: 1232
    title: 'Bonjour'
    other_stuff: {....}
  },
  childWordPressAcfIphonesAndContent: {
    id: 1232
    title: 'Bonjour'
    other_stuff: {....}
  },
  childWordPressAcfContentAndImageSlideShow: {
    id: 1232
    title: 'Bonjour'
    other_stuff: {....}
  }
}

But instead, I would want something like:
{
  id: 123,
  slug: 'hello',
  template: 'default',
  title: 'Help Me',
  childWordPressAcfFeaturedShowcaseCarousel: {
    id: 1232,
    index: 1,
    title: 'Bonjour',
    other_stuff: {....}
  },
  childWordPressAcfIphonesAndContent: {
    id: 1232,
    index: 2,
    title: 'Bonjour',
    other_stuff: {....}
  },
  childWordPressAcfContentAndImageSlideShow: {
    id: 1232,
    index: 3,
    title: 'Bonjour'
    other_stuff: {....}
  }
}

Or even better:
{
  id: 123,
  slug: 'hello',
  template: 'default',
  title: 'Help Me',
  module: [
    childWordPressAcfFeaturedShowcaseCarousel: {
      id: 1232,
      title: 'Bonjour',
      other_stuff: {....}
    },
    childWordPressAcfIphonesAndContent: {
      id: 1232,
      title: 'Bonjour',
      other_stuff: {....}
    },
    childWordPressAcfContentAndImageSlideShow: {
      id: 1232,
      title: 'Bonjour'
      other_stuff: {....}
    }
  ]
}

A: So I just figured it out. Turns out when querying data for a flexible content block there are a few things to remember. To access flexible content fields, instead of using their field name, you need to use [field_name]_[post_type] (if you have field named page_builder in your WordPress pages you would need to use page_builder_page). Once you do that everything will return in an array in the exact order they are in the ACF block.
So now my query looks like this:
allWordpressPage {
  edges {
    node {
      id
      slug
      status
      template
      title
      acf {
        modules_page {
          ... on WordPressAcf_featured_showcase_carousel {
            __typename
            id
            title
            other_stuff
          }
          ... on WordPressAcf_iphones_and_content {
            __typename
            id
            title
            other_stuff
          }
          ... on WordPressAcf_content_and_image_slide_show {
            __typename
            id
            title
            other_stuff
          }
        }
      }
    }
  }
}


text:
Q: Python : Recursively flatten a list I have a list l = [2, 9, [1, 13], 8, 6]. How can I flatten it recursively to get l = [2, 9, 1, 13, 8, 6]?

A: If you want to flatten arbitrarily nested iterables, you could try this function:
def flatten(x):
    try:
        it = iter(x)
    except TypeError:
        yield x
    else:
        for i in it:
            for j in flatten(i):
                yield j

Example:
a = [2, 9, [1, 13], 8, 6]
list(flatten(a))
# [2, 9, 1, 13, 8, 6]

Note that the function would also flatten out strings to single characters.


text:
Q: Why the email address could not be recognized by VSTS when assign work items? I tried set the email address for assign to field for work item manually.
Then an error displayed as "The identity value 'xxx@xxx.com' for field 'Assigned To' is an unknown identity."
This could be resolved by clicking search the user. Then the email address will be recognized.
Why the work item doesn't recognize the email address?
And how to assign the work item to user by email via coding?

A: To trouble shooting the issue, you can check with below aspects:

*

*Check if the user has been added to the VSTS account
In the Users Tab https://account.visualstudio.com/_admin/_users, make sure the  user (xxx@xxx.com) has been added.

*Check if the user and your VSTS in different AAD
It's mainly caused by the user (xxx@xxx.com) is backed to another AAD, so the VSTS account and the user (xxx@xxx.com) are in different AAD.
To double check if it's caused by AAD, you can ask the user (xxx@xxx.com) to login your VSTS account . If it shows 401 error, that means the user (xxx@xxx.com) is backed to a different AAD. To solve the issue, you can use any of below options:

*

*Option 1: ask the user to use a microsoft email address (such as xxx@outlook.com or xxx@hotmail.com etc).

*Option 2: add the VSTS accoutn to the same AAD as the user xxx@xxx.com.
You can refer the article Connect VSTS account to Azure Active Directory.

You can also refer the related post here.


text:
Q: Android. Изменение view выбора даты Здравствуйте.
В приложении необходимо выбрать дату. Используется стандартный DatePickerDialog.
При отображении выбора даты, календарь выглядит в Европейском стиле (Воскресенье - первый день недели). Как изменить выбор даты так, чтобы первым днем недели был понедельник?

И сразу второй вопрос касательно этой view.
Как заменить обозначения дней недели
с [П, В, С, Ч, П, С, В]
на [Пн, Вт, Ср, Чт, Пт, Сб, Вс]

A: это можно сделать, к примеру, в методах onCreate()/onCreateView() ваших активити/фрагмента
date = (DatePicker) value.findViewById(R.id.date);
if (Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1) {
    date.getCalendarView().setFirstDayOfWeek(Calendar.MONDAY);
}

либо строчкой ниже можно привязаться к локали:
date.getCalendarView().setFirstDayOfWeek(Calendar.getInstance().getFirstDayOfWeek());

https://stackoverflow.com/a/14423516/5887158


text:
Q: Why does my code skip straight to the else statement? Why does my code skip straight to the else statement? It returns the values inputted correctly if asked. But cant figure out why it just skips to "ERROR!" as opposed to proceeding to the relevant calculator. Here is my code:
package easy2;
import java.util.Scanner;
public class Calculator {

public static void main(String[] args) {

    float force, mass, acc;
    String answer = null;
    Scanner in = new Scanner(System.in);

    System.out.println("Force = Mass x Acceleration Calculator");

    System.out.println("Please state which variable you wish to work out: force, mass or acceleration");
    answer = in.nextLine();

    if(answer == "force"){
        System.out.println("What is your mass in killograms?");
        mass = in.nextFloat();
        System.out.println("What is your acceleration in meters per second?");
        acc = in.nextFloat();

        force = mass * acc;

        System.out.println("The force of this equation in Netwon Meters is " + force);
        }
    else if(answer == "mass") {
            System.out.println("What is your force in Newton Meters?");
            force = in.nextFloat();
            System.out.println("What is your acceleration in meters per second?");
            acc = in.nextFloat();

            mass = force / acc;

            System.out.println("The mass of this equation is equal to " + mass + "kg");
    }
    else if(answer == "acceleration"){

        System.out.println("What is your force in Newton Meters?");
        force = in.nextFloat();
        System.out.println("What is your mass in killograms?");
        mass = in.nextFloat();

        acc = force / mass;

        System.out.println("The acceleration of this equation equals " + acc + "m/s");

    }
    else{System.out.println("ERROR!");
    }
}

}

A: Try using myString.equals("myOtherString"). You're doing the string comparison wrong.
== in Java is to compare objects for equality, not their values.
I've made the same mistake countless times.


text:
Q: If $a,b,c \in \mathbb R$, $a+b+c=2$, $a^2-b^2-c^2=12$, find the difference between the max and min possible value of c. I couldn't find the answer to this on Google, but I did find a similar problem on Art of Problem Solving. The question was exactly same except that in the question $$a^2+b^2+c^2=12$$
But I couldn't incorporate the solution in my question because in mine only $b^2$ and $c^2$ are negative and $a^2$ has a different sign.
The answer given is 25, but I don't know how this answer came.

A: You can assume $c \neq 2$, otherwise you get a contradiction. Since $a+b=2-c$ and $(a+b)(a-b)=12+c^2$ then $a-b=(12+c^2)/(2-c)$, so you can find $a$ and $b$. This tells you any $c \neq 2$ will do, so the question does not make much sense.

A: Hint
The general idea is to eliminate one of $a,b$
$$12=(2-b-c)^2-b^2-c^2=4-4b-4c+2bc$$
$$\iff8+4b=2bc-4c$$
$$b=4(2+c)/2(c-2)$$
So, $c$ can assume any real value $\ne2$


text:
Q: How to organize builds by project and sub-project in Jenkins? We currently use TFS for source control and TeamCity for CI/CD, and we have over 300 builds. We are looking to possibly migrate to Jenkins, but I'd like to know if builds in Jenkins can be organized by project and sub-project.
For example, in TeamCity our builds are organized by Project, then by sub-project (branch), and then by builds:
Project1
    Dev
        build1
        build2
    Test
        build3
    Release
        build1
        build2
        build3
Project2
    Dev
        build1
    Test
        build2
    Release
        build1
        build2
Etc.

Can this type of organization be done in Jenkins?
If not, then we would have to name our builds something like Project1_Branch_build1, and have a long flat list of 300+ builds in Jenkins.


text:
Q: hapi-fhir-android library : how to bypass getting conformance? I'm trying to access FHIR resources from a FHIR server. Everything works fine when accessing the FHIR resources via postman
This is my code:
String serverBase = https://<fhir-server-url>;

//Adding required headers here - removed as irrelevant for this question

IGenericClient client = ctx.newRestfulGenericClient(serverBase);
client.setEncoding(EncodingEnum.JSON);

Patient p = client.read(Patient.class, "jasdkfljasdklfjasldfkja");
String resPatient = p.getName().get(0).getGiven().toString();

PROBLEM: The conformance functionality is broken and I am not being able to proceed with doing any operations on resources because the IGenericClient gets the conformance when initiating by calling https://<fhir-server-url>/metadata.
It is going to take time for the conformance functionality to get fixed. Meanwhile, I was wondering if there is a way to bypass getting the conformance by setting a flag or something so that i can access the FHIR resources?

A: Figured out myself. Can be done as follows:
FhirContext fhirfctx = FhirContext.forDstu2();

// bypass conformance check

fhirfctx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);


text:
Q: DataTemplate not drawing the View, but printing the typename for each ViewModel type it encounters in a Collection  <Grid>
        <ItemsControl ItemsSource="{Binding ScreenViewModelCollection}">
            <ItemsControl.Resources>
                <DataTemplate DataType="{x:Type redScreenView:RedScreenView}">
                    <Grid>
                        <redScreenView:RedScreenView/>
                    </Grid>
                </DataTemplate>

                <DataTemplate DataType="{x:Type greenScreenView:GreenScreenView}">
                    <Grid>
                        <greenScreenView:GreenScreenView/>
                    </Grid>
                </DataTemplate>

            </ItemsControl.Resources>
        </ItemsControl>

Instead of drawing the View for its ViewModel, it prints the namespace that the View belongs to!
But using an ItemTemplate works for just one of them. And ItemTemplate can't have more than one content :(

A: Your DataTemplates are for Views while I suspect your ScreenViewModelCollection contains ViewModels.
You just need to make the DataType properties be ViewModels instead of Views
<DataTemplate DataType="{x:Type myViewModels:RedScreenViewModel}">
    <Grid>
        <redScreenView:RedScreenView/>
    </Grid>
</DataTemplate>

<DataTemplate DataType="{x:Type myViewModels:GreenScreenViewModel}">
    <Grid>
        <greenScreenView:GreenScreenView/>
    </Grid>
</DataTemplate>

A: i miss the definition for redScreenView/greenScreenView namespace, type of ScreenViewModelCollection, xaml for ItemsControl.ItemTemplate - so i just assume:
EDIT: pls look at your xaml i think you has some typos in there. the DataType for your DataTemplates should be the viewmodel. the content of the datatemplate the view of course.
nevertheless the local define the namespace and have to be in your window/usercontrol definition. e.g.
 <UserControl xmlns:local="clr-namespace:MyWpfApplication1.MyTest.ViewModels"
              xmlns:views="clr-namespace:MyWpfApplication1.Controls.Views"

    <ItemsControl ItemsSource="{Binding ScreenViewModelCollection}">
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type local:RedScreenViewModel}">
                <Grid>
                    <views:RedScreenView/>
                </Grid>
            </DataTemplate>
            <DataTemplate DataType="{x:Type local:GreenScreenViewModel}">
                <Grid>
                    <views:GreenScreenView/>
                </Grid>
            </DataTemplate>
        </ItemsControl.Resources>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

does this ItemTemplate work for you?


text:
Q: Apply a function to each column with a condition in data.table [R] I'd like to apply a couple functions to a column but I want to apply some logic as to when I do this, in this case when another column has some NA's. To illustrate I'll add some NA to the iris dataset and turn it into a data.table:
library(data.table)

irisdt <- iris
## Prep some example data
irisdt[irisdt$Sepal.Length < 5,]$Sepal.Length <- NA
irisdt[irisdt$Sepal.Width < 3,]$Sepal.Width <- NA

## Turn this into a data.table
irisdt <- as.data.table(iris)

If I wanted to apply max to multiple columns I'd go like this:
## Apply a function to individual columns
irisdt[, lapply(.SD, max), .SDcols = c("Petal.Length", "Petal.Width")]
#>    Petal.Length Petal.Width
#> 1:          6.9         2.5

In this case however I'd like to take out any row that isn't an NA in Sepal.Length and then return max and min along with the name of the column I subset for NA's. Below is an ugly way of implementing this but hopefully illustrates what I am after:
## Here is what the table would look like
desired_table <- rbind(
  irisdt[!is.na(Sepal.Length), .(max = max(Petal.Length), min = min(Petal.Length), var = "Sepal.Length")],
  irisdt[!is.na(Sepal.Width), .(max = max(Petal.Length), min = min(Petal.Length), var = "Sepal.Width")]
)

desired_table
#>    max min          var
#> 1: 6.9 1.2 Sepal.Length
#> 2: 6.7 1.0  Sepal.Width

Created on 2020-01-14 by the reprex package (v0.3.0)
Any thoughts on how I might accomplish this?

A: melt may be better option if we are comparing by multiple columns.  Reshape into 'long' format, then use i with the condition !is.na(value), while grouping by 'variable' and get the min and max of the specified variable
library(data.table)
melt(irisdt,  measure = c('Sepal.Length', 'Sepal.Width'))[!is.na(value),
   .(max = max(Petal.Length), min = min(Petal.Length)), .(variable)]

If we are doing this for multiple variables, then use the lapply(.SD, ...


text:
Q: Binded DataGridView problem I have a binded DataGridView that allows adding new rows. The problem is that a new object is automatically inserted in the binding source when the CurrentRow is the last grid row.
I want that a new object to be added to the binding source only when the user starts typing in one of the last row cells.

A: That's not the way DataGridView works, and having tried before to change the way adding new items works, I have to caution you against trying it.
Your best option is to have your binding source implement the ICancelAddNew interface. If this interface is implemented, then the DataGridView will call CancelNew if the user leaves the row without entering any data into the new item. You can also use a BindingList<T> as your data source, or wrap your data source in a BindingSource; both of these classes implement ICancelAddNew.


text:
Q: pgfplotstable: How to add variable names (x_1, x_2,...) on each column? I would like to create a System of linear equations indeed with pgfplotstable.
How can I add names of variables (x_1, x_2,... or something else: x,y,z), if some strings have been replaced?
string replace={0}{},
string replace={-1}{-x},
string replace={1}{x}

\documentclass[border=5pt, varwidth]{standalone}
\usepackage{pgfplotstable, systeme}
 \pgfplotsset{compat=1.13}

\pgfplotstableset{
string type,%
%header=false,
every head row/.style={output empty row},%
column type=r,%
postproc cell content/.append style={
/pgfplots/table/@cell content/.add={$}{$},
},%
}

\begin{document}
\pgfplotstableread{
x                    y
-1                   0
0                    1
1                    2
3                    3
0                    4
13                  5
-6                   6
-\frac{3}{2}    7
-12                 8
}\test

Actual:  \pgfplotstabletypeset[]{\test}
%
Partially replaced:  \pgfplotstabletypeset[
string replace={0}{},
string replace={-1}{-x},
string replace={1}{x},
]{\test} \\

\bigskip
Target:  $\newcolumntype{R}{>{{}}r<{{}}}
\setlength\arraycolsep{1pt}
\begin{array}{ r R r R}
-                      &x_1 &    &            \\
{}                    & {} &    &x_2           \\
{}                    &x_1 &+2 &x_2           \\
3                     &x_1 &+3 &x_2           \\
{}                   & {} &+4 &x_2           \\
{}  13             &x_1  &+5 &x_2           \\
- 6                 &x_1 &+6 &x_2           \\
-\frac{3}{2}    &x_1 &+7 &x_2           \\
-12                &x_1 &+8 &x_2           \\
\end{array}$

\end{document}

A: This is only a partial solution because I don't know how to treat the sign of the second column if the number is not a number but a math expression (for example if you have -\fraq{...}{...} in the second column).
However, I think it could be useful to you.
With \pgfplotstablemodifyeachcolumnelement and etoolbox I have modified the column values:
\documentclass[border=5pt, varwidth]{standalone}
\usepackage{etoolbox}
\usepackage{pgfplotstable, systeme}
\pgfplotsset{compat=1.13}

\pgfplotstableset{
string type,
every head row/.style={output empty row},
column type=r,%
%postproc cell content/.append style={
%/pgfplots/table/@cell content/.add={$}{$},
%},%
}

\begin{document}
\pgfplotstableread{
x                    y
-1                   0
0                    1
1                    2
3                    3
0                    4
13                  5
-6                   6
-\frac{3}{2}    7
-12                 8
}\test

\newcommand{\firstvar}{x_1}
\newcommand{\secondvar}{x_2}
\pgfplotstablemodifyeachcolumnelement{x}\of\test\as\cell{%
\edef\cell{% code from https://tex.stackexchange.com/questions/24922/comparing-an-argument-to-a-string-when-argument-is-a-result-of-a-command-with-et
 \expandafter\ifstrequal\expandafter{\cell}{0}{}{\expandafter\ifstrequal\expandafter{%
        \cell}{-1}{$-\firstvar$}{%
        \expandafter\ifstrequal\expandafter{\cell}{1}{$\firstvar$}{$\cell\firstvar$}%
}}}
}
\pgfplotstablemodifyeachcolumnelement{y}\of\test\as\cell{%
\edef\cell{% this part is to improve to correctly manage the negative value
 \expandafter\ifstrequal\expandafter{\cell}{0}{}{\expandafter\ifstrequal\expandafter{%
        \cell}{-1}{$-\secondvar$}{%
        \expandafter\ifstrequal\expandafter{\cell}{1}{$+\secondvar$}{$+\cell\secondvar$}%
}}}
}
\pgfplotstabletypeset{\test}
\end{document}


text:
Q: Evaluate the infinite union and infinite intersection of $\left[\dfrac{1}{n},n\right]$.
I need help evaluating the infinite union and infinite intersection of $\left[\dfrac{1}{n},n\right]$ such that $n\in\Bbb N^+$.

I've been working for hours trying to figure out how to do this and I'm still not certain I understand this, but I think I might have gotten it.
My understanding says that

*

*$\displaystyle\bigcup_{n=1}^\infty\left[\frac{1}{n},n\right]=(0,\infty)$.
In this case, we want to identify the largest interval which $\left[\dfrac{1}{n},n\right]$ can produce.

*$\displaystyle\bigcap_{n=1}^\infty\left[\frac{1}{n},n\right]=\{1\}$. In this case, we want to identify the interval which is included in every interval that $\left[\dfrac{1}{n},n\right]$ produces.
Please tell me if my reasoning is sound and also can you show me how to justify my evaluation. My professor says that "For a complete description of the union one has to determine not only which elements are in the union but also which elements are not in the union. How one breaks into case to consider depends on the sets which one is given", and I do not understand what this means.
Thank you

A: The intersection is not $1$ but is $\{1\}$.
For proving that the union is $(0,\infty)$ you must show that for every positive $r$ we can find a positive integer that satisfies $1/n\leq r\leq n$ and secondly that $[1/n,n]\subseteq(0,\infty)$ for every positive integer $n$.
The first action shows that $(0,\infty)\subseteq\bigcup_{n=1}^{\infty}[1/n,n]$.
The second action shows that $\bigcup_{n=1}^{\infty}[1/n,n]\subseteq(0,\infty)$.

For proving that the intersection is $\{1\}$ it is enough to prove that $1\in[1/n,n]$ for each positive integer $n$ and secondly that it is unique in having this property. This uniqueness becomes evident if you concern the case $n=1$.
The first action shows that $\{1\}\subseteq\bigcap_{n=1}^{\infty}[1/n,n]$.
The second action shows that $\bigcap_{n=1}^{\infty}[1/n,n]\subseteq\{1\}$.


text:
Q: NGINX Proxy pass keep wrong redirect port First, would like to apologize to post this. I am already searching this issue, try and error but still didn't get answers. Please dont mad at me.
Ok here is my single config file:
upstream app-backend {
        server 172.23.2.143:9080 weight=1 max_fails=2 fail_timeout=10s;
        server 172.23.2.144:9080 weight=1 max_fails=2 fail_timeout=10s;
}

server {
    listen 12001 ssl;
    server_name test.abc.com;
    error_page  497 https://test.abc.com:12001$request_uri;
    include /usr/local/openresty/nginx/conf/tls/ssl.conf;

    location / {
        proxy_pass http://app-backend;
        proxy_set_header Host $host;
      }
}

So the problem is,
when i access my main domain which is and do some login (POST) :
https://test.abc.com:12001/login.jsp which is will redirect to one of the upstream with same path,
it throw me to http://test.abc.com:9080/home.detail which is this site
did not exist and i get message on browser this site cannot be reached
The question is, why this redirect to port 9080 which is belongs to backend port. i dont know what to do anymore. i just really need help and direction. Please

A: i am solving above case with this configuration.
proxy_cache_path /tmp/NGINX_cache/ keys_zone=backcache:10m;

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream app-backend {
       ip_hash;
       server 172.22.8.143:9080 weight=1 max_fails=2 fail_timeout=10s;
       server 172.22.8.144:9080 weight=1 max_fails=2 fail_timeout=10s;
}

server {
    listen 9080 ssl;
    server_name test.abc.com;
    error_page  497 https://test.abc.com:9080$request_uri;
    include /usr/local/openresty/nginx/conf/tls/ssl.conf;

    location / {
        proxy_pass http://app-backend;
        proxy_set_header   Host  $http_host;
        proxy_cache backcache;
      }

}


text:
Q: Why isn't my search with Control Parameters returning integer values? I am searching a grid view using control parameters, but in my code I search only for text instead of integer values.
How can I search for integer values using control parameters?
My code is:
   <%@ Page Language="VB" AutoEventWireup="false" CodeFile="GridviewwithHighlightedSearch.aspx.vb"
Inherits="GridviewwithHighlightedSearch" MasterPageFile="~/Default.master" %>

  <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderMain" runat="Server">

  <form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager" runat="server" />
  <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>

            Gridview with Highlighted Search

                Search for a person :
                <asp:TextBox ID="txtSearch" runat="server" />
                <asp:ImageButton ID="btnSearch" ImageUrl="images/searchbutton.png" runat="server"
                    Style="top: 5px; position: relative" />
                <asp:ImageButton ID="btnClear" ImageUrl="images/clearbutton.png" runat="server" Style="top: 5px;
                    position: relative" />

            <asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                AllowSorting="true" DataSourceID="dsGridview" Width="540px" PageSize="10" CssClass="Gridview">
                <Columns>
                    <asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" ItemStyle-Width="40px"
                        ItemStyle-HorizontalAlign="Center" />
                    <asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
                        <ItemStyle Width="120px" HorizontalAlign="Left" />
                        <ItemTemplate>
                            <asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("FirstName")) %>' runat="server"
                                CssClass="TextField" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
                        <ItemStyle Width="120px" HorizontalAlign="Left" />
                        <ItemTemplate>
                            <asp:Label ID="lblLastname" Text='<%# HighlightText(Eval("LastName")) %>' runat="server"
                                CssClass="TextField" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department"
                        ItemStyle-Width="130px" />
                    <asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location"
                        ItemStyle-Width="130px" />
                </Columns>
            </asp:GridView>

    </ContentTemplate>
</asp:UpdatePanel>

Download Source Code
<asp:SqlDataSource ID="dsGridview" runat="server" ConnectionString="<%$ ConnectionStrings:EvonetConnectionString %>"
    SelectCommand="SELECT * FROM [T_Employees]" FilterExpression="firstname like '%{0}%' or lastname like '%{1}%'">
    <FilterParameters>
        <asp:ControlParameter Name="firstname" ControlID="txtSearch" PropertyName="Text" />
        <asp:ControlParameter Name="lastname" ControlID="txtSearch" PropertyName="Text" />
    </FilterParameters>
</asp:SqlDataSource>
</form>
</asp:Content>

A: You could just add another OR condition to your filter to match the integer column and add the appropriate filter parameter...is that what you mean?
<asp:SqlDataSource
    ID="dsGridview"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:EvonetConnectionString %>"
    SelectCommand="SELECT * FROM [T_Employees]"
    FilterExpression="firstname like '%{0}%' or lastname like '%{1}%' or IntColumn = '{2}'">
    <FilterParameters>
        <asp:ControlParameter Name="firstname" ControlID="txtSearch" PropertyName="Text" />
        <asp:ControlParameter Name="lastname" ControlID="txtSearch" PropertyName="Text" />
        <asp:ControlParameter Name="IntColumn" ControlID="txtSearch" PropertyName="Text" />
    </FilterParameters>
</asp:SqlDataSource>

The important thing to note is that you cannot use like on an integer column...well not without casting it first I guess.


text:
Q: How can I have Safari on OS X remember to permanently trust a website with my current location? The only options on the location privacy prompt are 'Allow' or 'Don't Allow', with a 'Remember my decision for one day' modifier checkbox as well. But what if there's a site that I trust in perpetuity? I want to give it permission to access my location forever. Why can't I do that?
Safari 8.0 on Mac OS X 10.10 Yosemite

A:
But what if there's a site that I trust in perpetuity?

If you want to trust a site in perpetuity check "Prompt for each website one time only" in Settings>Privacy, visit the site, in the sheet that appears check the option "Remember my decision and don't ask me again" and click the Allow button:

If you get prompted to allow Safari to use your location, press the OK button:

Note that the Cookies and Website Data>Details section in Safari:

doesn't mention whether a specific site can access your location information:

so you might lose track of which sites you allowed.
For more information visit this article: http://support.apple.com/en-us/HT5403


text:
Q: Using a value from a matrix as a multiplier in an equation? Started using MatLab a couple of weeks ago, I don't know much proper syntax / terminology.
I'm trying to use a value in a 3x1 matrix as a multiplier in an equation later.
This is to draw a circle with radius and centre point defined by values input by the user.
I have a pop-up window, the values are input by the user and stored in this 3x1 cell (labelled answer).
How do I use the second value of that matrix, answer(2), in the following equation:
x = 'answer(2)' * cos(theta) + xCentre;
This error message appears:
Error using  .*
Matrix dimensions must agree.

Error in Disks (line 40)
x = 'answer(2)'.* cos(theta) + xCentre;

A: In MATLAB, apostrophes ('') define a string. If the name of your matrix is answer, you can refer to its second value by the command answer(2) as mentioned by @Schorsch. For more infos on vectors and matrices, you can check this site.

A: In addition to what the previous answer says, its important to understand what exactly you are doing before you do it. Only add the ('') if you are defining a string, which generally occurs when dealing with variables. In your case, you simply have a matrix, which is not a string, but rather a set of numbers. You can simply do answer(2) as aforementioned, because answer(2) calls up the second value in your matrix while 'answer(2)' has you trying to define some variable that does not exist.
the most important thing is truly understanding what you are doing to avoid the basic syntax errors.


text:
Q: PL/SQL Comparing bit strings, I need an AND operation? I currently have a script that calculates the tanimoto coefficient on the fingerprints of a chemical library. However during testing I found my implementation could not be feasibly scaled up due to my method of comparing the bit strings (It just takes far too long). See below. This is the loop I need to improve. I've simplified this so it is just looking at two structures the real script does permutations about the dataset of structures, but that would over complicate the issue I have here.
LOOP
-- Find the NA bit
SELECT SUBSTR(qsar_kb.fingerprint.fingerprint, var_fragment_id ,1) INTO var_na FROM qsar_kb.fingerprint where project_id = 1 AND structure_id = 1;

-- FIND the NB bit
SELECT SUBSTR(qsar_kb.fingerprint.fingerprint, var_fragment_id ,1) INTO var_nb FROM qsar_kb.fingerprint where project_id = 1 AND structure_id = 2;

-- Test for both bits the same
IF var_na > 0 AND var_nb > 0 then
var_tally := var_tally + 1;
END IF;

-- Test for bit in A on and B off
IF var_na > var_nb then
var_tna := var_tna + 1;
END IF

-- Test for bit in B on and A off.
IF var_nb > var_na then
var_tnb := var_tnb + 1;
END IF;

var_fragment_id := var_fragment_id + 1;
EXIT WHEN var_fragment_id > var_maxfragment_id;
END LOOP;

For a simple example
Structure A = '101010'
Structure B = '011001'
In my real data set the length of the binary is 500 bits and up.
I need to know:
1)The number of bits ON common to Both
2)The number of bits ON in A but off in B
3)The number of bits ON in B but off in B
So in this case
1) = 1
2) = 2
3) = 2
Ideally I want to change how I'm doing this. I don't want to be steeping though each bit in each string its just too time expensive when I scale the whole system up with thousands of structures each with fingerprint bit strings in the length order of 500-1000
My logic to fix this would be to:
Take the total number of bits ON in both
A) = 3
B) = 3
Then perform an AND operation and find how many bits are on in both
= 1
Then just subtract this from the totals to find the number of bits on in one but not the other.
So how can I perform an AND like operation on two strings of 0's and 1's to find the number of common 1's?

A: Check out the BITAND function.

The BITAND function treats its inputs and its output as vectors of bits; the output is the bitwise AND of the inputs.

However, according to the documentation, this only works for 2^128

A: You should move the SELECT out of the loop. I'm pretty sure you're spending 99% of the time selecting 1 bit 500 times where you could select 500 bits in one go and then loop through the string:
DECLARE
   l_structure_a LONG;
   l_structure_b LONG;
   var_na        VARCHAR2(1);
   var_nb        VARCHAR2(1);
BEGIN
   SELECT MAX(decode(structure_id, 1, fingerprint)),
          MAX(decode(structure_id, 2, fingerprint))
     INTO l_structure_a, l_structure_b
     FROM qsar_kb.fingerprint
    WHERE project_id = 1
      AND structure_id IN (1,2);
   LOOP
      var_na := substr(l_structure_a, var_fragment_id, 1);
      var_nb := substr(l_structure_b, var_fragment_id, 1);

      -- Test for both bits the same
      IF var_na > 0 AND var_nb > 0 THEN
         var_tally := var_tally + 1;
      END IF;
      -- Test for bit in A on and B off
      IF var_na > var_nb THEN
         var_tna := var_tna + 1;
      END IF;
      -- Test for bit in B on and A off.
      IF var_nb > var_na THEN
         var_tnb := var_tnb + 1;
      END IF;

      var_fragment_id := var_fragment_id + 1;
      EXIT WHEN var_fragment_id > var_maxfragment_id;
   END LOOP;
END;

Edit:
You could also do it in a single SQL statement:
SQL> WITH DATA AS (
  2     SELECT '101010' fingerprint,1 project_id, 1 structure_id FROM dual
  3     UNION ALL SELECT '011001', 1, 2 FROM dual),
  4  transpose AS (SELECT ROWNUM fragment_id FROM dual CONNECT BY LEVEL <= 1000)
  5  SELECT COUNT(CASE WHEN var_na = 1 AND var_nb = 1 THEN 1 END) nb_1,
  6         COUNT(CASE WHEN var_na > var_nb THEN 1 END) nb_2,
  7         COUNT(CASE WHEN var_na < var_nb THEN 1 END) nb_3
  8    FROM (SELECT to_number(substr(struct_a, fragment_id, 1)) var_na,
  9                 to_number(substr(struct_b, fragment_id, 1)) var_nb
 10             FROM (SELECT MAX(decode(structure_id, 1, fingerprint)) struct_a,
 11                           MAX(decode(structure_id, 2, fingerprint)) struct_b
 12                      FROM DATA
 13                     WHERE project_id = 1
 14                       AND structure_id IN (1, 2))
 15            CROSS JOIN transpose);

      NB_1       NB_2       NB_3
---------- ---------- ----------
         1          2          2

A: I'll sort of expand on the answer from Lukas with a little bit more information.
A little bit of an internet search revealed code from Tom Kyte (via Jonathan Lewis) to convert between bases. There is a function to_dec which will take a string and convert it to a number. I have reproduced the code below:
Convert base number to decimal:
create or replace function to_dec(
  p_str in varchar2,
  p_from_base in number default 16) return number
is
    l_num   number default 0;
    l_hex   varchar2(16) default '0123456789ABCDEF';
begin
    for i in 1 .. length(p_str) loop
        l_num := l_num * p_from_base + instr(l_hex,upper(substr(p_str,i,1)))-1;
    end loop;
    return l_num;
end to_dec;

Convert decimal to base number:
create or replace function to_base( p_dec in number, p_base in number )
return varchar2
is
    l_str   varchar2(255) default NULL;
    l_num   number  default p_dec;
    l_hex   varchar2(16) default '0123456789ABCDEF';
begin
    if ( trunc(p_dec) <> p_dec OR p_dec < 0 ) then
        raise PROGRAM_ERROR;
    end if;
    loop
        l_str := substr( l_hex, mod(l_num,p_base)+1, 1 ) || l_str;
        l_num := trunc( l_num/p_base );
        exit when ( l_num = 0 );
    end loop;
    return l_str;
end to_base;

This function can be called to convert the string bitmap into a number which can then be used with bitand. An example of this would be:
select to_dec('101010', 2) from dual

Oracle only really provides BITAND (and BIT_TO_NUM which isn't really relevant here` as a way of doing logical operations but the operations required here are (A AND B), (A AND NOT B) and (NOT A AND B). So we need a var of converting A to NOT A. A simple way of doing this is to use translate.
So.... the final outcome is:
select
  length(translate(to_base(bitand(data_A, data_B),2),'10','1')) as nb_1,
  length(translate(to_base(bitand(data_A, data_NOT_B),2),'10','1'))  as nb_2,
  length(translate(to_base(bitand(data_NOT_A, data_B),2),'10','1'))  as nb_3
from (
  select
    to_dec(data_A,2) as data_A,
    to_dec(data_b,2) as data_B,
    to_dec(translate(data_A, '01', '10'),2) as data_NOT_A,
    to_dec(translate(data_B, '01', '10'),2) as data_NOT_B
  from (
    select '101010' as data_A, '011001' as data_B from dual
  )
)

This is somewhat more complicated than I was hoping when I started writing this answer but it does seem to work.

A: Can be done pretty simply with something like this:
SELECT utl_raw.BIT_AND( t.A, t.B )                                                 SET_IN_A_AND_B,
       length(replace(utl_raw.BIT_AND( t.A, t.B ), '0', ''))                       SET_IN_A_AND_B_COUNT,
       utl_raw.BIT_AND( t.A, utl_raw.bit_complement(t.B) )                         ONLY_SET_IN_A,
       length(replace(utl_raw.BIT_AND( t.A, utl_raw.bit_complement(t.B) ),'0','')) ONLY_SET_IN_A_COUNT,
       utl_raw.BIT_AND( t.B, utl_raw.bit_complement(t.A) )                         ONLY_SET_IN_A,
       length(replace(utl_raw.BIT_AND( t.B, utl_raw.bit_complement(t.A) ),'0','')) ONLY_SET_IN_A_COUNT
  FROM (SELECT '1111100000111110101010' A, '1101011010101010100101' B FROM dual) t

Make sure your bit string has an even length (just pad it with a zero if it has an odd length).


text:
Q: Предупреждение x509 при билде образа с Dockerfile При попытки сбилдить образ выводится данное предупреждение:
Step 1/17: FROM mcr.microsoft.com/dotnet/aspnet:2.2
Trying to pull repository mcr.microsoft.com/dotnet/aspnet ...
Get https://mcr.microsoft.com/v1/_ping: x509: certificate signed by unknown authority

Я пробовал перезапускать Docker, также обновлять сертификаты посредством комманды update-ca-trust, но это ничего не дало, проблема не устранилась. Что можно сделать чтобы образ сбилдился без данной проблемы?


text:
Q: C# Json.NET - json to c# object I have the following json which I am trying to convert into a C# object using json.net.
{
    "torrents": [
        [
            "03FE02E76D99D94B9FF7689080F168C70BC2A3B7",
            136, "02 - Aleph One.mp3", 98206320,
            0, 0, 0, 0, 0, 0, 0, "",
            0, 0, 0, 0, 0, 2, 98206320,
            "", "", "Stopped 0.0 %", "4",
            1427414173, 0, "", "D:\\downloading",
            0, "481B6500"
        ],
        [
            "6D5A14A99970EF0366F69BF21BD6633D19F8C80C",
             128, "01 - Infinity Mix 1.mp3", 279245285,
             0, 212992, 0, 0, 0, 0, 0, "",
             0, 0, 0, 0, 0, 1, 279032293,
             "", "", "Stopped 0.0 %", "3",
             1427414139, 0, "", "D:\\downloading",
             0, "C32DD134"
        ]
    ]
}

I have the following code, I am not sure why it is not working, maybe someone could point me in the right direction.
The error message I am getting is: "Object reference not set to an instance of an object."
var ds = JsonConvert.DeserializeObject<TorrentList>(json);
MessageBox.Show(ds.Torrents[0].Name);

.
public class TorrentList
{
    public Torrent[] Torrents { get; set; }
}

[JsonConverter(typeof (TorrentJsonConverter))]
public class Torrent
{
    public String Hash { get; set; }
    public int Status { get; set; }
    public String Name { get; set; }
    public int Size { get; set; }
    public int Progress { get; set; }
    public int Downloaded { get; set; }
    public int Uploaded { get; set; }
    public int Ratio { get; set; }
    public int UploadSpeed { get; set; }
    public int DownloadSpeed { get; set; }
    public int Eta { get; set; }
    public String Label { get; set; }
    public int PeersConnected { get; set; }
    public int PeersInSwarm { get; set; }
    public int SeedsConnected { get; set; }
    public int SeedsInSwarm { get; set; }
    public int Availability { get; set; }
    public int TorrentOrder { get; set; }
    public int Remaining { get; set; }
    public String Unknown1 { get; set; }
    public String Unknown2 { get; set; }
    public String CurrentStatus { get; set; }
    public String Unknown3 { get; set; }
    public int Unknown4 { get; set; }
    public int Unknown5 { get; set; }
    public String Unknown6 { get; set; }
    public String FilePath { get; set; }
    public int Unknown7 { get; set; }
    public String Unknown8 { get; set; }
}

internal class TorrentJsonConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var obj = new Torrent
        {
            Hash = reader.ReadAsString(),
            Status = reader.ReadAsInt32().GetValueOrDefault(),
            Name = reader.ReadAsString(),
            Size = reader.ReadAsInt32().GetValueOrDefault(),
            Progress = reader.ReadAsInt32().GetValueOrDefault(),
            Downloaded = reader.ReadAsInt32().GetValueOrDefault(),
            Uploaded = reader.ReadAsInt32().GetValueOrDefault(),
            Ratio = reader.ReadAsInt32().GetValueOrDefault(),
            UploadSpeed = reader.ReadAsInt32().GetValueOrDefault(),
            DownloadSpeed = reader.ReadAsInt32().GetValueOrDefault(),
            Eta = reader.ReadAsInt32().GetValueOrDefault(),
            Label = reader.ReadAsString(),
            PeersConnected = reader.ReadAsInt32().GetValueOrDefault(),
            PeersInSwarm = reader.ReadAsInt32().GetValueOrDefault(),
            SeedsConnected = reader.ReadAsInt32().GetValueOrDefault(),
            SeedsInSwarm = reader.ReadAsInt32().GetValueOrDefault(),
            Availability = reader.ReadAsInt32().GetValueOrDefault(),
            TorrentOrder = reader.ReadAsInt32().GetValueOrDefault(),
            Remaining = reader.ReadAsInt32().GetValueOrDefault(),
            Unknown1 = reader.ReadAsString(),
            Unknown2 = reader.ReadAsString(),
            CurrentStatus = reader.ReadAsString(),
            Unknown3 = reader.ReadAsString(),
            Unknown4 = reader.ReadAsInt32().GetValueOrDefault(),
            Unknown5 = reader.ReadAsInt32().GetValueOrDefault(),
            Unknown6 = reader.ReadAsString(),
            FilePath = reader.ReadAsString(),
            Unknown7 = reader.ReadAsInt32().GetValueOrDefault(),
            Unknown8 = reader.ReadAsString()
        };
        reader.Read();
        return obj;
    }

A: Add a null check here, Probably your Items are null,
if(ds != null)
{
   if(ds.count > 0 )
    {
      if(ds.Torrents.count > 0)
       {
      MessageBox.Show(ds.Torrents[0].Name);
       }
   }
}


text:
Q: JavaFx handle dragging nodes from FXML controller of node or main? I am trying to drag some custom nodes. These nodes are added as children to an AnchorPane, as defined in the Controller of the root FXML:
package sample;

import ...

public class Controller {
    @FXML
    AnchorPane anchorPane;

    public void add() {
        try {
            // Node.fxml is the custom node object
            Parent root = FXMLLoader.load(getClass().getResource("Node.fxml"));
            anchorPane.getChildren().add(root);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Should I handle my node dragging within the root FXML controller or within the FXML controller of the draggable node itself?
If I should do it within the root FXML controller, how do I do this? Calling FXMLLoader.Load() just references an FXML file, and so I can't attach mouse events to it.
I'm pretty new to Java and JavaFx, so anything is helpful. (not a beginner to programming, however).
Thanks in advance.

A: Thanks to @fabian and @Gikkman I figured out a solution to my problem.
My error was not understanding that Parent extends Node -- I had assumed that I needed to reference something else.
To implement the dragging functionality that I wanted, I created a function that has a Node input variable (thanks @Gikkman) - this Node object can then have event handlers attached to it. Since Parent extends Node (which I didn't realise), I can easily use the FXMLLoader.Load() as input.
So I then have:
package sample;

import ...

import java.io.IOException;

public class Controller {
    @FXML
    AnchorPane anchorPane;

    public void add() {
        try {
            // Node.fxml is the custom node object
            Parent root = FXMLLoader.load(getClass().getResource("Node.fxml"));
            // Sets the EventHandlers for dragging
            dragNode(root);
            // Adds the node to the scene
            anchorPane.getChildren().add(root);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Handles all dragging EventHandlers for any node object
    public void dragNode(Node node) {
        // Custom object to hold x and y positions
        final Delta dragDelta = new Delta();

        node.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                dragDelta.x = node.getLayoutX() - mouseEvent.getSceneX();
                dragDelta.y = node.getLayoutY() - mouseEvent.getSceneY();
            }
        });

        node.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                node.setCursor(Cursor.HAND);
            }
        });

        node.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                node.setLayoutX(mouseEvent.getSceneX() + dragDelta.x);
                node.setLayoutY(mouseEvent.getSceneY() + dragDelta.y);
            }
        });

        node.setOnMouseEntered(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                node.setCursor(Cursor.HAND);
            }
        });
    }

    class Delta { double x, y; }
}


text:
Q: Include Entry node in AQL Graph traversal I'm using AQL to traverse through Graphs, right now that's my statement:
FOR v, e, p IN 1..1 ANY 'Bridges/1004'
    GRAPH 'S_Graph'
    FILTER not (p.vertices[1].IID != 'null' AND p.vertices[1].cls_name == "Bridge")
    OR p.vertices[1].cls_name == "Node"
    RETURN v

And the result are the Documents my Entry-Document Bridges/1004, but not the Entry-Document itself.
How is it possible to include the Entry-Document in the Query-Result?

A: Just change the traversal depth from 1..1 to 0..1 and that should include the initial node.
FOR v, e, p IN 0..1 ANY 'Bridges/1004'
GRAPH 'S_Graph'
FILTER not (p.vertices[1].IID != 'null' AND p.vertices[1].cls_name == "Bridge")
OR p.vertices[1].cls_name == "Node"
RETURN v

Also  note that in your original query, if you return the path, it does include all the nodes in the path including the original node


text:
Q: Python: TypeError: __init__() takes exactly 2 arguments (1 given) I know this question has been asked several times, but none have managed to provide me with a solution to my issue. I read these:
__init__() takes exactly 2 arguments (1 given)?
class __init__() takes exactly 2 arguments (1 given)
All I am trying to do is create two classes for a "survival game" much like a very crappy version of minecraft. Bellow is the full code for the two classes:
class Player:
    '''
    Actions directly relating to the player/character.
    '''
    def __init__(self, name):
        self.name = name
        self.health = 10
        self.shelter = False

    def eat(self, food):
        self.food = Food
        if (food == 'apple'):
            Food().apple()

        elif (food == 'pork'):
            Food().pork()

        elif (food == 'beef'):
            Food().beef()

        elif (food == 'stew'):
            Food().stew()

class Food:
    '''
    Available foods and their properties.
    '''
    player = Player()

    def __init__(self):
        useless = 1
        Amount.apple = 0
        Amount.pork = 0
        Amount.beef = 0
        Amount.stew = 0

    class Amount:
        def apple(self):
            player.health += 10

        def pork(self):
            player.health += 20

        def beef(self):
            player.health += 30

        def stew(self):
            player.health += 25

And now for the full error:
Traceback (most recent call last):
  File    "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe  s.py", line 26, in <module>
    class Food:
  File     "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe    s.py", line 30, in Food
    player = Player()
TypeError: __init__() takes exactly 2 arguments (1 given)

I just want to make the classes work.

A: The code you used is as follows:
player = Player()

This is an issue since the __init__ must be supplied by one parameter called name according to your code. Therefore, to solve your issue, just supply a name to the Player constructor and you are all set:
player = Player('sdfasf')

A: The problem is that the Class Player's __init__ function accepts a name argument while you are initializing the Class instance. The first argument, self is automatically handled when you create a class instance. So you have to change
player = Player()

to
player = Player('somename')

to get the program up and running.

A: __init__() is the function called when the class is instantiated. So, any arguments required by __init__ need to be passed when creating an instance. So, instead of
player = Player()

use
player = Player("George")

The first argument is the implicit self, which doesn't need to be included when instantiating. name, however, is required. You were getting the error because you weren't including it.

A: Your code know expects that you input something in __init__ which you don't.
I have made a simple example below that does give you an idea where the error __init__() takes exactly 2 arguments (1 given) is coming from.
What I did is I made a definition where I give input to useless.
And I am calling that definition from __init__.
Example code:
class HelloWorld():
    def __init__(self):
        self.useThis(1)
    def useThis(self, useless):
        self.useless = useless
        print(useless)

# Run class
HelloWorld()

If you have a definition like def exampleOne(self) it doesn't expect any input. It just looks a t itself.  But def exampleTwo(self, hello, world) expects two inputs.
So to call these two you need:
self.exampleOne()
self.exampleTwo('input1', 'input2')


text:
Q: getPackage() returning null when my JUnit test is run from Ant I'm having problems running a JUnit test.
It runs fine in Eclipse, but now I'm trying to run it from the command-line using Ant. The problem is that the following code is returning null: getClass().getPackage().
I'm running my JUnit test like so:
    <junit fork="no" printsummary="yes" haltonfailure="no">
        <classpath refid="junit.classpath" />
        <batchtest fork="yes" todir="${reports.junit}">
            <fileset dir="${junit.classdir}">
                <include name="**/FileHttpServerTest.class" />
                <exclude name="**/*$*" />
            </fileset>
        </batchtest>
        <formatter type="xml" />
        ...

I Googled for this sort of error, and found a number of references to classloader misbehaviour. But I've found nothing gave me enough information to solve my problem.
I really need getClass().getPackage() to not return null. Can anyone help me?
Thanks,
Phil

A: I am not sure on which object are you trying to do getClass().getPackage()?
Looking at what the API Javadoc says for this method, I would guess that the issue is JUnit is being loaded by Bootstrap classloader when you are running it from command line whereas the object on which you are doing getPackage() operation is loaded by one of the child classloaders.
Not sure if this makes sense, but because getPackage is trying to locate the package using Bootstrap classloader and standard class loader behavior does not look at its children, it returns null.
If you can give more idea about the object on which you are doing this operation, I could be more specific

A: Try running your tests with junit fork="yes", that will isolate your classloading pretty reasonably and may fix your problem.

A: If it's a classloader's fault, you can always load the same class using different classloader:
URLClassLoader cld = new URLClassLoader(new URL[] { urlsToClasses });
Class.forName(getClass().getName(), true, cld).getPackage();

The problem here is to figure out, how to find class path urls (urlsToClasses). I'm not familiar with JUnit classloaders, so you may try to cast Thread.currentThread().getContextClassLoader() to URLClassLoader to see if it could help you obtain that URLs.


text:
Q: sqlalchemy InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers I have the following tables using SQLAlchemy
#Sistema de escuelas por Jenifer
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

###############Creación de la base de datos #########################################
engine=create_engine('sqlite:///:memory:')
Base=declarative_base(engine)

class Estudiante(Base):
    __tablename__="alumno"
    id=Column(Integer,Sequence('alumno_seq_id'),primary_key=True)
    cedula_identidad=Column(String)
    nombre_alumno=Column(String)
    apellido_alumno=Column(String)
    curso_idAlumno=Column(Integer,ForeignKey('curso.id'))

    cursos=relationship("Curso",back_populates='estudiantes')
    #cursos=relationship("Curso",back_populates='alumno')
    def __repr__(self):
        return'{}{}'.format(self.nombre_alumno, self.apellido_alumno)

class Curso(Base):
    __tablename__='curso'
    id=Column(Integer, Sequence('curso_seq_id'),primary_key=True)
    nombre_curso=Column(String)

    estudiantes=relationship("Estudiante",back_populates='curso')
    hora_curso=relationship("Horarios",back_populates='curso_hora')
    def __repr__(self):
        return'{}'.format(self.nombre_curso)

class Horarios(Base):
    __tablename__='horario'
    id=Column(Integer, Sequence('horario_seq_id'),primary_key=True)
    dia=Column(String)
    hora_inicio=Column(String)
    hora_fin=Column(String)
    profesor_id=Column(Integer,ForeignKey('profesor.id'))
    curso_id=Column(Integer,ForeignKey('curso.id'))

    curso_hora=relationship("Curso",back_populates='hora_curso')
    curso_profe=relationship("Profesor",back_populates='profe_curso')

    def __repr__(self):
        return'{}{}{}'.format(self.dia,self.hora_inicio, self.hora_fin,\
        self.cedula_identidad)

class Profesor(Base):
    __tablename__='profesor'
    id=Column(Integer, Sequence('profesor_seq_id'),primary_key=True)
    cedula_identidad=Column(String)
    nombre_profesor=Column(String)
    apellido_profesor=Column(String)

    profe_curso=relationship("Horarios",back_populates='curso_profe')
    def __repr__(self):
        return'{}{}{}'.format(self.nombre_profesor, self.apellido_profesor,
        self.cedula_identidad)

Profesor.__table__
Estudiante.__table__
Curso.__table__
Horarios.__table__
Base.metadata.create_all(engine)

And the following function to preload data:
def precargarDatos(ses):
###############ESTUDINTES##################################################
    alumno1=Estudiante(nombre_alumno='Raton', apellido_alumno='Perez',
    cedula_identidad='1234567-8')
    alumno2=Estudiante(nombre_alumno='Hugo', apellido_alumno='Donald',\
    cedula_identidad='abcdef123')
    alumno3=Estudiante(nombre_alumno='Paco', apellido_alumno='Donald',\
    cedula_identidad='abcdef124')
    alumno4=Estudiante(nombre_alumno='Luis', apellido_alumno='Donald',\
    cedula_identidad='abcdef125')
    ses.add(alumno1)
    ses.add(alumno2)
    ses.add(alumno3)
    ses.add(alumno4)

The problem is that when I try to run this it gives me the following error:
InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Estudiante->alumno'. Original exception was: Mapper 'mapped class Curso->curso' has no property 'alumno'

This error rises when I try to assign alumno1 using the class Estudiante.
I've seen similar posts but I can't figure out what to change in my code, if the problem is the function or the definition of the tables.
If enyone can help me I will appreciate it

A: Thanks to @snakecharmberb I noticed the errors in the back_populates, the fields didn't match.
The code now:
class Estudiante(Base):
    __tablename__="alumno"
    id=Column(Integer,Sequence('alumno_seq_id'),primary_key=True)
    cedula_identidad=Column(String)
    nombre_alumno=Column(String)
    apellido_alumno=Column(String)
    curso_idAlumno=Column(Integer,ForeignKey('curso.id'))

    cursos=relationship("Curso",back_populates='estudiantes')

    def __repr__(self):
        return'{}{}'.format(self.nombre_alumno, self.apellido_alumno)

class Curso(Base):
    __tablename__='curso'
    id=Column(Integer, Sequence('curso_seq_id'),primary_key=True)
    nombre_curso=Column(String)

    estudiantes=relationship("Estudiante",back_populates='cursos')
    hora_curso=relationship("Horarios",back_populates='curso_hora')
    def __repr__(self):
        return'{}'.format(self.nombre_curso)

class Horarios(Base):
    __tablename__='horario'
    id=Column(Integer, Sequence('horario_seq_id'),primary_key=True)
    dia=Column(String)
    hora_inicio=Column(String)
    hora_fin=Column(String)
    profesor_id=Column(Integer,ForeignKey('profesor.id'))
    curso_id=Column(Integer,ForeignKey('curso.id'))

    curso_hora=relationship("Curso",back_populates='hora_curso')
    curso_profe=relationship("Profesor",back_populates='profe_curso')

    def __repr__(self):
        return'{}{}{}'.format(self.dia,self.hora_inicio, self.hora_fin,\
        self.cedula_identidad)

class Profesor(Base):
    __tablename__='profesor'
    id=Column(Integer, Sequence('profesor_seq_id'),primary_key=True)
    cedula_identidad=Column(String)
    nombre_profesor=Column(String)
    apellido_profesor=Column(String)

    profe_curso=relationship("Horarios",back_populates='curso_profe')
    def __repr__(self):
        return'{}{}{}'.format(self.nombre_profesor, self.apellido_profesor,
        self.cedula_identidad)

So thanks for your kindness

A: I'm using FastAPI and got the same issue.

If you guys using the same, maybe check what i've done to resolve this issue:

So it's because of wrong relation declaration in models.

The correct one is something like this:

class Book(Base):
    __tablename__ ="book"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)

    # relation
    bookmark = relationship("BookMark", back_populates="book")

class BookMark(Base):
    __tablename__ ="bookmark"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)
    book_id = Column(Integer, ForeignKey("book.id"), nullable=False)

    # relation
    book = relationship("Book", back_populates="bookmark")

It have to be declare relation in both table, if you missing one, then issue will appear.
Back there, i was missing the relation in Book table, so it causing the issue.
Hope this help.


text:
Q: My login codes validate my credentials ,but don't login I have MVC.Net C# Login page and I decided to make some fancy changes, and all of the sudden my login page stoped working.
I need your help , somebody else to look at my code and may be see what I couldn't find. during debugging, it returns all true but don't go into index page. What do you think ? what is my problem that I can't see!
Here is my controller:
// GET: /Account/Login

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}

//
// POST: /Account/Login
[HttpPost]
public ActionResult Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        if (model.IsUserExist(model.EMP_ID, model.EMP_PASSWORD))
        {
            FormsAuthentication.SetAuthCookie(model.EMP_ID, false);
        }
        else
        {
            ModelState.AddModelError("", "The User ID or Password provided is incorrect.");
        }
    }

    return View(model);
}

A: You are transferring it to any other view, you can use return RedirectToAction("Actionname","controllername","params if any");
// POST: /Account/Login
    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            if (model.IsUserExist(model.EMP_ID, model.EMP_PASSWORD))
            {
                FormsAuthentication.SetAuthCookie(model.EMP_ID, false);
                //change here
                return RedirectToAction("Actionname","controllername","params if any");

            }
            else
            {
                ModelState.AddModelError("", "The User ID or Password provided is incorrect.");
            }
        }

        return View(model);
    }


text:
Q: jQuery issue in Internet Explorer 8 I am trying to get my jQuery functions to work on IE8. I am loading the library from Google's servers (http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js).
The $(function(){}) is never called. Instead, I get an error Object expected. I opened the developer and ran typeof $ in the console, and it came up as undefined.
I have tried going to other sites that I know use jQuery (jquery.com), and those all work, is there something I might be missing here?

A: Some people stumbling on this post might get this issue with jquery and IE8 because they're using >= jQuery v2. Use this code:
<!--[if lt IE 9]>
    <script src="jquery-1.9.0.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="jquery-2.0.0.js"></script>
<!--<![endif]-->

A: jQuery is not being loaded, this is not likely specific to IE8. Check the path on your jQuery include. statement. Or better yet, use the following to the CDN:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js">
</script>

A: If you are using HTTPS on your site, you will need to load the jQuery library from Googles https server instead. Try this:
https://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js
(or the latest https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js)

A: I was fixing a template created by somebody else who forgot to include the doctype.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

If you don't declare the doctype IE8 does strange things in Quirks mode.

A: Write "var" before variables, when you define them. IE8 dies when there is no "var".

A: The onload event does not always work on IE7/8 in <head> ... </head>
You can force it by adding an onload script at the end of your page before the  tag as below.
  <script>
    window.onload();
  </script>
</body>

A: The error Object expected is raised because Jquery is not loaded. This happens because of browser security (usually IE) which does not allow you executing external javascript source code. You can correct this problem by:

*

*1: Changing browser security level to allow executing external javascript code.
You can find how to do this here
OR

*

*2: Copy-paste the jquery source code into your web page so that it won't be considered as an external script.

I prefer the first solution.

A: Correction:
Check your script include tag, is it using
type="application/javascript" src="/path/to/jquery"

change to
type="text/javascript" src="/path/to/jquery"

A: I was having a similar issue.  Things worked in IE6, Firefox, and IE8 running in IE7 compatibility mode; but not in 'normal' IE8.  My solution was to put this code in the header
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

As to why jquery isn't working in IE8 I'm unclear.

A: I had the same problems.
I solved it verifying that IE8 was not configured correctly to reach the SRC URL.
I changed this, it works right.

A: Maybe you insert two scripts,it should be work.
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js">/script>

A: This fixed my issue in IE8:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

Running on localhost, I had to change the https:// to http://
If I try to browse to the secure link, I get the Internet Explorer cannot display the webpage
friendly warning.
Always try to load your text scripts in a browswer first if there are issues!

A: The solution is to upgrade to the latest version of jQuery. I had the exact same problem and upgraded to 1.4.2 and it all works fine again in IE8.
Seems to be totally backwards-compatible with all the jQuery 1.3.2 stuff I did as well so no complaints here!

A: I had this problem and tried the solutions mentioned here with no success.
Eventually, I realised that I was linking to the Google CDN version of the script using an http URL while the page embedding the script was an https page.
This caused IE to not load jquery (it prompts the user whether they want to load only secure content). Changing the Google CDN URL to use the https scheme fixed the problem for me.

A: Maybe you have inPrivate Filtering turned on?

A: I had the same issue. The solution was to add the link to the JQuery file as a trusted site in IE.

A: I think that you have same problem as I do:
Message: Permission denied
Line: 13
Char: 27021
Code: 0
URI: http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.3.2.min.js

Because of cross domain reference. Try to host jquery.js on same domain.

A: OK! I know that jQuery is loading.  I know that jQuery.textshadow.js is loading.  I can find both of the scripts in Developer Tools.
The weird part: this code is working in the content area but not in the banner.  Even with a dedicated fixIE.css.  AND it works when I put the css inline. (That, of course, messes up FireFox.)
I have even put in a conditional IE span around the text field in the banner with no luck.
I found no difference and had the same errors in both jquery-1.4.2.min.js and jquery-1.2.6.min.js.  jquery.textshadow.js was downloaded from the jQuery site while trying to find a solution to this problem.
This is not posted to the Website

A: In short, it's because of the IE8 parsing engine.
Guess why Microsoft has trouble working with the new HTML5 tags (like "section") too? It's because MS decided that they will not use regular XML parsing, like the rest of the world. Yes, that's right - they did a ton of propaganda on XML but in the end, they fall back on a "stupid" parsing engine looking for "known tags" and messing stuff up when something new comes around.
Same goes for IE8 and the jquery issue with "load", "get" and "post". Again, Microsoft decided to "walk their own path" with version 8. Hoping that they solve(d) this in IE9, the only current option is to fall back on IE7 parsing with <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />.
Oh well... what a surprise that Microsoft made us post stuff on forums again. ;)

A: The solution in my case was to take any special characters out of the URL you're trying to access. I had a tilde (~) and a percentage symbol in there, and the $.get() call failed silently.


text:
Q: RetrieveSalesforceObjects to retrieve lead records based on email submit Trying to retrieve lead object record based on email to pre fill the textbox when submitted. I can't seem to find any examples of "RetrieveSalesforceObjects ". can someone please point me in the right direction for the code below:

%%[ var @rs
set @Email = QueryParameter("emailaddress")
Set @rs= RetrieveSalesforceObjects('Lead', 'Id, FirstName,LastName', 'Email', '=', @Email)
Set @row = ROW(@rs,1)
Set @Id = FIELD(@row,"Id")
]%%

         <form action="http://example.com/" method="POST" target='_parent'>
   <input type="hidden" id="p" name="p" value="y">
   <input type="hidden" id="rid" name="rid" value = "%%=v(@Id)=%%" />
   <input type="hidden" id="SubmitDate" name="SubmitDate" value="%%=Now()=%%">

                    First Name

                      <input  type="text" id="firstname" name="firstname"  value = "%%=v(@FirstName)=%%" />

                    Last Name*

                    <input type="text" id="lastname" name = "lastname" value = "%%=v(@LastName)=%%" required />

                    Email*

                        <input type="email" id="emailaddress" name = "emailaddress"  value = "%%=v(@Email)=%%" required/>

                    Mobile Phone*

                        <input type="tel" id="mobilephone" name = "mobilephone" value = "%%=v(@MobilePhone)=%%"   required/>

                   <input type="checkbox" name="Email_Opt_in" id="Email_Opt_in" value="True"> Durham College values the opportunity to provide you with information. Please click here to allow us to continue to contact you via email.

                  <input type="submit" value="Submit">
  </form>

A: A few pointers -
1) Define all Variables
2) Retrieve the data from the resultset.
3) Display in the form
See code snippet below. P.S. Added Null Check too :)
%%[ var @rs, @Email, @row, @Id, @Fname, @Lname
set @Email = QueryParameter("emailaddress")
Set @rs= RetrieveSalesforceObjects('Lead', 'Id, FirstName,LastName', 'Email', '=', @Email)

// Null check
IF NOT Empty(@rs) THEN
    Set @row = ROW(@rs,1)
    Set @Id = FIELD(@row,"Id")
    Set @Fname = FIELD(@row,"FirstName")
    Set @Lname = FIELD(@row,"LastName")
ENDIF

Use %%=v(@Fname)=%% & %%=v(@Lname)=%% within HTML tags to display the relevant values.

A: Just to update the above and answer the comment from garek007 (years late...) - the null check will work if you change the IF statement as follows:
// Null check
IF rowcount(@rs) > 0 THEN


text:
Q: Cannot run remote script via bash script but can through terminal ssh -p 60022 centos@localhost 'bash -s '< ./update.sh
If I run the following command through the terminal, all works fine and update.sh is ran on the remote machine.
If I place the same command into a bash script, deploy.sh for example, then execute with
. ./deploy.sh

from the same directory, it will not allow me to execute the script with the error:
: No such file or directory
I'm assuming this is something to do with working directories or something similar, but I can't find a fix.

A: The problem was line endings, when executing the file remotely with windows line endings nothing would work.
Changing the line endings to UNIX fixed this for me.


text:
Q: Templating a Jinja2 CSR conf with all hostnames in SAN I have 3 servers in my Ansible inventory:
[hosts]
ServerA ansible_host=hostname1.domain ...
ServerB ansible_host=hostname2.domain ...
ServerC ansible_host=hostname3.domain ...

I want to generate CSR with all hostnames in subject alternative name and sometime ago, I heard about Jinja templating so I thought it would be nice to prepare template and get dynamically list of hostnames from Ansible. Can someone help me and tell how can I search for ansible_host in Jinja template? Can I use magic variables?
So my CSR configuration looks like:
[req]
distinguished_name = req_distinguished_name
req_extensions = req_ext
prompt = no
[req_distinguished_name]
emailAddress = email@address.com
C            = US
O            = Google
OU           = HR
CN           = {{ AppNameDns }}
[req_ext]
subjectAltName = @alt_names
[alt_names]
DNS.1=hostname1.domain
DNS.2=hostname2.domain
DNS.3=hostname3.domain

A: Indeed, with the special variable groups you can list all hosts of a specific group, and with the special variable hostvars you can access variables of those hosts.
You can also use the special variables of the loop in Jinja to create for the index.
So the end of your configuration file end up being:
[alt_names]
{% for alt_host in groups['hosts'] %}
DNS.{{ loop.index }}={{ hostvars[alt_host].ansible_host }}
{% endfor %}


text:
Q: PHP preg_match_all wont find values I keep try to search for two values inside an string. I know I have to use the following command in PHP:
preg_match_all

It also have to be escaped. So I've tried to create a filter for this.

Original code:
<![CDATA[312.09999999999997]]></var><var n='destinationX' t='n'><![CDATA[510.75]]>

My actual code:
if (preg_match_all("\<!\[CDATA\[([0-9a-z_-]+)\]\]\>\</var\>\<var n=\'destinationY\' t=\'n\'\>\<\!\[CDATA\[([0-9a-z_-]+)\]\]/i>", $packets, $matches) )

Sadly it wont return the data contained in the CDATA. So I'm trying to get the following informations from this string:
Match 1: 312.09999999999997
Match 2: 510.75

Does anyone have a clue what I'm doing wrong?

A: change your regular expression to this:
/<!\[CDATA\[([0-9a-z_\-.]+)\]\]>/

you need to escape a literal hyphen or the regex engine will assume it's looking for a range (like in 0-9 or a-z) and you didn't allow periods.
I put it in a quick test script using the string you supplied:
<?php

$matches;
$packets = "<![CDATA[312.09999999999997]]></var><var n='destinationX' t='n'><![CDATA[510.75]]>";
preg_match_all('/<!\[CDATA\[([0-9a-z_\-.]+)\]\]>/i', $packets, $matches);
$matches = $matches[1];
print_r($matches);

This gave me an output like this:
Array ( [0] => 312.09999999999997 [1] => 510.75 )

A: $myString = "<![CDATA[312.09999999999997]]></var><var n='destinationX' t='n'><![CDATA[510.75]]>";
preg_match_all('/CDATA\[([a-z0-9-\.]+)\]/i', $myString, $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);

OUTPUT
Array
(
    [0] => 312.09999999999997
    [1] => 510.75
)

LIVE DEMO
http://ideone.com/C3a7Ci

A: This should get the values in between;
$packets = "<![CDATA[312.09999999999997]]></var><var n='destinationX' t='n'><![CDATA[510.75]]>";
$regex = "~[0-9]+\.[0-9]+~";
preg_match_all($regex, $packets, $matches);

print_r($matches);


text:
Q: Displaying statistics with SceneKit (SCNView) (Swift 4 / iOS 11 beta) I've been trying to get SCNView to display statistics on the Scene View, but showsStatstics doesn't seem to do anything.
Here's my code where I set SCNView.showsStatistics
  scnScene = SCNScene()
  scnView.scene = scnScene

However, this is a screenshot from the simulator running the app

As you can see, no statistics panel. What could be going on?

A: The problem is you cannot run AR apps from your simulator since there is no camera. Try using an actual device and see if the problem persists.


text:
Q: Can anybody help me how to check is there in table users user with this username? Can anybody help me how to check is there in table users user with this username ?
I am using SQLite3, PHP and PDO and I wrote code like
 try {
    $db = new PDO('sqlite:/var/db/db_users.db');
    $query = 'SELECT COUNT(*) FROM users WHERE username= :username';// moze LIMIT 1 da se stavi jer je sigurno jedan sa istim username i password sine
    $sth = $db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(array(':username' => $username));
    $result = $sth->fetchAll();
} catch (Exception $e) {
    return (array('message' => 'error'));
}

but there is no single_fetch or I cannot find. Can anybody help me how to solve this ?

A: Just use a single fetch.. since there is only one row you jsut fetch it like normal and dont loop then close the cursor. If youre only after a specific value you can jut pull the column too...
try {
    $db = new PDO('sqlite:/var/db/db_users.db');

    // add an alias.. not really necessary but good practice
    $query = 'SELECT COUNT(*) AS usercount FROM users WHERE username= :username';

    $sth = $db->prepare($query);
    $sth->execute(array(':username' => $username));

    // just call regular fetch for the first an only result
    // use fetch(PDO::FETCH_COLUMN) or fetchColumn to jsut get
    // a single column value from the row
    $result = $sth->fetchColumn(0);

    // be nice and close the cursor since we are done.
    $sth->closeCursor();

} catch (Exception $e) {
    return (array('message' => 'error'));
}


text:
Q: How to create a dynamic UML-diagram from HTML Tables? EDIT 1:
How about if I make them into a class and turn that into a UML-diagram that way?

I would like to create a dynamic UML-diagram based off my HTML code if that is possible.
The code looks like this:

Foo

FooHead

        Field
        Datatype
        Length

        Description

        Foo1
        String
        32
        M
        Unique foo number.

        Foo2
        String
        32
        M
        Foo2.

FooLine

        Field
        Datatype
        Length

        Description

        Foo1
        String
        32
        M
        Unique foo number.

        Foo6
        String
        32
        M
        Foo6.

        Foo7
        String
        32
        M
        Foo7.

The UML-diagram should look something like this (see below). I have tried googling around and couldn't really find anything. Any ideas for solutions or anything pointing me in the right direction would be greatly appreciated.

A: In order to style tables into UML classifiers (classes, interfaces, etc.), CSS might be useful. CSS selectors might help you to style specific columns for specific informations (name, type, or non-standard informations such as the length).
If you want do draw relationships between your tables, the simple solution is to use some Javascript library such as JSPlumb or  Raphael.
Finally, if you want to leave the HTML tables, here is some advertising for a personal work with Polymer Web components . Polymeria UML is a set of web components. Inspired by Eclipse UML2 elements, it supports generic class diagram elements. This is a work in progress: the current version is based on Polymer 0.5. An evolution for Polymer 1.0 might be available soon.

A: Here is an example:

Here is the complete implementation:
<!DOCTYPE html>

<title>UML Class Nodes</title>
<meta name="description" content="UML Class-like nodes showing two collapsible lists of items." />

<meta charset="UTF-8">

<link href="../assets/css/goSamples.css" rel="stylesheet" type="text/css" />

  This sample is adapted and simplified from GoJS UML Class sample.
  Data is taken from these HTML tables:

Foo

FooHead

      Field
      Datatype
      Length

      Description

      Foo1
      String
      32
      M
      Unique foo number.

      Foo2
      String
      32
      M
      Foo2.

FooLine

      Field
      Datatype
      Length

      Description

      Foo1
      String
      32
      M
      Unique foo number.

      Foo6
      String
      32
      M
      Foo6.

      Foo7
      String
      32
      M
      Foo7.

The code was adapted from the GoJS sample: UML Class