text:
Q: NameError: global name 'Pubnub' is not defined Im Deploying an Application Server on Bluemix using cf push, im receiving a error of "NameError: global name 'Pubnub' is not defined" but actually the first error i encountered is  "ERR ImportError: cannot import name Pubnub" then i got a solution looking in other threads where they suggest to change the syntax to "from pubnub.pubnub import PubNub" because i have PubNub v4 installed. Any Idea how to solve this. thanks. below is my code where the error is coming
def init():
    #Pubnub Initialization
    global pubnub
    pubnub = Pubnub(publish_key=PUB_KEY,subscribe_key=SUB_KEY)
    pubnub.subscribe(channels='kitchenDevice-resp', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect)
    pubnub.subscribe(channels='kitchenApp-req', callback=appcallback, error=appcallback, reconnect=reconnect, disconnect=disconnect)

A: It looks like you are attempting which is deprecated/EOL'ed, although, it should work.
Please be sure that you are using PubNub Python SDK v4 as v3 is no longer supported, although, it will still work.
If you provide more of your code (with the imports) that would be helpful but I would strongly suggest trying again with the v4 SDK and you can contact PubNub Support, if necessary.

A: Pip is the Python package manager. You use it to install packages and SDKs on your machine to run better Python apps.
To install with Mac OS, use this command in your terminal:
easy_install pip

Installing Pip on Linux
Installing Pip on Windows
Use pip to install the PubNub Python v4 SDK (which is latest). Terminal command:
pip install 'pubnub>=4.1.2'

Here is the code to connect to PubNub and Publish and Subscribe to an awesome channel. Make sure that you put in your own Free PubNub API keys into the code:
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pubnub = PubNub(pnconfig)

def my_publish_callback(envelope, status):
    # Check whether request successfully completed or not
    if not status.is_error():
        print 'publish success'

class MySubscribeCallback(SubscribeCallback):
    def presence(self, pubnub, presence):
        pass
    def status(self, pubnub, status):
        pass
    def message(self, pubnub, message):
        print message.message

pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels("awesomeChannel").execute()

## publish a message
pubnub.publish().channel("awesomeChannel").message("publish from device").pn_async(my_publish_callback)


text:
Q: Bootstrap event not caught in ajax loaded form I'm trying to grab the bootstrap panel shown event.  I believe the panel is working, because changing the panels swap the active class on the panels.  However, the event grab is not working.
Here is part of the form:

Discounts

Brand

Discount level

        <select class="form-control" name="brandID">
            <option value="0">Select a brand</option>

            @foreach($brands as $brand)
                <option value="{{$brand->getId()}}">{{$brand->getName()}}</option>
            @endforeach
        </select>

        <select class="form-control" name="genericDiscount" disabled>
            <option value="0">Select a discount</option>

            @foreach(ProductBase::getDiscountLevels() as $discountLabel => $discount)
                <option value="{{$discount}}">{{$discountLabel}}</option>
            @endforeach
        </select>

$(document).ready(function(){
    updateDiscountInputs();

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
        updateDiscountInputs();
    });
});

/**
 * Only the active table input should not be disabled.
 */
function updateDiscountInputs(){
    var brandDiscount   = $('#brandDiscounts').hasClass('active');
    var genericDiscount = !brandDiscount;

    $('#brandDiscounts').find('select').prop('disabled', !brandDiscount)    ;
    $('#genericDiscounts').find('select').prop('disabled', !genericDiscount);
}

The page that loads first has a select box and making a selection loads (via ajax) in a form that includes the above code.

A: Your tabs link are missing some important tags such aria-control and role

Brand

Discount level

Also you have to add your event listener after the html is added into the DOM. So you have to add the event listeners in your $(element).load() callback function.
For instance:
$(element).load(url, function() {
    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
        console.log("test")
        updateDiscountInputs();
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: ARM64 - Set most significant bits in 64 bit register What is the best way to set MSB bits of register x0 (64bit register) in arm?
The final goal is to set TCR_EL1 -64 bit system register- with the value I wish


text:
Q: What is the gradient of $f(x) := \langle v , F(x) v \rangle$? Let $F: \mathbb{R}^n \to S^n$ be differentiable function at point $x \in \mathbb{R}^n$. Where $S^n$ is the space of all symmetric matrices with usual Euclidian (trace) norm. Assume $v \in \mathbb{R}^n$ be a fix vector. Define the real valued function $f: \mathbb{R}^n  \to \mathbb{R}$ with $f(x) = \langle  v , F(x) v \rangle$.
My question:  Is the any nice representation of $\nabla f(x)$ in terms of derivative of $F$?

A: As suggested in the comments, the $i^{th}$ component of the gradient $\nabla f(x)$ is just the $i^{th}$ partial derivative $(\partial _if)(x)$, and by the chain rule it can be calculated as
\begin{align}
(\partial_if)(x) = \left\langle v, (\partial_iF)(x) \cdot v \right\rangle
\end{align}
We can also convey the same information in the language of Frechet/total derivatives as follows: $df_x: \Bbb{R}^n \to \Bbb{R}$ is that linear map such that for every $\xi \in \Bbb{R}^n$,
\begin{align}
df_x(\xi) = \left\langle v, dF_x(\xi) \cdot v \right\rangle
\end{align}


text:
Q: zend locale page not found I have been given a task to clone the website www.guilherminashoes.com to another hoster under another domain www.guilherminashoesna.com.
Everything works fine except when I click on the link to translate the page to English. I get page not found.
The link that is being called when clicking on ' ENG ' is:
http://guilherminashoesna.com/site.php/locale/index/lang/en/url/http%3A%2F%2Fguilherminashoesna.com%2Fsite.php%2F

The code of the site.php is as follows:
<?php
ini_set('display_errors', 'on');

ini_set('error_reporting', E_ALL);

try {

    // Define path to application directory
    defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/private/application'));

    // Define application environment
    defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));

    // Ensure library/ is on include_path
    set_include_path(implode(PATH_SEPARATOR, array(realpath(APPLICATION_PATH . '/../library'))));

    /** Zend_Application */
    require_once 'Zend/Application.php';

    // Create application, bootstrap, and run
    $application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');

    $application->bootstrap()->run();

} catch (Exception $e) {
    die($e->getMessage());
}

This feature works perfectly fine on www.guilherminashoes.com but does not work on www.guilherminashoesna.com any ideas what I might be missing here?

A: I have accidently solved this myself.... all I have do to was to call this URL:
    http://guilherminashoesna.com/site.php/locale/index/lang/en/url/

Instead of:
    http://guilherminashoesna.com/site.php/locale/index/lang/en/url/http%3A%2F%2Fguilherminashoesna.com%2Fsite.php%2F


text:
Q: Permission error when trying to use chrome.fileSystem chooseEntry When trying to use
chrome.fileSystem.chooseEntry({
    type: 'openFile'
},chooseEntryCallback)`

on Canary 28.0.1483.0 , I get the following error in the console:

chrome.fileSystem is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.

I only require read access, and this is how my permissions option in the manifest file looks like:
"permissions": [
  {
    "fileSystem": []
  },
  "contextMenus",
  "clipboardWrite",
  "storage"
],

This works fine with Stable 26.0.1410.64 so the question is whether there are some manifest permission changes which will need to be updated.
Note: Chrome running on Windows 8, and when opening the file via drag 'n drop it is opened without errors. So i'm guessing its some problem with chooseEntry ?

A: Based on @sowbug's comment I fixed this issue by changing the fileSystem permission to a list item:
"permissions": [
  "fileSystem"
],

Edit:
To include the extended write permission:
"permissions": [
  "fileSystem",
  "fileSystem.write"
],


text:
Q: Origin of "Best boy" - a film crew position For a long time I saw a title in the list of movie crew positions that was strange to me, Best boy.
Wikipedia says about that:

In a film crew there are two kinds of best boy: best boy electric and best boy grip. They are assistants to their department heads, the gaffer and the key grip, respectively. In short, the best boy acts as the foreman for his/her department.

I could not find a clear connection between the title and its role. So, what's the origin of this title and position?

A: The term shows up in credits as "Best Boy Electric" or "Best Boy Grip."  Imdb explains the origin of the term thus:

The origin of the term is from "pre-union" filming days when the line
  between Grip [department dealing with cameras and other equipment] and
  Electric departments was less rigid. When the head of either
  department needed another body temporarily, he'd go to the head of the
  other department and ask him to "lend me your BEST boy". By default
  the 2nd in charge of either department came to be known as best-boy.

This exact wording appears in multiple places across the internet, sometimes with attribution to IMdb and sometimes without.  Imdb gives no source for its explanation, which sounds like folk etymology to me.
Long before the film industry came about, English public schools had the office of "best boy," or teacher's assistant, described here in an 1892 issue of The Public School Journal:

Not only can the best boy in school light cigarettes for his
  teacher,
  but he becomes the  monitor of the school room when the teacher is
  hearing recitations.... [H]e patrols the aisles of the school room,
  ... calling the other boys to order....

The term was also used on sailing ships for the captain's apprentice as recorded in the journal The Nineteenth Century and After in a 1921 article called "Sea Service"  which reported on an apprentice's drowning:

The captain was almost overcome by the loss of 'his best boy.'

You can find claims that early movie crews were made up longshoremen and sailors.  (See this Forbes article, for instance.)  Again, no sources are cited.

A: There is only one Best Boy and he is in the Electrical dept, the use of best boy electric has only crept into the game since the 80's. The term is associated with the term Gaffer, therefore Best Boy Grip needs the suffix Grip. The origins are scattered, from Gaffers who rigged sails on tall ships putting his Best Boy on each spar, One Gafffs sails, and a lot of early film lighting involves rigging ( or Gaffing) sailcloths and other overhead textiles to control lighting, this predates film eclectic lighting and is everyday work today. There is also reference to the potato famine of Ireland whereby Gaffers would bring work gangs to England to pick crops, promoting a Best Boy to manage each workgang, usually per field or task. Then there are the myriad of other uses whereby a 'Boy' was promoted to crew chief. The suggestion that one calls for another dept Best Boy is bunk, the Best Boy is the last member to be released to another dept, he is after all that departments cheif asset, least not in my 35 years as a Best Boy.
Cheers

A: Jonathon Green, Dictionary of Jargon (1987) has this entry for best boy:

best boy n. {Film} a film crew member who is the assistant to the gaffer [chief electrician] or key grip [supervisor of employee who move around various specific types of heavy equipment].

But this only tells us what the best boy does and puts the origin of the term at no later than 1987. The Internet Movie Database site has a somewhat more helpful glossary entry for the term:

Best Boy
AKA: Assistant Chief Lighting Technician, Best Boy Grip, Best Boy Electric
The chief assistant, usually of the gaffer or key grip. In charge of the people and equipment, scheduling the required quantities for each day's work. The term originates from promoting the crew's 'best boy' to supervising, allowing the gaffer and key grip to stay on set and carry out the cameraman's lighting needs. The origin of the term is from "pre-union" filming days when the line between Grip and Electric departments was less rigid. When the head of either department needed another body temporarily, he'd go to the head of the other department and ask him to "lend me your BEST boy". By default the 2nd in charge of either department came to be known as best-boy. This term may also have been borrowed from early sailing and whaling crews, as sailors were often employed to set up and work rigging in theatres. There are no "best girls" per se; female chief assistants are also called "Best Boys".

According to the Infoplease entry for "Movies and Films: Unions" unionization of actors, cameramen and other U.S. film industry employees occurred began during the 1910s and 1920s. However, Merriam-Webster's Eleventh Collegiate Dictionary (2003) reports a first occurrence date of 1937 for best boy in the film industry sense of the term.

A: The department head is in charge of a bunch of people in the department, called boys.
The department head appoints a second in command, or foreman, who is the best of those boys.

A: my understanding of the the term best boy comes from an old doco i saw years ago. a gaffer was explaining the best boy was an actual young boy who would be nimble enough to climb to the top of the rigging to secure sailcloth & tweak lighting focus.

A: I was told that in the early days of the motion picture industry, when a gaffer would get hired to light a movie he would go to the union hall and say, "Give me your best boy for my second electric."


text:
Q: Search and match CSV file values with javascript I've uploaded a CSV-file to an HTML page via javascript. The CSV rows are: name and email-address, e.g. rambo,rambo@rambo.com.
How to SEARCH the 'name' from these loaded CSV-file?
Also, one of the data is an email-address and I want to send a mail to that email-address. Is that value retrieved to a variable?
My code to search each elements:
function Search() {
 var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
    if (typeof (FileReader) != "undefined") {
        var reader = new FileReader();
        reader.onload = function (e) {
          var table = document.createElement("table");
var rows = e.target.result.split("\n");
for(var i = 0; i < rows.length; i++)
{
    var row = table.insertRow(-1);
    var cells = rows[i].split(",");
    for(var j = 0; j < cells.length; j++)
    {
        var cell = row.insertCell(-1);
      //  cell.innerHTML = cells[j];

    // Here repeated checkboxes:
    var radio = document.createElement('input');
    radio.type = 'checkbox';
    radio.name = 'check';

}

var ser=document.getElementById("texts");
    if(cells[i].indexOf(ser))
    {
     alert("matches");
       cell.innerHTML = cells[i];
    }
    else
    {
     alert("unmatches");
    }

    var cell = row.insertCell(-1);
    cell.appendChild(radio);
    //cell.appendChild(button);
}
 var button = document.createElement('button');
    button.textContent = 'Send';
cell.appendChild(button);
button.onclick = function(){ alert();};

var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
        }

        reader.readAsText(fileUpload.files[0]);

    }
   }
}

A: Ad search: indexOf() is your friend here. This should give you a figure:
var table = $('#your-table'),
    searchstring = 'your-searchstring';
searchstring.toLowerCase();
for (var i = 0, cell; cell = table.cells[i]; i++) {
    if (cell.indexOf(searchstring)) {
        // I don't know what you want to do with the search-results...
        // ..but you can do it here.
    }
}

Ad email-address: you can add the address to a variable in your CSV-import:
var cells = rows[i].split(","),
    address = cells[1];

I'd suggest making an array addresses and fill it each row.


text:
Q: Openstreetmap - Osmdroid - WMTS I'm looking to use mapping services via WMTS protocol through the OpenstreetMap android SDK (osmdroid).
However no matter the zoom level, I load for each web request an image of 256x256px.
This causes a lot of performance problems.
I think it must come from the row/col calculation of the image matrix.
However, to do this calculation I only have the value pMapTileIndex (cf. OnlineTileSourceBase.getTileURLString(long pMapTileIndex) https://github.com/osmdroid/osmdroid/blob/master/osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/OnlineTileSourceBase.java)
I don't know if I have to do some conversion or not, I can't find more documentation about that


text:
Q: Are these frequent calls to a function that returns a fixed value in dblquad avoidable? This script calculates the electric field at (x0, y0, z0) from a uniformly charged annulus using SciPy's dblquad.
My question is about the use of gfun and hfun which define the functional dependence of the inner integral limits on the outer integral variable. This would be a cookie-cutter shape if I'd chosen to integrate in cartesian coordinates, but when I use cylindrical coordinates the functions return constant floats.
Is there a way to eliminate these function calls that simply return constants in order to avoid the time penalty of the function calls?
The example may not be optimized in other ways, but it's just a simple example to show the use of gfun and hfun.
def Excalc(r, th):
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0
    return (x0-x) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

def Eycalc(r, th):
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0
    return (y0-y) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

def Ezcalc(r, th):
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0
    return (z0-z) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

def gfun(x):
    return rmin

def hfun(x):
    return rmax

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import dblquad

twopi = 2.*np.pi

# annulus of uniform, unit charge density
rmin, rmax   = 0.8, 1.2
thmin, thmax = 0,   twopi

# point to evaluate the field
x0, y0, z0 = 1.5, 0, 1

eps = 1E-10

Ex, Exerr  = dblquad(Excalc, thmin, thmax, gfun, hfun, epsrel=eps)
Ey, Eyerr  = dblquad(Eycalc, thmin, thmax, gfun, hfun, epsrel=eps)
Ez, Ezerr  = dblquad(Ezcalc, thmin, thmax, gfun, hfun, epsrel=eps)

print Ex, Ey, Ez
print Exerr, Eyerr, Ezerr

A: According to the definition of dblquad, the gfun and hfun parameters are of type callable, which means they will be called by dblquad in a function-call way.
However you can make the code a little bit neat by using Python's lambda instead of a normal function. Example:
Ex, Exerr = dblquad(Excalc, thmin, thmax, lambda: 0.8, lambda: 1.2, epsrel=eps)


text:
Q: DataTable to List Generic i'm using the following extension to extract a column from a datatable to a list-object:
public static List<string> ColumnToList(this DataTable dt, string ColumnName)
{
    return dt.AsEnumerable().Select(x => x[ColumnName].ToString()).ToList();
}

ist it possible to use a genereic datata-type - not just string - ? in my case the return-value can be anything like List<string>, List<datetime>, List<int>, List<bool>, ...

A: Sure, you can use DataRow.Field<T> method:
public static List<T> ColumnToList<T>(this DataTable dt, string ColumnName)
{
    return dt.AsEnumerable().Select(x => x.Field<T>(ColumnName)).ToList();
}

You need to specify the column type when calling the method, for example:
List<int> idList = dt.ColumnToList<int>("id");


text:
Q: "sudo apt-get install xyz" command Can someone explain what actions this command will perform?

sudo apt-get install xyz

A: Note: "apt-get install" will also install missing dependencies for the xyz package.

A: for future reference, the man command can help with commands
just type
man *yourCommand*

or in your case
man sudo

man apt-get

A: Indeed, lets break this down.

*

*sudo (some parameters): Instructs the operating system to execute the parameters as a command, but do so with administrative (usually root) privileges.

*apt-get (some parameters): Runs the package manager called apt-get on your machine. The parameters are a command for apt-get to run.

*install xyz: These parameters to apt-get instruct apt-get to find and install a package called xyz.

So, as a whole, this command attempts to find and install package/program xyz on your machine and does so as root if you are able to authenticate as such.

A: This is more of a ServerFault.com question than StackOverflow, but it instructs the package manager to install the xyz program.
sudo - do this as an administrative user
apt-get - the package management program
install - the instruction for the program
xyz - the program to install

A: In order to see the repository that would be used to install a package, use the following:
apt-get --print-uris install xyz

then answer "Y". The URIs will be printed, but the package won't be installed.
To see what repositories you have configured, look at this file /etc/apt/sources.list which can be edited (but you should probably use System>Administration>Software Sources to choose repositories.

A: To see what versions of a package are available to be installed, and from what repository, try
apt-cache policy xyz


text:
Q: redirect to the welcome page(login page) whenever any request for .jsp resources within the /WEB-INF/views folder comes directly I am new in spring mvc.i want to redirect to the welcome page(login page) whenever any request for .jsp resources within the /WEB-INF/views folder comes directly. I mean without logging into the application.
Any suggestion??

A: You should use Spring Security for this task. You can configure Spring Security that it show every page only to loggedin users. If a not loggedin user try to access one of this protected pages, then spring security will redirect him to an logging page (your welcome page).


text:
Q: Problem with .cbr comics I have several .cbr comic files that I downloaded and am now unable to open. I have downloaded at least 5 different comic book viewers (including comix) in Ubuntu through the package manager and downloading off websites and all of the programs are unable to open these files. I have also tried to rename the file from X.cbr to X.zip then extract the file but only the extra files within are extracted and it is unable to extract the image files.
Does anyone have any idea how to get this comics to work in either windows or Ubuntu? I'm worried that they haven't been compressed properly and I will never be able to access them.

A: .cbr uses RAR as its compression. Install unrar.

A: If you are want to read the comic then download this software http://comicrack.cyolito.com/.
If you want to extract the content of the package use 7zip


text:
Q: Test Camel Route that starts by waiting for a file to arrive I have a Camel route that waits for a zip file to be received in a directory. It unzips it and then iterates over the files it contains, parsing their contents before sending them on to one of a number of message queues.
I have got the route to work end to end, but now I want to write unit tests to handle the different cases that might arise. And I'm falling at the first hurdle.
All the unit tests that I have been able to find on the internet seem to start with a message being received by the first component in the route. I need to simulate the existence of a file.
My route is configured in a Spring context file, and I can see that my routes are being adviced ( for example : Adviced endpoint [file:///tmp/dta/xml_source?antInclude=*.zip&move=.done&moveFailed=.error] with mock endpoint [mock:file:/tmp/dta/xml_source] )
I just don't know how to kick it into action.

A: Replace the advice from mock: to seda: or direct: and use a ProducerTemplate to send a message to the starter endpoint.

A: You can simply advice your consumer (i.e. FILE) to point to a test resource directory with specific file name and make sure the noop=true so test does not delete the file.
This way you are not mocking this endpoint and your route runs just as in a real scenario.
replaceFromWith("file:///TEST_RESOURCE_DIRECTORY/dta/xml_source?antInclude=*.zip&move=.done&moveFailed=.error&noop=true")


text:
Q: How to develop an app across multiple PCs I want to keep developing my android project across different computers,
so whatever I do on pc1 should be in sync with project on pc2. I used github, but I don't like it, because it shares my project publicly and makes it accessible to anybody.

A: Use Bitbucket. You can have unlimited number of private repos there.
Here's a link guiding you through the process of setting up a private repo (point 4):
https://confluence.atlassian.com/bitbucket/create-a-repository-800695642.html


text:
Q: Generating two opposite PWM signals with timers and GPIO/AF pins change I need to generate two opposite PWM signals (when one is high the other one is low) using timers in STM32. I have read several examples and this is the code I came up with:
void TM_PINS_Init(void) {
    GPIO_InitTypeDef GPIO_InitStruct;
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

    /* Alternating functions for pins */
    GPIO_PinAFConfig(GPIOD, GPIO_PinSource12, GPIO_AF_TIM4);
    GPIO_PinAFConfig(GPIOD, GPIO_PinSource13, GPIO_AF_TIM4);

    /* Set pins */
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_Init(GPIOD, &GPIO_InitStruct);
}

void TM_TIMER_Init(void) {
    TIM_TimeBaseInitTypeDef TIM_BaseStruct;

    /* Enable clock */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

    uint16_t Period;
    Period = 1000000 / 200000; // 200 KHz from 1MHz

    TIM_BaseStruct.TIM_Prescaler = (SystemCoreClock / 1000000) - 1; // 1MHz
    TIM_BaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_BaseStruct.TIM_Period = Period - 1;
    TIM_BaseStruct.TIM_ClockDivision = 0;
    TIM_BaseStruct.TIM_RepetitionCounter = 0;
    /* Initialize TIM4 */
    TIM_TimeBaseInit(TIM4, &TIM_BaseStruct);
    /* Start count on TIM4 */
    TIM_Cmd(TIM4, ENABLE);
}

void TM_PWM_Init(void) {
    TIM_OCInitTypeDef TIM_OCStruct;

    /* PWM mode 2 = Clear on compare match */
    /* PWM mode 1 = Set on compare match */
    TIM_OCStruct.TIM_OCMode = TIM_OCMode_PWM2;
    TIM_OC1Init(TIM4, &TIM_OCStruct);
    TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);

    TIM_OCStruct.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OC2Init(TIM4, &TIM_OCStruct);
    TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable);

    TIM_OCStruct.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCStruct.TIM_OCPolarity = TIM_OCPolarity_Low;
    TIM_OCStruct.TIM_Pulse = Period/2; /* 50% duty cycle */
}

I have several questions:

*

*Since I need frequencies in terms of tens of kHz, do I need 100MHz setting for the GPIO speed? Is there any benefit to make it slower?

*Would my PWM function generate what I need? I think the opposite PWM signals are actually achieved using PWM modes 1 and 2, but I am afraid I may be missing something there.

*I want to be able to stop the timers, and to set high/low state to the same pins. Would the following code work?
GPIOD-> MODER |= (5 << 24); //set pin 12 and 13 to GPIO, 5 gives us 101, shifted 23 bits so that '1's are in pos. 24 and 26

GPIOD->regs->BSRR = (3<<12); // 3 gives us 11 pattern, shifted 12 bits so that pins 12 and 13 are set to high

GPIOD-> MODER |= (5 << 24); //set pin 12 and 13 to AF, 5 gives us 101, shifted 24 bits so that '1's are in pos. 25 and 27

*When the AF is restored, are the previous pwm settings restored or must be set again.

*Would it be better to use MODER as above to change pins to GPIO and then set to high/low, or I can use 100% duty cycle for high and 0% duty cycle for low?

A: Q1: No, you do not need to. Faster settings means more power consumed by the peripheral and sharper edges of the generated signal which causes more EMI. If you do not care about the both - it does not matter.
Q2: You need to check it yourself if you use some kind of "magic" numbers.
Q3: Same as above. Why don't you use human readable CMSIS definitions only "magic" functions. If you correct set the register values it will work
Q4: If you stopped the timer you need to start/configure it again. If not it should work.
Q5: It does not matter. But running timer will generate noise and consume some power.


text:
Q: Creating an array of arrays in perl How can I create an array of arrays in perl and access each of the member arrays with an appropriate index.
Currently I'm using a one dimensional array, updating it at each iteration and printing:
for ($i=0;$i<$size;$i++)
{
  @words = @synsets[$i]->words;
  print "@words\n"
}

But since at the next step i want to perform further operations, I want to access arrays corresponding to each "synset".
Could someone please tell me how i could do that?

A: Here's a small self-contained files to demonstrate the basics.  Edit to suit :-)
Data::Dumper helps with visualizing data structures - a great learning tool.
The [] acts as an "anonymous array constructor".  You can read more about that with perldoc perlref (or follow the previous link). Sometimes you have to explain something to someone else before you can be even somewhat sure you understand it yourself, so bear with me ;-)
use 5.10.0 ;
use Data::Dump;
use strict;
use warnings;

my @AoA ;

#my $file = "testdata.txt";
#open my ($fh), "<", "$file" or die "$!";
#while  (<$fh>) {
while  (<DATA>) {
  my @line = split ;
  push @AoA, [@line] ;
}

say for @AoA;   # shows array references
say @{$AoA[0]}[0] ;  # dereference an inner element
foreach my $i (0..$#AoA)
{
 say "@{$AoA[$i]}[2..4]" ; # prints columns 3-5
}

dd (@AoA) ;   # dump the data structure we created ... just to look at it.

__DATA__
1 2 3 0 8 8
4 5 6 0 7 8
7 8 9 0 6 7

A: Try:
for my $synset ( @synsets ){
    my @words = @$synset;
    print "@words\n";
}

A: You'll need to make a list of references to lists, since Perl doesn't allow lists in a list.
@sentences = ();
...
    # in the loop:
    push @sentences, \@words;

To access individual words you can then do the following:
$word = $sentences[0]->[0];

The arrow can be omitted in this case though.


text:
Q: A subset of $SL(2,\mathbb{C})$ Let $\mathcal{H}$ be the real vector space of $2 \times 2$ complex Hermitian matrices. Set
$$\mathcal{K} := \{A \in SL(2,\mathbb{C}) : \forall H \in \mathcal{H}, \space A^{-1}H = HA^* \}.$$
Here $A^*$ denotes the conjugate transpose of $A$. I'm trying to determine which matrices are exactly the elements of $\mathcal{K}$. It seems to me that $\space \mathcal{K} = \{I_2,-I_2\}$, but all my attempts to prove this have failed.
Any ideas would be appreciated.

A: Fix $A\in\mathcal K$.  Taking $H=I_2$ you get that $A^*=A^{-1}$.  Thus $A^*H=HA^*$ for all Hermitian $H$, which implies $AH=HA$ for all $H$ (take the conjugate transpose of each side).  Because $M_2(\mathbb C)$ is the complex linear span of $\mathcal H$, this implies that $A$ commutes with every $2$-by-$2$ matrix, hence $A$ is a scalar multiple of the identity. Because $\det(A)=1$, the scalar is $\pm1$.


text:
Q: Cantor set representation Why is it possible to write the cantor set $C$ as $C= \frac{1}{3} C \cup (\frac{2}{3} + \frac{1}{3} C)$? I found this in my textbook and am not quite sure, how to deduce this.
Thanks for clarifying!

A: This is a recursive definition, and one should show that it is well defined.
If $C \subset \mathbb R$ and $d\in \mathbb R$ you can define $$dC = \{d\cdot x|c\in C\}.$$
And $$d+C = \{d+x | x\in C\}.$$
This way it is pretty clear that the cantor set satisfies the given condition $C = \frac 1 3 C \cup (\frac 2 3 + \frac 1 3 C)$.
Edit: Of course I do not mean that this a definitino of the cantor set, but rather a definition of a set $C$ and obviously the cantor set satisfies it.


text:
Q: Tool to connect to IMAP server I have an outlook mailbox.
Main goal is to find out message's IMAP UID of particular message having all the information that outlook web interface provides (subject is quite good for that).
I can connect to outlook using openssl s_client -crlf -connect imap-mail.outlook.com:993, but it is not very comfortable to work through terminal.
Is there any tool that helps to simplify work with IMAP server where I still can write my own commands like fetch 1:10 (UID)?


text:
Q: Remote service query (sc.exe query) fails with "access is denied" for one service, but not others I'm trying to remotely uninstall a specific service, but get the famous "FAILED 5: Access is denied." message.  I've reduced the test case to running
sc \\remotemachine.domain.local query "flexnet licensing service"

and I get
[SC] EnumQueryServicesStatus:OpenService FAILED 5:
Access is denied.

The interesting thing is that I can remotely query pretty much any other service from the same client and there's no problem.
The host machine

*

*Has UAC disabled

*Has LocalAccountTokenFilterPolicy set to 1

Using the same user when logged on directly to the machine, I can query, start or stop this "flexnet licensing service" with no problem, it's only when trying to do it remotely than I encounter a problem.
Originally we bumped into this problem when our uninstaller could not uninstall this service, using the Windows C API.  The uninstaller would work fine when run directly on the machine, but when invoked remotely via WMI it would fail.  We've been reducing the test case progressively, and so far in all cases, querying or trying to stop or delete this particular service fails when attempted remotely.
I have also tried calling a batch script remotely, which contained the commands:
powershell.exe -Command "Start-process C:\myDeleteSvc.exe -Verb RunAs"

Where myDeleteSvc.exe was a simple program installed on the target machine to delete the service using the Windows C API, but that also failed in the OpenService call with an access denied.  Again, it works fine if run directly on the machine.
I've had this happen with the service installed on Windows 7 and 2008R2 machines (did not test on other platforms).
The service in question is for a third party software.  It has a dependency on the Windows Management Instrumentation service, but even when I manually remove all dependencies (and dependents) it still cannot be queried remotely.
Does anyone have any further suggestions for investigation (or solutions)?
There is one case where the service can be uninstalled remotely.  We talked to the support team for this product in trying to understand the problem, and while they're also mystified, they did provide a msi file that, when run remotely, uninstalled the service in question.  We don't have access to whatever script was used to generate this msi, but we were told it was "very simple, and all it did was uninstall the service".  One possible avenue of investigation is to understand if the msi service uninstall does anything "extra" when it performs an uninstall--does anyone know?
Some related questions, although they seem to all be the same theme of UAC & running as administrator, and since I can query other services remotely, I think my problem must be something slightly different.  Including the links makes the bot think this is spam, so just search on the titles.

*

*"Access is denied" when trying to start service even when running Administrator/elevated

*psexec: "Access is Denied"?

*remote sc OpenSCManager query failed 5 access denied

A: Thanks to Craig620, the problem was indeed related to the security descriptor.
C:>sc sdshow "flexnet licensing service"

D:(D;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;NU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)(A;;CCLCSWRPLOCRRC;;;IU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

C:>sc sdshow myService

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

And from the SID syntax we can see the first entry ((D;;...;;;NU)) Disables most permissions for anything coming over the network (NU).  When I changed the SD to have the same permissions minus the NU disablement, I could query and delete the service remotely using the sc.exe command.


text:
Q: Animate from one style to another Just wondering if anyone know how to animate from one style to another i.e. going from NormalStyle to ActiveStyle when the user focuses on the textbox
<Style x:key="NormalStyle" TargetType="{x:Type TextBox}">
    <Setter Property="BorderBrush" Value="Gray" />
    <Setter Property="BorderThickness" Value="2" />
</Style>

<Style x:key="ActiveStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource NormalStyle}">
    <Setter Property="BorderBrush" Value="Green" />
    <Setter Property="BorderThickness" Value="4" />
</Style>

A: If you want to swap the whole style, I think you might have to do it in code:
<StackPanel>
    <TextBox Style="{StaticResource NormalStyle}" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
    <TextBox Style="{StaticResource NormalStyle}" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
</StackPanel>

    private Style focusedStyle;
    private Style normalStyle;

    public MainWindow()
    {
        InitializeComponent();

        focusedStyle = FindResource("ActiveStyle") as Style;
        normalStyle = FindResource("NormalStyle") as Style;
    }

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        ((TextBox)sender).Style = focusedStyle;
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        ((TextBox)sender).Style = normalStyle;
    }

Otherwise, you are pretty much confined to triggering back and forth..
<TextBox Text="1" >
        <TextBox.Style>
            <Style BasedOn="{StaticResource NormalStyle}" TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="GotFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" To="Green" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="LostFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" To="Gray" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style


text:
Q: Spring Boot class def not found error I have a simple spring boot app that I'm using to connect to a REST api and see it response. It's a simple app for prototyping. However I'm getting the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: [Lcom/crossover/techtrial/java/se/dto/Account;
    at com.crossover.techtrial.java.se.TrialApplication.main(TrialApplication.java:25)
Caused by: java.lang.ClassNotFoundException: com.crossover.techtrial.java.se.dto.Account
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

I have no idea why is it occuring since I have defined the class Account:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Account
{
    private String id;

    private MonetaryAmount monetaryAmount;

    public Account()
    {

    }

    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    public  MonetaryAmount getMonetaryAmount()
    {
        return monetaryAmount;
    }

    public void setMonetaryAmount(MonetaryAmount monetaryAmount)
    {
        this.monetaryAmount = monetaryAmount;
    }

}

my calling code:
package com.crossover.techtrial.java.se;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;

import com.crossover.techtrial.java.se.dto.Account;

@SpringBootApplication
public class TrialApplication
{
    @Autowired
    public static RestTemplate restTemplate;

    @Value("${apiforest.baseuri}")
    public static String baseURI;

    public static void main(String[] args)
    {

        String url = baseURI + "/paypallets/accounts";
        //SpringApplication.run(TrialApplication.class, args);
        restTemplate.getForObject(url, Account[].class);
        System.out.println(url);
    }
}

Another problem is it is not fetching the value for key "apiforest.baseuri" that I have defined in application.properties.
My application.properties:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/SampleDB
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
management.port = 9001
apiforest.baseuri = https://api-forest/....
read.timeout = 10000
connect.timeout = 10000

My RestConfig:
package com.crossover.techtrial.java.se.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

// To set the configuration parameters like read timeout and connect timeout for Rest Client
@Configuration
public class RestConfig
{
    @Bean
    public RestTemplate createRestTemplate(final ClientHttpRequestFactory clientHttpRequestFactory)
    {
        return new RestTemplate(clientHttpRequestFactory);
    }

    @Bean
    public ClientHttpRequestFactory createClientHttpRequestFactory(@Value("${connect.timeout}") final int connectTimeout,
            @Value("${read.timeout}") final int readTimeout)
    {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(connectTimeout);
        factory.setReadTimeout(readTimeout);
        return factory;
    }
}

My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.crossover.techtrial.java.se</groupId>
    <artifactId>trial</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>trial</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Any ideas?
EDIT: I changed my calling code to what @Luke suggested by doing this:
@SpringBootApplication
public class TrialApplication
{
    @Value("${apiforest.baseuri}")
    public static String baseURI;

    public static void main(String[] args)
    {
        ConfigurableApplicationContext run =
          SpringApplication.run(TrialApplication.class, args);
        RestTemplate restTemplate = run.getBean(RestTemplate.class);
        String url = baseURI + "/paypallets/accounts";
        restTemplate.getForObject(url, Account[].class);
        System.out.println(url);
    }
}

But now I'm getting the following exceptions one of which is still ClassdefNot Found:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'createRestTemplate' defined in class path resource [com/crossover/techtrial/java/se/config/RestConfig.class]: Unsatisfied dependency expressed through method 'createRestTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'createClientHttpRequestFactory' defined in class path resource [com/crossover/techtrial/java/se/config/RestConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.http.client.ClientHttpRequestFactory]: Factory method 'createClientHttpRequestFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1134) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1028) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at com.crossover.techtrial.java.se.TrialApplication.main(TrialApplication.java:21) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'createClientHttpRequestFactory' defined in class path resource [com/crossover/techtrial/java/se/config/RestConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.http.client.ClientHttpRequestFactory]: Factory method 'createClientHttpRequestFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1134) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1028) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1136) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.http.client.ClientHttpRequestFactory]: Factory method 'createClientHttpRequestFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 32 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient
    at com.crossover.techtrial.java.se.config.RestConfig.createClientHttpRequestFactory(RestConfig.java:25) ~[classes/:na]
    at com.crossover.techtrial.java.se.config.RestConfig$$EnhancerBySpringCGLIB$$25eeb443.CGLIB$createClientHttpRequestFactory$1(<generated>) ~[classes/:na]
    at com.crossover.techtrial.java.se.config.RestConfig$$EnhancerBySpringCGLIB$$25eeb443$$FastClassBySpringCGLIB$$44b4ec10.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at com.crossover.techtrial.java.se.config.RestConfig$$EnhancerBySpringCGLIB$$25eeb443.createClientHttpRequestFactory(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_121]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 33 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.apache.http.client.HttpClient
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_121]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_121]
    ... 44 common frames omitted

A: I don't think you can inject a bean in the same class that create the Context (maybe you it works for a property since PropertySourcesPlaceholderConfigurer is a BeanFactoryPostProcessor).
You can try with
SpringBootApplication
public class TrialApplication
{
    @Value("${apiforest.baseuri}")
    public static String baseURI;

    public static void main(String[] args)
    {
        ConfigurableApplicationContext run =
          SpringApplication.run(TrialApplication.class, args);
        RestTemplate restTemplate = run.getBean(RestTemplate.class);
        String url = baseURI + "/paypallets/accounts";
        restTemplate.getForObject(url, Account[].class);
        System.out.println(url);
    }
}

But I would  use this solution only for a test (definately non for production code)

A: Fix your main class with @SpringBootApplication. And add this dependency to your pom
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
</dependency>


text:
Q: Failed JUnit test when calling Stored Procedure with Spring I am really new to Spring JDBC. I have 3 JUnit Tests which have no shared data (no before/after methods required as they have their own data in their own data files)
Each of these tests call a stored procedure inside a package. If I run the tests individually they all pass but running all three, one fails: (if i change the order of the tests in the class the failing one changes)
The call to the stored proc uses Spring JDBC:
 SimpleJdbcCall callProcedure = new SimpleJdbcCall(jdbcTemplate)
                .withCatalogName("ADMIN.CALCULATE")
                .withProcedureName("GET_TOTALS")
                .useInParameterNames("account_no", "request_list")
                .withoutProcedureColumnMetaDataAccess()
                .declareParameters(
                        new SqlParameter("account_no", Types.INTEGER),
                        new SqlParameter("request_list", OracleTypes.ARRAY, "ADMIN.CALC_REQUEST_TAB"),
                        new SqlOutParameter("response_list", OracleTypes.ARRAY, "ADMIN.CALC_RESPONSE_TAB"));
        callProcedure.compile();
        Map<String, Object> inputParams = new HashMap<String, Object>();
        // set StructDescriptor and ArrayDescriptor
        genericTypeDTO.setStructDescriptorName("ADMIN.T_CALC_REQUEST_TYPE");
        genericTypeDTO.setArrayDescriptorName("ADMIN.CALC_REQUEST_TAB");
                   inputParams.put("account_no", accountNo);
        inputParams.put("clawback_list", genericTypeDTO);
        Map<String, Object> outData = (Map<String, Object>) callProcedure.execute(inputParams);

Below is the exception that is thrown when hitting callProcedure.execute(inputParams) for one of the tests:

Caused by: org.springframework.jdbc.BadSqlGrammarException:
  CallableStatementCallback; bad SQL grammar [{call
  ADMIN.CALCULATE.GET_TOTALS(?, ?, ?)}]; nested exception is
  java.sql.SQLException: ORA-06533: Subscript beyond count ORA-06512: at
  "ADMIN.CALCULATE", line 2160 ORA-06512: at line 1

Any advice would be appreciated.

A: I think that you need to take a look at the mocking frameworks. It looks like your unit-tests are related to each other. Unit-tests actually must be unrelated, and you can achieve this by using the mocks.


text:
Q: Splitting an array and counting values I'm trying to figure out how to implement a method that does the following:
The method takes in a text file and counts the number of words up until a specified character "#".
An array is passed as a parameter through the method, this contains a list of sequential numbers. A number in an array corresponds to the position the word occurs in the text file (disregarding #'s) so the 4th word will correspond to a value of 3 (n-1).
The method will count the number of times the word before a # occurs in the array and divide it by the total number of entries between #'s it will then take the average of each time this is done.
So an example to make this clear:
Say you have the text file containing :
Hi my name # is something #
A corresponding array would be:
0,0,1,1,1,2,2,2,2,3,4,4 (a number for each letter in sequence)
The first hash would occur between the 2 and 3. So the 2's represent the word occuring before the #.  So we would  calculate (total number of 2's)/total number of 0's, 1's and 2's.  This would be 4/9.
We would then calculate the same between the two hashes # is something #. 'something' corresponds to a 4, so we would have (total number of 4's)/total number of 3 and 4's.
This would be 2/3.
We would then take the average of 2/3 and 4/9
I hope this is clear, let me know if you need any clarifications.

A: I'd split() the string for any whitespace chars. Now I have every word in an array, with each cell's index representing the corresponding num, and the cell's content(the word) length is the 'how many 0's or 1's or ..' I have.
That should solve the first part of your problem.
Then you need to find where each # is, its offset that is, but that offset you want to represent in words, not chars. So I'd iterate through the previously created array, and check if the word I stored is a #. If it is I'd update a marker variable (this should hold the previous position/index of the last seen #), and calculate the division you want (4/8 , 2/3 w/e). That is the length of the previous cell's content divided by the sum of length's from the marker until the current index-1.
I think that's about it; the logic. It's not that hard to implement. Just don't forget to check the bounds.


text:
Q: Uniqueness of left-hand limit of $\sqrt{x}$ at $x = 0$ This post says that right-hand limit, or similarly left-hand limit, is unique when it exists by the uniqueness of limit. That can be asserted because $$\lim_{x\to c} f(x) = L \Longleftrightarrow \lim_{x\to c^-} f(x) = L = \lim_{x\to c^+} f(x).$$
Now let $f : [0, \infty) \to \mathbb{R}$ be defined as $f(x) = \sqrt{x}$. This post says that $$\lim_{x\to 0} \sqrt{x} = 0 \text{ because } \lim_{x\to 0^-} \sqrt{x} = 0 = \lim_{x\to 0^+} \sqrt{x}$$
asserting that the left-hand limit exists by the vacuous truth of an empty domain, which is confirmed in this post.
But, by the vacuous truth of an empty domain, the left-hand limit is no longer unique because $$\begin{align*}
&\forall z \in \mathbb{R} : \lim_{x\to 0^-} \sqrt{x} = z \\
\Longleftrightarrow\;&\forall z \in \mathbb{R} : \forall \varepsilon\in\mathbb{R}:\exists\delta\in\mathbb{R}:\forall x\in \varnothing : -\delta < x < 0 \longrightarrow \left|\sqrt{x} - z\right| < \varepsilon\;\ldots\;\text{LH limit definition} \\
\Longleftrightarrow\;&\top\;\ldots\;\text{vacuously true by }\forall x \in \varnothing\text{ for all }z
\end{align*}$$
But, it must be unique because $$\lim_{x\to 0} \sqrt{x} = 0$$ is unique.
What is my logical fallacy such that I can show that the left-hand limit is no longer unique by the vacuous truth of an empty domain?


text:
Q: Jupyter missing version metadata I'm trying to open jupyter and check an ipynb file but an error appears saying that there is no version attribute but I don't know how to fix it. If anyone knows how to, I'll be grateful.
The text on screen is:
Traceback (most recent call last):

File "C:\Users\D3ll\Anaconda3\Scripts\jupyter-notebook-script.py", line 6, in
from notebook.notebookapp import main

File "C:\Users\D3ll\Anaconda3\lib\site-packages\notebook\notebookapp.py", line 85, in
from .services.contents.manager import ContentsManager

File "C:\Users\D3ll\Anaconda3\lib\site-packages\notebook\services\contents\manager.py", line 17, in
from nbformat import sign, validate as validate_nb, ValidationError

File "C:\Users\D3ll\Anaconda3\lib\site-packages\nbformat\__init__.py", line 32, in
from .validator import validate, ValidationError

File "C:\Users\D3ll\Anaconda3\lib\site-packages\nbformat\validator.py", line 12, in
from jsonschema import ValidationError

File "C:\Users\D3ll\Anaconda3\lib\site-packages\jsonschema\__init__.py", line 34, in
__version__ = metadata.version("jsonschema")

AttributeError: module 'importlib_metadata' has no attribute 'version'

A: The specific version of json was 3.0.2 in the anaconda prompt I typed:
pipenv install jsonschema==3.0.2
taken from:
https://blog.gaborschulz.com/my-jupyter-notebook-stopped-working.html

A: Have you tried reinstalling the module?
conda install importlib_metadata --force-reinstall


text:
Q: Sets and Notation. There is a set like:
$V = \{f : R \to R \mid f(x) = ax + c \text{ with } a, c \in \mathbb{R} \}$
I do not know what "$:$" means.
I do not know what "$|$" means.
I think the meaning is something like "is defined as" but i can not find more documentation.
What is the difference between "$:$" and "$|$"?
When do i use the one and when the other?
How would i use them in a spoken sentence?

Edit: changed x to V.
Edit: changed example to make more senese in general
Edit: changed example to improve even further.

A: It depends on the context.  Here is an example:
Consider both sets $\{ x \in \mathbb{R} : x < 2 \}$ and $\{ x \in \mathbb{R} | x < 2 \}$.
These sets both represent the same set.  The : and | should both be read as "such that".  So you read both sets as "the set of $x$ in $\mathbb{R}$ such that $x < 2$".

Now, when we define a function, say, $f: X \to Y$, the : is included after the name of the function, in this case $f$, and before the listing of the domain and codomain of the function.  So $f: X \to Y$ is how we start to define a function $f$ with domain (or input) from $X$ and codomain (or output) in $Y$.
The problem is in your example, $\{x : R \to R | x < 4\}$, we are using both : and |.  But the : looks like it is used as defining a function $x$ with domain $R$ and codomain $R$.  Then the | looks like it is a such that.  So, I would read this set as "the set of functions $x$ from $R$ to $R$ such that $x < 4$".
Now, does it really make sense to say functions are less than $4$?  No.  We usually say a function's output is less than $4$, so that makes me believe there is something wrong with the set you wrote down.  Is it possible you copied it down wrong?  But from a math language point of view, the set you wrote down can be read in plain English, as above.  It just doesn't appear to be a meaningful description.
(Although, there is a debate as many mathematicians use $x < 4$ for a function $x$ as shorthand to say for all inputs, the output is less than $4$, but this notation is rarely used in undergraduate courses, from my experience.)

EDIT
Ok, so you updated the set description.  Everything I said above is still true, only now your new set is also mathematically meaningful. $\{ f : R \to R \mid f(x) = ax + c \}$ is "the set of functions $f$ from $R$ to $R$ such that $f(x) = ax + c$".
As long as you know what $a$ and $c$ are, this makes sense.  If they remain variables, their description should be included in the set -- e.g., are they real numbers, or complex, etc?  If real, the set should look like $\{f : R \to R \mid f(x) = ax + c \text{ with } a, c \in \mathbb{R} \}$.


text:
Q: Can I revert a new MacOS X installation using a Time Machine backup? I regularly use Time Machine to create backups of my current macbook.
I am trying to upgrade to MacOS X Big Sur, but I was wondering what happens if I don't like it?
Is it possible to downgrade back to my current version of MacOS X using a Time Machine backup from just before upgrading the system?
I do not use any specialty boot up situation. I do not boot up from external drives.
It's just my laptop with its SSD. I keep larger files in external drives but OS X doesn't get installed to those drives.

A: The simple answer is yes.
If you have a complete Time Machine Backup of your system, wiping the disk and restoring the computer will install the macOS version of your TM Backup. You can read more about the full procedure on Macworld or on this blog or here.
The general procedure of downgrading macOS with a TM backup is the following:

*

*Make a TM Backup

*Shut down your machine and boot into recovery mode (press cmd + r right after boot chime)

*Connect your external TM Backup drive and select Restore From Time Machine Backup

*Continue and select your latest Backup to restore your machine

Edit: As Tetsujin mentioned in the comments, it is very important to unplug your TM drive before upgrading to the new OS and not reconnect afterwards. Ideally you get a second drive to start new Backups for the macOS version and not let the new Mac version touch the old Backup hard drive!

It is actually even possible to downgrade your macOS version without a TM Backup. You can read more about where to get the installers and more over here: How can I download an older version of macOS/OS X?


text:
Q: Update DynamoDB Entries at Specific Times I have a DynamoDB table where each entry has a time and a status. I would like to have DynamoDB update the status at the entry's specified time. What is the recommended way to do this without running a server? Basically I want to have TTL trigger a custom lambda instead of delete my entry, but I don't think this is possible.

A: You probably want to setup an AWS cloudwatch event that calls a lambda function on a schedule you decide.
The Lambda function can then update the DynamoDB data for you.
This will work as long as you are OK with scheduling things to happen at minute, or slower, intervals - i.e. you can't get things updated every second.

A: There are a couple of solutions for this.

*

*Using Lambda Scheduled Events (Create a Lambda function with a scheduled frequency to run and update the status if it matches the TTL).

*Using CloudWatch Events to Trigger a Lambda function which does the status update.

For the above two approaches, the time of update depends on the frequency the Lambda function executes.

*

*Use DynamoDB TTL to trigger a Lambda function once the specified TTL is reached. At this time you can change the status and create a new item. (The limitation of this approach is that DynamoDB can take up to 48 hours to delete an expired item, which can also delay the status change time up to 48 hours from specified)


text:
Q: ExpressJS - switching between multiple categories in API requests I'm currently fetching below API from http://localhost:3009/api/get-products/ .
How do I switch between 10 categories and search using other keywords ?
    app.get("/api/get-products",async (req, res) => {
    client.execute('affiliate.product.query', {
    'app_signature':'mcc',
    'category_ids':'111,222,333',  <--- query different categories
    'keywords':'shirt',            <--- query different search keyword
    'target_currency':'USD',
    'target_language':'EN',
  }

A: You should use query parameters that allow you to specify what keywords or categories you want to receive:
Look at that example:
https://example.com/over/there?name=ferret.
While passing a query like that, you are able to get name from req object.
Here you can find more about the query parameters in Node.js: How to get GET (query string) variables in Express.js on Node.js?


text:
Q: What's the best way to deal with a non-const-aware Library/SDK? I've been working for longer now with the 3ds max SDK, which in nearly all parts doesn't use const at all. So even a Width() or Height() getter of a Bitmap isn't marked as const. This has been already a real annoyance in small projects, but since I've been working on a larger project, it becomes increasingly terrible.
For example, I am holding a single Bitmap instance as a shared_ptr<Bitmap> member in multiple class instances out of performance reasons. Of course there are cases I want to avoid by all means that a single instance may change the properties for all instances, thus all raw pointer getters (necessary for the SDK) deliver a const Bitmap*. Unfortunately, now I can't even ask the const Bitmap* for its width - because Width() is non-const.
I'm asking myself what is the best way to deal with this. I see three options:

*

*Forget about const completely, make everything non-const. In the smaller projects I used to do this, but like I said, with more sophisticated techniques, it becomes more dangerous.

*Make an inplace const_cast at every place it's necessary. That will be at many places, and it's pretty bad to read.

*Write wrappers for the 3ds max classes, which provide const methods at least for the methods which are highly presumably safe. This would encapsulate all the const_cast in one place and be also suitable for other projects.

I have been warned (and I know) that this might be opinion-based. But I had to deal with this annoying problem for a long time now, and I'd really like to find a solution and thus need the experience of others.

A: First of all, I would like to mention that lack of const correctness may be justifiable by implementation details, for example getter function may perform lock on internal synchronization primitive and therefore always alters internal state and can not be marked as const:
int Bitmap::Width(void)
{
     int width{};
     ::std::lock_guard<::std::mutex> const lock{m_sync};
     width = m_width;
     return width;
}

As a workaround you can write a dedicated PImpl bitmap wrapper restricting direct access to bitmap implementation forwarding functions of interest with appropriate const qualifiers:
class SharedBitmap
{
    private: ::std::shared_ptr<Bitmap> m_p_bitmap;

    public: int Width(void) const
    {
        return m_p_bitmap->Width();
    }

    // other methods...
};

Note that this approach is different from third option listed in question as it does not involve const_cast.

A: In my experience (10yr), "const" has been a greater nusiance than it has been helpful. Not to mentions code getting longer, ergo harder to read. If you want to know how a library works, you read the manual anyway, not the header. If you want to know you did it right, you run functional tests. Hell there are even static analysis tools checking if a variable is ever written to, without burdening the code with useless non-functional metadata to capture undocumented usage patterns. And since there are a many ways to break const, it is the right way of capturing such errors.
In summary, option 1 is in my experience the most efficient solution. (Is this an opinion? Those who disagree will probably think so.)
For that quick post-purge of const you could do #define const or even -Dconst to remove it, though whether it is safe may depend on your specific scenario, one illegal use is doing this for the standard headers. I have done similar hacks like #define private|protected public instead of messing with friend when doing white box testing, works like a charm!
Know that the concept of "constant variable" is void in many programming languages and they seem to do just fine without it.
The only time you need const is in the case of C-string constants / string literals. Does not seem to be your case though.


text:
Q: PlotLegends don't match the plot's curves Can anyone help me make the legends(markers) match with the figure curves?
I have 2 figures that have three curves each, and then I have to combine them.
I used the following code for the first figure:
 p1 = ListLinePlot[Transpose[{k, #}] & /@ {K11s, K12s, K22s},
 PlotLegends ->
 Placed[LineLegend[{"K11", "K12", "K22"},
 LegendFunction -> (Framed[#1, FrameMargins -> 0] & )], {0.8,
  0.2}], FrameLabel -> {"k", "K"}, Axes -> True, Frame -> True,
  AxesStyle -> Directive[{Bold, 25}, {Black, 25}],
  BaseStyle -> {FontWeight -> Bold, FontSize -> 14},
   PlotRange -> All]

for the other figure I used this:
p2 = Legended[Show[
 ListLinePlot[Transpose[{k, #}] & /@ {K11b}, PlotStyle -> Red],
   ListLinePlot[Transpose[{k, #}] & /@ {K12b},
  PlotStyle -> {Dashing[Large], Thickness[Large], Blue}],
 ListLinePlot[Transpose[{k, #}] & /@ {K22b}, PlotStyle -> {Dashed}],
  AxesStyle -> Directive[{Bold, 25}, {Black, 25}],
 FrameLabel -> {"k", "K"}, Frame -> True, FrameTicks -> Automatic,
 ImageSize -> 700, Background -> Transparent, PlotRange -> All,
 BaseStyle -> {FontWeight -> Bold, FontSize -> 14}],
 Placed[LineLegend[{Red, {Dashing[Large], Thickness[Large],
  Blue}, {Dashed, Blue}}, {Style["fitted K11", 12],
  Style["fitted K12", 12], Style["fitted K22", 12]},
  LegendMargins -> {{0, 0}, {0, 0}},
  LegendFunction -> (Framed[#1, FrameMargins -> 0] & ) ,
  LabelStyle -> {(FontFamily -> "Helvetica"),
   FontWeight -> Bold}], {0.4, 0.8}]]

Then I combined them using "Show".
My problem with the second one is the markers do not match the one in the plot.Also is there another way to make these plots in one graph rather than using "Show" with keeping the legends bar inside the graph?

A: SeedRandom[1]
k = Range[10];
{K11s, K12s, K22s} = RandomInteger[10, {3, 10}];
{K11b, K12b, K22b} = {K11s, K12s, K22s} + RandomReal[{-1, 1}, {3, 10}];

ListLinePlot[Transpose[{k, #}] & /@ {K11s, K12s, K22s, K11b, K12b, K22b},
 PlotStyle -> {Automatic, Automatic, Automatic,
   Red, Directive[Dashing[Large], Thickness[Large], Blue], Directive[Dashed, Blue]},
 PlotLegends -> Placed[
   LineLegend[
     Flatten[{#, "fitted " <> # & /@ #}] &@{"K11", "K12", "K22"},
     LegendLayout -> {"Column", 2},
     LegendMarkerSize -> {40, 20},
     LegendFunction -> (Framed[#1, FrameMargins -> 0] &)],
   {0.35, 0.85}],
 FrameLabel -> {"k", "K"}, Axes -> True, Frame -> True,
 AxesStyle -> Directive[{Bold, 25}, {Black, 25}],
 BaseStyle -> {FontWeight -> Bold, FontSize -> 14}, PlotRange -> All]


text:
Q: Is it a bad practice to use an Input Type for a graphql Query? I have seen that inserting an Input Type is recommended in the context of mutations but does not say anything about queries.
For instance, in learn tutorial just say:

This is particularly valuable in the case of mutations, where you might want to pass in a whole object to be created

I have this query:
type query {
    person(personID: ID!): Person
    brazilianPerson(rg: ID!): BrazilizanPerson
    foreignerPerson(passport: ID!): ForeignerPerson
}

Instead of having a different type just because of the name (rg, passport) of the fields, or put one more argument like type in query, I could not just have the Person with an documentNr field and do an Input type like that?
input PersonInput {
   documentNr : ID!
   type: PersonType # this type is Foreign or Brazilian and with this I k
}

PersonType is a enum and with him I know if the document is a rg or a passport.

A: No, there is nothing incorrect about your approach. The GraphQL spec allows any field to have an argument and allows any argument to accept an Input Object Type, regardless of the operation. In fact, the differences between a query and a mutation are largely symbolic.
It's worth pointing out that any field can accept an argument -- not just ones at the root level. So if it suited your needs, you could easily set up a schema that would allow queries like:
query {
  person(id: 1) {
    powers(onlyMutant: true) {
      name
    }
  }
}


text:
Q: module 'virtualenv.create.via_global_ref.builtin.cpython.mac_os' has no attribute 'CPython2macOsArmFramework I am trying to install python packages to a venv using poetry - on BigSur macos.
I have pyenv on stable python.
pyenv which python
/Users/josh/.pyenv/versions/3.8.6/bin/python

When I exec.

poetry shell && poetry install

I get this error but do not know what to do with it.
  AttributeError

  module 'virtualenv.create.via_global_ref.builtin.cpython.mac_os' has no attribute
'CPython2macOsArmFramework'

  at ~/.pyenv/versions/3.8.2/lib/python3.8/importlib/metadata.py:79 in load
       75│         """
       76│         match = self.pattern.match(self.value)
       77│         module = import_module(match.group('module'))
       78│         attrs = filter(None, (match.group('attr') or '').split('.'))
       79│         return functools.reduce(getattr, attrs, module)
       80│
       81│     @property
       82│     def extras(self):
       83│         match = self.pattern.match(self.value)

Any ideas of what to troubleshoot welcome!

A: I got this error today. I'm on Ubuntu, python 3.8.10 (pyenv managed). So seeing an error with mac_os in the message felt weird. On further debugging, found that the reason behind the issue was that some other package had installed virtualenv as a dependency in my local venv. We need to get rid of it.
And the culprit package was pre-commit. Uninstalled it from local venv for now. Installing rest of the packages works without any error.

A: I faced this issue after upgrading python from 3.9.5 to 3.9.12
I resolved it by switching from the online installer, which is deprecated, to installing through pip
Before:
export POETRY_VERSION=1.1.4
curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python

After:
export POETRY_VERSION=1.1.4
pip install "poetry==$POETRY_VERSION"


text:
Q: Are SQL Server unique constraints "Silent" or do they raise an exception? I want to prevent inserting duplicate values into my tables. At first, I added code to check if the value already existed in the database, but that seems like a lot of overhead / wasted time if I can prevent it at the DDL level.
So I found this and changed one of my tables (as an example) from this:
CREATE TABLE [dbo].[ACTORS]
(
    [Id]      INT IDENTITY (1, 1) NOT NULL,
    [ActorId] CHAR(9)     NOT NULL,
    [Actor]   VARCHAR(50) NOT NULL,

    PRIMARY KEY CLUSTERED ([Id] ASC),
);

to this:
CREATE TABLE [dbo].[ACTORS]
(
    [Id]      INT IDENTITY (1, 1) NOT NULL,
    [ActorId] CHAR(9)     NOT NULL,
    [Actor]   VARCHAR(50) NOT NULL,

    PRIMARY KEY CLUSTERED ([Id] ASC),

    CONSTRAINT [CK_ACTORS_Column]
        UNIQUE NONCLUSTERED ([ActorId] ASC)
);

I want the constraint to prevent a second identical ActorId without whin[g]ing about it. IOW, just bypass it, don't tell me about it, don't stop the app or throw an exception.
Is this how it works (silently), or will it throw an exception?

A: @GMB wrote in his answer "SQL Server has built-in no option (that I know about) to ignore such error".
As @a_horse_with_no_name pointed out in the comment, there is an IGNORE_DUP_KEY option of an index that is relevant here.
You said:

I want the constraint to prevent a second identical ActorId without
whin[g]ing about it. IOW, just bypass it, don't tell me about it,
don't stop the app or throw an exception.

It can be achieved with this option.

At first, I should point out that when you create a unique constraint
CONSTRAINT [CK_ACTORS_Column] UNIQUE NONCLUSTERED ([ActorId] ASC)

the engine will create a unique index to enforce the constraint. The constraint is a logical concept, the index is a physical implementation of the concept.
You can achieve the same effect by creating just an index, a unique index. When you create an index you can specify various options, including the IGNORE_DUP_KEY option.

IGNORE_DUP_KEY = { ON | OFF }
Specifies the error response when an
insert operation attempts to insert duplicate key values into a unique
index. The IGNORE_DUP_KEY option applies only to insert operations
after the index is created or rebuilt. The option has no effect when
executing CREATE INDEX, ALTER INDEX, or UPDATE. The default is OFF.
ON A warning message will occur when duplicate key values are inserted
into a unique index. Only the rows violating the uniqueness constraint
will fail.
OFF An error message will occur when duplicate key values are inserted
into a unique index. The entire INSERT operation will be rolled back.

By default this option is OFF, so an attempt to insert a duplicate key value will fail with an error. The server will roll back the INSERT operation and send this error message to your application and it will depend on your application how to handle it. If your application doesn't expect it, it will likely throw some exception.
If you set this option to ON, your application will no longer receive an error message. It will receive a warning message, which most applications usually ignore. So, it will look like the server silently ignores duplicate values and inserts only those values that are not duplicates.
It is rarely a desired behaviour to silently ignore problems, but if you really know what you are doing, you can do it.

Here is a short demo.
Let's start with your table
CREATE TABLE [dbo].[ACTORS]
(
    [Id]      INT IDENTITY (1, 1) NOT NULL,
    [ActorId] CHAR(9)     NOT NULL,
    [Actor]   VARCHAR(50) NOT NULL,

    PRIMARY KEY CLUSTERED ([Id] ASC),
);

Option 1. Default. IGNORE_DUP_KEY = OFF
CREATE UNIQUE NONCLUSTERED INDEX [IX_ActorID] ON [dbo].[ACTORS]
(
    [ActorId] ASC
) WITH (IGNORE_DUP_KEY = OFF)

The table is empty. Let's try to insert some values.
insert into actors (actorid, actor) values('foo', 'bar');

-- (1 row affected)

Let's try to insert a duplicate value:
insert into actors (actorid, actor) values('foo', 'baz');

--Msg 2601, Level 14, State 1, Line 4
--Cannot insert duplicate key row in object 'dbo.ACTORS' with unique index 'IX_ActorID'.
--The duplicate key value is (foo      ).
--The statement has been terminated.

Let's try to insert several values in a single statement with some duplicates:
insert into actors (actorid, actor) values
('foo', 'baz'),
('fo2', 'baz'),
('fo2', 'baz'),
('fo3', 'baz'),
('fo3', 'baz'),
('fo3', 'baz'),
('fo4', 'baz');

--Msg 2601, Level 14, State 1, Line 16
--Cannot insert duplicate key row in object 'dbo.ACTORS' with unique index 'IX_ActorID'.
--The duplicate key value is (foo      ).
--The statement has been terminated.

Let's see what we have in the table now.
SELECT * FROM Actors;

+----+-----------+-------+
| Id |  ActorId  | Actor |
+----+-----------+-------+
|  1 | foo       | bar   |
+----+-----------+-------+

Only the first INSERT statement succeeded and only one row was inserted.
Now, clean up.
DROP INDEX [IX_ActorID] ON [dbo].[ACTORS];
TRUNCATE TABLE dbo.Actors;

Option 2. IGNORE_DUP_KEY = ON
CREATE UNIQUE NONCLUSTERED INDEX [IX_ActorID] ON [dbo].[ACTORS]
(
    [ActorId] ASC
) WITH (IGNORE_DUP_KEY = ON)

The table is empty. Let's try to insert some values.
insert into actors (actorid, actor) values('foo', 'bar');

-- (1 row affected)

Let's try to insert a duplicate value:
insert into actors (actorid, actor) values('foo', 'baz');

--Duplicate key was ignored.
--(0 rows affected)

As you can see, now it is not an error message. It is just a warning "Duplicate key was ignored."
Let's try to insert several values in a single statement with some duplicates:
insert into actors (actorid, actor) values
('foo', 'baz1'),
('fo2', 'baz2'),
('fo2', 'baz3'),
('fo3', 'baz4'),
('fo3', 'baz5'),
('fo3', 'baz6'),
('fo4', 'baz7');

--Duplicate key was ignored.
--(3 rows affected)

Here you can see that out of 7 rows only 3 rows were inserted.
Let's see what we have in the table now.
SELECT * FROM Actors;

+----+-----------+-------+
| Id |  ActorId  | Actor |
+----+-----------+-------+
|  1 | foo       | bar   |
|  4 | fo2       | baz2  |
|  6 | fo3       | baz4  |
|  9 | fo4       | baz7  |
+----+-----------+-------+

You can see that the last INSERT statement inserted non-duplicate values. Also, have a close look at the values in ID column. The IDENTITY values have gaps, because they were generated for each row that was attempted to be inserted and some of these rows were rejected by the unique index.

Overall, this index option is designed primarily for the cases when you need to insert a lot of rows in bulk, in a single INSERT statement, but you expect that some of these row may violate the unique constraint. You don't want the whole large INSERT statement to fail, you want only few violating rows to be ignored. Without this option you would have to try to insert your values one-by-one, row-by-row, which may be much slower than a single INSERT statement.

A: Let's try that:
insert into actors (actorid,actor) values('foo', 'bar');
-- 1 row affected

insert into actors (actorid, actor) values('foo', 'baz');
-- Msg 2627 Level 14 State 1 Line 1
-- Violation of UNIQUE KEY constraint 'CK_ACTORS_Column'.
-- Cannot insert duplicate key in object 'dbo.ACTORS'. The duplicate key value is (foo      ).

A unique constraint violation does raise an error. This is how the database lets you know that something went wrong.
SQL Server has built-in no option (that I know about) to ignore such error, unlike many other databases (MySQL, Postgres, SQLite...). A workaround is to rewrite the insert with not exists and a subquery:
insert into actors (actorid, actor)
select v.*
from (values ('foo', 'bar')) v(actorid, actor)
where not exists (select 1 from actor a where a.actorid = v.actorid)

Another option is the merge statement:
merge into actors a
using (values ('foo', 'bar')) v(actorid, actor)
on v.actorid = a.actorid
when not matched then insert (actorid, actor)
values (v.actorid, v.actor)


text:
Q: Protocol buffer3 and json Protocol buffer v3 claims, that library is json friendly (https://developers.google.com/protocol-buffers/docs/proto3#json), but I cannot find how to achieve get that mapping. Should I add some plugin, or some option into protoc, or call something special instead SerializeTo/ParseFrom?
Is it someone who use that feature?

A: I'm using Protobuf 3.3.0, which does have a built-in JSON serializer and parser. You can use 2 functions from google/protobuf/util/json_util.h called MessageToJsonString() and JsonStringToMessage() to make your C++ generated Message objects go to and from JSON respectively.
Here's a simple test that uses them:
test-protobuf.proto:
syntax = "proto3";

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}

test-protobuf.cpp:
#include <iostream>
#include <google/protobuf/util/json_util.h>

#include "test-protobuf.pb.h"

int main()
{
  std::string json_string;
  SearchRequest sr, sr2;

  // Populate sr.
  sr.set_query(std::string("Hello!"));
  sr.set_page_number(1);
  sr.set_result_per_page(10);

  // Create a json_string from sr.
  google::protobuf::util::JsonPrintOptions options;
  options.add_whitespace = true;
  options.always_print_primitive_fields = true;
  options.preserve_proto_field_names = true;
  MessageToJsonString(sr, &json_string, options);

  // Print json_string.
  std::cout << json_string << std::endl;

  // Parse the json_string into sr2.
  google::protobuf::util::JsonParseOptions options2;
  JsonStringToMessage(json_string, &sr2, options2);

  // Print the values of sr2.
  std::cout
    << sr2.query() << ", "
    << sr2.page_number() << ", "
    << sr2.result_per_page() << std::endl
  ;

  return 0;
}

You can compile these files (assuming that you have protobuf, a compiler, and CMake installed) by using the following CMakeLists.txt file (tested on Windows).
cmake_minimum_required(VERSION 3.8)

project(test-protobuf)

find_package(Protobuf REQUIRED)

# Use static runtime for MSVC
if(MSVC)
  foreach(flag_var
      CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
      CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES "/MD")
      string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
    endif(${flag_var} MATCHES "/MD")
  endforeach(flag_var)
endif(MSVC)

protobuf_generate_cpp(test-protobuf-sources test-protobuf-headers
  "${CMAKE_CURRENT_LIST_DIR}/test-protobuf.proto"
)

list(APPEND test-protobuf-sources
  "${CMAKE_CURRENT_LIST_DIR}/test-protobuf.cpp"
)

add_executable(test-protobuf ${test-protobuf-sources} ${test-protobuf-headers})
target_include_directories(test-protobuf
  PUBLIC
    ${PROTOBUF_INCLUDE_DIRS}
    ${CMAKE_CURRENT_BINARY_DIR}
)
target_link_libraries(test-protobuf
  ${PROTOBUF_LIBRARIES}
)

Assuming that CMakeLists.txt, test-protobuf.proto, and test-protobuf.cpp are in the same directory, here are the commands to compile and run them on Windows with Visual Studio 15 2017 and 64-bit protobuf libraries.
mkdir build
cd build
cmake -G "Visual Studio 15 2017 Win64" ..
cmake --build . --config Release
Release/test-protobuf

You should see the following output:
{
 "query": "Hello!",
 "page_number": 1,
 "result_per_page": 10
}

Hello!, 1, 10

A: Protobuf has json api for C#. There are some json class for C# in google protobuf reference and You can find some tests in github protobuf repository for java and c++.


text:
Q: Regex to match variable number of annotations I have a string that has variable number of annotations, the goal is to get

(1) the annotation type,
(2) the annotated string, and
(3) get the original string without annotation.

e.g., Let's try /A_RESTAURANT(Burger King). It is at /A_LOCATION(DOWNTOWN Chicago).
I was able to write regex to match single annotations. But has no clue to do multiple annotations.
(.*)\/(A_.*)\((.*)\)(.*)

A: Here is a function to get your goals:
import re

regex = re.compile(r"/A_(?P<a_type>[^()]*)\((?P<a_string>.*?)\)")

def process(text):
    def helper(matchobject):
        annotations.append((matchobject['a_type'], matchobject['a_string']))
        return matchobject['a_string']

    annotations = []

    clean_text = regex.sub(helper, text)

    return clean_text, annotations

A test:
text = "Let's try /A_RESTAURANT(Burger King). It is at /A_LOCATION(DOWNTOWN Chicago)."

clean_string, annotations = process(text)

print(clean_string)
print(annotations)

Output:
Let's try Burger King. It is at DOWNTOWN Chicago.
[('RESTAURANT', 'Burger King'), ('LOCATION', 'DOWNTOWN Chicago')]


text:
Q: Postgres SQL error: there is no unique or exclusion constraint matching the ON CONFLICT specification" DESPITE constrain being set (sorry, there are many similar questions on SO but none I could find that match well enough)
Attempting to upsert to a Postgres RDS table via a temp table...
import sqlalchemy as sa

# assume db_engine is already set up

with db_engine.connect() as conn:

            conn.execute(sa.text("DROP TABLE IF EXISTS temp_table"))
            build_temp_table = f"""
                CREATE TABLE temp_table (
                unique_id        VARCHAR(40) NOT NULL,
                date             TIMESTAMP,
                amount           NUMERIC,
                UNIQUE (unique_id)
                );
                """
            conn.execute(sa.text(build_temp_table))

            upsert_sql_string = """
                INSERT INTO production_table(unique_id, date, amount)
                SELECT unique_id, date, amount FROM temp_table
                ON CONFLICT (unique_id)
                DO UPDATE SET
                            date = excluded.date,
                            amount  = excluded.amount
                """
            conn.execute(sa.text(upsert_sql_string))

Note: production_table is configured the identically to temp_table
Other methods I have tried include:

*

*Specifying unique_id as PRIMARY KEY or UNIQUE in table definition

*Running ALTER TABLE temp_table ADD PRIMARY KEY (unique_id) after creating temp_table
Regardless of what I do, I get the error:
psycopg2.errors.InvalidColumnReference: there is no unique or exclusion constraint matching the ON CONFLICT specification
Thanks


text:
Q: Need help in translating C++ to C# I don't know C++ very well especially the IO part. Can anyone please help me to translate the following C++ code into C#?
unsigned *PostingOffset, *PostingLength, NumTerms;

void LoadSubIndex(char *subindex) {
  FILE *in = fopen(subindex, "rb");
  if (in == 0) {
    printf("Error opening sub-index file '%s'!\n", subindex);
    exit(EXIT_FAILURE);
  }
  int len=0;
  // Array of terms
  char **Term;
  char *TermList;
  fread(&NumTerms, sizeof(unsigned), 1, in);
  PostingOffset = (unsigned*)malloc(sizeof(unsigned) * NumTerms);
  PostingLength = (unsigned*)malloc(sizeof(unsigned) * NumTerms);
  Term = (char**)malloc(sizeof(char*) * NumTerms);
  Term = (char**)malloc(sizeof(char*) * NumTerms);
  // Offset of each posting
  fread(PostingOffset, sizeof(unsigned), NumTerms, in);
  // Length of each posting in bytes
  fread(PostingLength, sizeof(unsigned), NumTerms, in);
  // Number of bytes in the posting terms array
  fread(&len, sizeof(unsigned), 1, in);
  TermList = (char*)malloc(sizeof(char) * len);
  fread(TermList, sizeof(unsigned)*len, 1, in);

  unsigned k=1;
  Term[0] = &TermList[0];
  for (int i=1; i<len; i++) {
    if (TermList[i-1] == '\0') {
      Term[k] = &TermList[i];
      k++;
    }
  }
  fclose(in);
}

Thanks in advance.

A: I'll give you a headstart.
using(var reader = new BinaryReader(new FileStream(subindex, FileMode.Open)) {
    int numTerms = reader.ReadUInt32();
    postingOffset = new UInt32[numTerms];
    postingLength = new UInt32[numTerms];
    var term = new byte[numTerms];
    for(int i=0;i<numTerms;i++)
        postingOffset[i] = reader.ReadUInt32();
    for(int i=0;i<numTerms;i++)
        postingLength[i] = reader.ReadUInt32();
    var len = reader.ReadInt32();
    var termList = new ... // byte[] or uint32[] ??
    //etc
}

There's no need to close the file handle here - it will close when the using { } block loses scope.
I didn't finish it because there are some flaws in your code. With TermList you are reading in 4 times as much data as you've allocated. You shouldn't be allocating Term twice either - that will result in leaking memory.
To turn Term back into a string, use Encoding.ASCII.GetString(term).TrimEnd('\0');