text:
Q: "package org.junit does not exist" when running first time I am working on a little schoolproject. Whenever I get my code from Git, the following errors appear when running it for the first time:
"package org.junit does not exist"
"package org.junit.runners does not exist"
"cannot find symbol"

When I run the project for a second time, everything works as expected. This is very annoying because I want to run the project in Jenkins with source code import from Git so it has to work the first time.
I checked my build path in Eclipse, but JUnit5 is included from the start.
I don't know if something is wrong with my pom, everything seems fine as far as my knowledge goes.
<dependencies>
    <!-- Selenium dependencies -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.141.59</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.141.59</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>
    <dependency>
        <groupId>io.github.bonigarcia</groupId>
        <artifactId>webdrivermanager</artifactId>
        <version>4.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-params</artifactId>
        <version>5.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.25</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>3.0.0-M4</version>
        <type>maven-plugin</type>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.7</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19</version>
            <configuration>
                <parallel>all</parallel>
                <threadCount>10</threadCount>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.0.0</version>
                </dependency>
            </dependencies>
        </plugin>
        <plugin>
            <artifactId>maven-clean-plugin</artifactId>
            <version>3.1.0</version>
        </plugin>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.0.2</version>
        </plugin>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>13</source>
                <target>13</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
        </plugin>
        <plugin>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.5.2</version>
        </plugin>
        <plugin>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.8.2</version>
        </plugin>
        <plugin>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.7.1</version>
        </plugin>
    </plugins>
</build>

A: I have resolved my own problem.
After a Merge a collegue added some tests, configured in an older version of JUnit.  That's why it failed. After adding JUnit 4 to my POM my problem was solved. Updating the tests to the JUnit 5n should also solve the problem.


text:
Q: React Hooks: setState hook inside map function Im currently wrestling with the async nature of setState with a form, my intended behaviour is that when the user clicks on the submitForm button it checks all the form values inside the state if that value is empty it then sets the errorState for that specific form element so that an error message appears
  const [values, setValues] = React.useState({
    firstName: '',
    lastName: '',
    id: '',
    city: '',
    emailAddress:'',
    mobileNumber: ''
  });

  const [errors, setError] = React.useState({
    firstName: false,
    lastName: false,
    id: false,
    city: false,
    emailAddress: false,
    mobileNumber: false
  })

  const submitForm = () => {
    const setErrorArray = Object.keys(values).map((key) => {
      if (values[key] === '') {
        setError({...errors, [key]: true })
      }
    });
  }

I believe the issue is due to setState being async, so after the .map is done it sets only the last value inside the errors object to be true (thus errors.mobileNumber = true). Instead of making all the values that match the condition to be true. The spread operator {...errors} is overwriting the values to the initial false value.Is there anyway to achieve that each key inside errors is set to true if the value inside the values array is empty ??
Please any help will be greatly appreciated

A: I'd construct the whole new errors object at once by mapping the entries of the values, and then you can call setError with that object:

const values = {
    firstName: 'first',
    lastName: 'last',
    id: '',
    city: '',
};
const newErrors = Object.fromEntries(
  Object.entries(values).map(
    ([key, val]) => [key, val === '']
  )
);
console.log(newErrors);
// setError(newErrors);

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# PDFSharp transparent Text I am making a searchable PDF using C# and PDFSharp.  Basically - I run the PDF image through a separate OCR application to get the text and then I open the PDF (using PDFSharp) and write the text over the PDF image.  All of this works.  User then open the final PDF - search for text in the PDF and it highlights the spot in the PDF that has the text.
Problem is - writing text over the PDF - blocks the original PDF image.  I want to write transparent text over the PDF.  So the text is there - but the text is not visible to humans
This example shows how to do it - but it does not work
http://www.pdfsharp.net/wiki/Graphics-sample.ashx#Show_how_to_get_text_metric_information_19
My code is:
            XColor transparentColor = XColors.White;
            transparentColor.A = 0;
            XSolidBrush transparentBrush = new XSolidBrush(transparentColor);

                    xTextFormatter.DrawString(block.Text, font, transparentBrush, xRect);

Some posts I found talked about how it had to be done in CMYK space.  I found this example
http://www.pdfsharp.net/wiki/ColorsCMYK-sample.ashx
And tried this code
            XColor transparentColor = XColor.FromCmyk(0, 0, 0, 0);
            XSolidBrush transparentBrush = new XSolidBrush(transparentColor);

                newPdfDocument.Options.ColorMode = PdfColorMode.Cmyk;

                    xTextFormatter.DrawString(block.Text, font, transparentBrush, xRect);

Both tests produce white text over top of the PDF image.  Any ideas?  Thanks!

A: It appears that the opacity (alpha) flag works opposite of what it should in version 1.50.5147 of PDFSharp I got from NuGet.org.  @RebootDeluxe should have been correct.  But what works - is the opposite.  XSolidBrush(XColor.FromArgb(1, 0, 0, 0));.


text:
Q: Linker does not recognize (generated) methods if the count of methods is high enough I have a weird problem with the linker (appears with different compilers).
I'm genreating kernels like that:
inline void doSomething3() {
  #pragma omp for simd nowait schedule(static, chunkSize)
  for (int i = 0; i < size_mat; ++i) {
    matrix[i] +=
            buffer->threadedData[1].matr[i]
        +   buffer->threadedData[2].matr[i];
    buffer->threadedData[1].matr[i] = 0.0;
    buffer->threadedData[2].matr[i] = 0.0;
  }

This is an example for 3 threads where the buffers of thread 1 and 2 are added up to another buffer. But the content of the kernel is not the important part.
Basically, I'm generating lets say 16 of such kernels with names
doSomething2(), doSomething3(), doSomething4() and so on. Each are different in the number of arrays they sum up.
These kernels are generated via boost and preprocessor directives. And this generation works fine (as one can check in the output of the preprocessor).
Now, it looks like that the linker gets into trouble when increasing the number of kernels at some point.
Usually, I'm generating 16 kernels (times 8 since I have different things to sumup). This works fine for Intel compiler and Clang. GCC and GCC on 32 bit do not accept that many kernels. I get a linker error there (even if the kernels are correctly generated) and the maximum number is 8 for GCC. When switching to debug mode, the number is even smaller (in debug mode also for Clang and Intel, 16 is not possible). So far, so strange.
/opt/gcc/11.2.0/linux70_64/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../x86_64-pc-linux-gnu/bin/ld: CMakeFiles/my.dir/omp_sumUp/omp_sumUp.c.o: in function `doSomething_matrix':
omp_sumUp.c:(.text+0xedb1): undefined reference to 'doSomething16'
/opt/gcc/11.2.0/linux70_64/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../x86_64-pc-linux-gnu/bin/ld: omp_sumUp.c:(.text+0x110b1): undefined reference to 'doSomething13'
/opt/gcc/11.2.0/linux70_64/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../x86_64-pc-linux-gnu/bin/ld: omp_sumUp.c:(.text+0x110c9): undefined reference to 'doSomething14'
/opt/gcc/11.2.0/linux70_64/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../x86_64-pc-linux-gnu/bin/ld: omp_sumUp.c:(.text+0x110e1): undefined reference to 'doSomething15'

Now, a colleague changed some part in the code in another place and this also changed the number of kernels which can be treated by the linker. WTF?
Originally, I expected the generation of the kernels to be the problem, but as mentioned, there everything works fine. The compiler did also his job as I could see the kernels in the optimization report. So, the linker remains.
Does anybody have a clue what the issue of the linker is (overflow on number of methods?) and how to solve it?


text:
Q: Script produces wrong results when linebreak comes into play I've written a script in python to scrape some disorganized content located within b tags and thier next_sibling from a webpage. The thing is my script fails when linebreaks come between. I'm trying to extract the title's and their concerning description from that page starting from CHIEF COMPLAINT: Bright red blood per rectum to just before Keywords:.
Website address
I've tried so far with:
import requests
from bs4 import BeautifulSoup

url = 'https://www.mtsamples.com/site/pages/sample.asp?Type=24-Gastroenterology&Sample=941-BloodperRectum'

res = requests.get(url)
soup = BeautifulSoup(res.text,'lxml')
for item in soup.select_one("hr").find_next_siblings('b'):
    print(item.text,item.next_sibling)

The portion of output giving me unwanted results are like:
LABS:

CBC:

CHEM 7:

How can I get the titles and their concerning description accordingly?

A: Here's a scraper that's more robust compared to yesterday's solutions.

*

*How to loop through scraping multiple documents on multiple web pages using BeautifulSoup?

*How can I grab the entire body text from a web page using BeautifulSoup?
It extracts, title, description and all sections properly
import re
import copy
import requests
from bs4 import BeautifulSoup, Tag, Comment, NavigableString
from urllib.parse import urljoin
from pprint import pprint
import itertools
import concurrent
from concurrent.futures import ThreadPoolExecutor

BASE_URL = 'https://www.mtsamples.com'

def make_soup(url: str) -> BeautifulSoup:
    res = requests.get(url)
    res.raise_for_status()
    html = res.text
    soup = BeautifulSoup(html, 'html.parser')
    return soup

def clean_soup(soup: BeautifulSoup) -> BeautifulSoup:
    soup = copy.copy(soup)
    h1 = soup.select_one('h1')
    kw_re = re.compile('.*Keywords.*', flags=re.IGNORECASE)
    kw = soup.find('b', text=kw_re)

    for el in (*h1.previous_siblings, *kw.next_siblings):
        el.extract()
    kw.extract()
    for ad in soup.select('[id*="ad"]'):
        ad.extract()
    for script in soup.script:
        script.extract()
    for c in h1.parent.children:
        if isinstance(c, Comment):
            c.extract()
    return h1.parent

def extract_meta(soup: BeautifulSoup) -> dict:
    h1 = soup.select_one('h1')
    title = h1.text.strip()

    desc_parts = []
    desc_re = re.compile('.*Description.*', flags=re.IGNORECASE)
    desc = soup.find('b', text=desc_re)
    hr = soup.select_one('hr')
    for s in desc.next_siblings:
        if s is hr:
            break
        if isinstance(s, NavigableString):
            desc_parts.append(str(s).strip())
        elif isinstance(s, Tag):
            desc_parts.append(s.text.strip())
    description = '\n'.join(p.strip() for p in desc_parts if p.strip())

    return {
        'title': title,
        'description': description
    }

def extract_sections(soup: BeautifulSoup) -> list:
    titles = [b for b in soup.select('b') if b.text.isupper()]

    parts = []
    for t in titles:
        title = t.text.strip(': ').title()
        text_parts = []
        for s in t.next_siblings:
            # walk forward until we see another title
            if s in titles:
                break
            if isinstance(s, Comment):
                continue
            if isinstance(s, NavigableString):
                text_parts.append(str(s).strip())
            if isinstance(s, Tag):
                text_parts.append(s.text.strip())
        text = '\n'.join(p for p in text_parts if p.strip())
        p = {
            'title': title,
            'text': text
        }
        parts.append(p)
    return parts

def extract_page(url: str) -> dict:
    soup = make_soup(url)
    clean = clean_soup(soup)
    meta = extract_meta(clean)
    sections = extract_sections(clean)
    return {
        **meta,
        'sections': sections
    }

url = 'https://www.mtsamples.com/site/pages/sample.asp?Type=24-Gastroenterology&Sample=941-BloodperRectum'
page = extract_page(url)
pprint(page, width=2000)

output:
{'description': 'Status post colonoscopy.  After discharge, experienced bloody bowel movements and returned to the emergency department for evaluation.\n(Medical Transcription Sample Report)',
 'sections': [{'text': 'Bright red blood per rectum', 'title': 'Chief Complaint'},
              # some elements removed for brevity
              {'text': '', 'title': 'Labs'},
              {'text': 'WBC count: 6,500 per mL\nHemoglobin: 10.3 g/dL\nHematocrit:31.8%\nPlatelet count: 248 per mL\nMean corpuscular volume: 86.5 fL\nRDW: 18%', 'title': 'Cbc'},
              {'text': 'Sodium: 131 mmol/L\nPotassium: 3.5 mmol/L\nChloride: 98 mmol/L\nBicarbonate: 23 mmol/L\nBUN: 11 mg/dL\nCreatinine: 1.1 mg/dL\nGlucose: 105 mg/dL', 'title': 'Chem 7'},
              {'text': 'PT 15.7 sec\nINR 1.6\nPTT 29.5 sec', 'title': 'Coagulation Studies'},
              {'text': 'The patient receive ... ula.', 'title': 'Hospital Course'}],
 'title': 'Sample Type / Medical Specialty:  Gastroenterology\nSample Name: Blood per Rectum'}

A: Code:
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = 'https://www.mtsamples.com/site/pages/sample.asp?Type=24-Gastroenterology&   Sample=941-BloodperRectum'
res = urlopen(url)
html = res.read()
soup = BeautifulSoup(html,'html.parser')

# Cut the division containing required text,used Right Click and Inspect element in broweser to find the respective div/tag
sampletext_div = soup.find('div', {'id': "sampletext"})
print(sampletext_div.find('h1').text) # TO print header

Output:
Sample Type / Medical Specialty:  Gastroenterology
Sample Name: Blood per Rectum

Code:
# Find all the  tag
b_all=sampletext_div.findAll('b')
for b in b_all[4:]:
    print(b.text, b.next_sibling)

Output:
CHIEF COMPLAINT:  Bright red blood per rectum
HISTORY OF PRESENT ILLNESS:  This 73-year-old woman had a recent medical history significant for renal and bladder cancer, deep venous thrombosis of the right lower extremity, and anticoagulation therapy complicated by lower gastrointestinal bleeding. Colonoscopy during that admission showed internal hemorrhoids and diverticulosis, but a bleeding site was not identified. Five days after discharge to a nursing home, she again experienced bloody bowel movements and returned to the emergency department for evaluation.
REVIEW OF SYMPTOMS:  No chest pain, palpitations, abdominal pain or cramping, nausea, vomiting, or lightheadedness. Positive for generalized weakness and diarrhea the day of admission.
PRIOR MEDICAL HISTORY:  Long-standing hypertension, intermittent atrial fibrillation, and hypercholesterolemia. Renal cell carcinoma and transitional cell bladder cancer status post left nephrectomy, radical cystectomy, and ileal loop diversion 6 weeks prior to presentation, postoperative course complicated by pneumonia, urinary tract infection, and retroperitoneal bleed. Deep venous thrombosis 2 weeks prior to presentation, management complicated by lower gastrointestinal bleeding, status post inferior vena cava filter placement.
MEDICATIONS:  Diltiazem 30 mg tid, pantoprazole 40 mg qd, epoetin alfa 40,000 units weekly, iron 325 mg bid, cholestyramine. Warfarin discontinued approximately 10 days earlier.
ALLERGIES:  Celecoxib (rash).
SOCIAL HISTORY:  Resided at nursing home. Denied alcohol, tobacco, and drug use.
FAMILY HISTORY:  Non-contributory.
PHYSICAL EXAM:

LABS:

CBC:

CHEM 7:

COAGULATION STUDIES:

HOSPITAL COURSE:  The patient received 1 liter normal saline and diltiazem (a total of 20 mg intravenously and 30 mg orally) in the emergency department. Emergency department personnel made several attempts to place a nasogastric tube for gastric lavage, but were unsuccessful. During her evaluation, the patient was noted to desaturate to 80% on room air, with an increase in her respiratory rate to 34 breaths per minute. She was administered 50% oxygen by nonrebreadier mask, with improvement in her oxygen saturation to 89%. Computed tomographic angiography was negative for pulmonary embolism.
Keywords:
    gastroenterology, blood per rectum, bright red, bladder cancer, deep venous thrombosis, colonoscopy, gastrointestinal bleeding, diverticulosis, hospital course, lower gastrointestinal bleeding, nasogastric tube, oxygen saturation, emergency department, rectum, thrombosis, emergency, department, gastrointestinal, blood, bleeding, oxygen,

 NOTE : These transcribed medical transcription sample reports and examples are provided by various users and
        are for reference purpose only. MTHelpLine does not certify accuracy and quality of sample reports.
        These transcribed medical transcription sample reports may include some uncommon or unusual formats;
        this would be due to the preference of the dictating physician. All names and dates have been
        changed (or removed) to keep confidentiality. Any resemblance of any type of name or date or
        place or anything else to real world is purely incidental.


text:
Q: Displaying SHOM WMS in Folium / Leaflet map I'm trying to display this WMS in Leaflet / Folium: http://services.data.shom.fr/INSPIRE/wms/r
I use the following code:
import folium

center=[49.9765229931438, 1.1902348134956244]

def inline_map(m, width=800, height=500):
    """Takes a folium instance and embed HTML."""
    m._build_map()
    srcdoc = m.HTML.replace('"', '"')
    embed = HTML('<iframe srcdoc="{}" '
                 'style="width: {}px; height: {}px; '
                 'border: none"></iframe>'.format(srcdoc, width, height))
    return embed

width, height = 1400, 800

#tileset = r'http://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}'

tileset = r'http://services.data.shom.fr/INSPIRE/wms/r/{z}/{y}/{x}'

map = folium.Map(location=center, zoom_start=10,
                    #tiles='Stamen Terrain',
                    tiles = tileset,
                    #tiles='OpenStreetMap',
                    width=width,
                    height=height,
                    attr="MyDataAttribution")

map.save("mapTEST.html")

When I open mapTEST.html with my brother it does create a leaflet map object, but no tile is displayed, when I use another WMS, it works perfectly. Did I do something wrong with the URL?

A: From the information I can find at the portal home page the data is provided as a WMS and WMTS layer. Looking at the GetCapabilities shows that it only supports KVP requests while you seem to be trying to access the data as an XYZ layer.
So a request like http://services.data.shom.fr/clevisu/wmts?layer=SCAN-LITTO_PYR-PNG_WLD_3857_WMTS&style=normal&tilematrixset=3857&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix=14&TileCol=8002&TileRow=5688 will give you an image:

Alternatively you can use a WMS request from the capabilities given.


text:
Q: ASP.NET MVC Model State ModelState.IsValid is returning false for me in my controller.  I know that means one or more model errors were found when model binding.  My question is how do I see the errors?
I noticed that my particular ModelState has 6 items in it.  If I try to do any of these...
ModelState[0].Errors[0].ToString()
ModelState[0].Errors[0].ErrorMessage
ModelState[0].Value.AttemptedValue

I get this error:
The best overloaded method match for 'System.Web.Mvc.ModelStateDictionary.this[string]' has some invalid arguments

A: The indexor into the ModelState is a string (usually the property name of the offending model or name of the html element).
If you check the MSDN docs for the ModelState class, you'll see that it has an Errors collection that will allow you to iterate over the error items (which are ModelError instances) to see what caused them.

A: in controller;
ModelState.AddModelError("username", "Bad username");

in view;
 <%= Html.ValidationMessage("username") %>

also
<%= Html.ValidationSummary() %>

Html.ValidationSummary() might be what you are looking for.


text:
Q: Java - RSA публичный и приватный ключ в виде String Требуется шифровать пароли на клиентской стороне (Java апплет). Пароль нужно зашифровать приватным ключом, а публичный нужно отправить в базу данных, что бы потом достать его и расшифровать.
Пара ключей генерируется следующим образом:
  KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
           keyPairGenerator.initialize(2048);
           KeyPair keyPair = keyPairGenerator.generateKeyPair();
           PublicKey publicKey = keyPair.getPublic();
           PrivateKey privateKey = keyPair.getPrivate();

И с такими ключами шифрование и обратное действие происходят без проблем, но чтобы хранить ключ в БД, методом toString() он преобразуется в строку. А как эту же строку сделать типом PublicKey?

A: Оригинал ответа. Допускаю, что blob твоего ключа хранится в base64.
byte[] publicBytes = Base64.decodeBase64(publicK);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);


text:
Q: run a cmd in shell script for once a shell script runs 12 times in a day (in every 2 hrs). the script transfer data from location (/var/log/2015_07_29) to external storage (/data).
the script has a make directory command for date such as
a=date +"%F"
b=echo $a | cut -d'-' -f1
c=echo $a | cut -d'-' -f2
d=echo $a | cut -d'-' -f3
mkdir $d_$c_$b
But it has to be run only once because once it is created at first place, we don't need to run this command remaining 11 times.
Can you restrict this command to be run once in a day ?

A: Assuming you just want to prevent the mkdir part being run if the directory is already there, just check that first.
[ -d $d_$c_$b ] || mkdir $d_$c_$b

The left side of the || is testing whether the directory exists.  If it does exist, the expression evaluates to true, so the right side is never evaluated. Otherwise, the right-side gets run, creating the directory.


text:
Q: JSON Parse Json and Jquery ParseJson is not working in visualforce I am trying to parse a json string in salesforce visual force, it working good in standard HTML jquery test page but not working in my visual force page. I checked and the json string is valid. Can someone help?
MyController.MyCompany( j$('#input').val(),function(result,event){

              alert(result);// this alert shows the JSON string from controller
              var parsedRes=jQuery.parseJSON(result);
              var parsedRes2=JSON.parse(result);
              alert(parsedRes); //this is not alerting
              alert(parsedRes2); this is not alerting

I tried the same thing in other JSON validating websites and everything works good expect in visual force.
The JSON is:
{"CompanyResponse":{"@ServiceVersionNumber":"2.0","TransactionDetail":{"ApplicationTransactionID":"Id-fc6a4756f6b52b00f2ae0e009fcc2af3-1","ServiceTransactionID":"Id-fc6a4756f6b52b00f2ae0e009fcc2af3-1","TransactionTimestamp":"2015-11-14T17:10:20"},"TransactionResult":{"SeverityText":"Information","ResultID":"CM000","ResultText":"Success"},"FindCompanyResponseDetail":{"CandidateMatchedQuantity":1,"CandidateReturnedQuantity":1,"FindCandidate":[{"DUNSNumber":"884745530","OrganizationPrimaryName":{"OrganizationName":{"$":"AMAZON.COM, INC."}},"TradeStyleName":[{"OrganizationName":{"$":"Amazon.Com"}}],"MarketabilityIndicator":true,"PrimaryAddress":{"StreetAddressLine":[{"LineText":"410 Terry Ave N"}],"PrimaryTownName":"Seattle","CountryISOAlpha2Code":"US","PostalCode":"98109","PostalCodeExtensionCode":"5210","TerritoryOfficialName":"Washington","TerritoryAbbreviatedName":"WA","MetropolitanStatisticalAreaUSCensusCode":["42660"]},"TelephoneNumber":{"TelecommunicationNumber":"2062661000"},"FacsimileNumber":{"TelecommunicationNumber":"2062664952"},"FamilyTreeMemberRole":[{"FamilyTreeMemberRoleText":{"@CodeValue":12771,"$":"Headquarters"}}],"StandaloneOrganizationIndicator":false,"IndustryCode":[{"@TypeText":"D&B Standard Industry Code","@CodeValue":3599,"IndustryCode":{"$":"59610000"},"IndustryCodeDescription":[{"@IndustryCodeDescriptionLengthCode":2121,"$":"CATALOG,MAIL HOUSES"}]}],"ConsolidatedEmployeeDetails":{"TotalEmployeeQuantity":154100},"PubliclyTradedCompanyIndicator":true,"UpwardFamilyMemberPubliclyTradedCompanyIndicator":true,"StockExchangeDetails":[{"StockExchangeTickerName":"AMZN"},{"StockExchangeTickerName":"AMZ"},{"StockExchangeName":{"@CodeValue":23343,"$":"Dusseldorf Stock Exchange"},"StockExchangeTickerName":"AMZ"},{"StockExchangeName":{"@CodeValue":23344,"$":"Frankfurt Stock Exchange"},"StockExchangeTickerName":"AMZ"},{"StockExchangeName":{"@CodeValue":23345,"$":"Hamburg Stock Exchange"},"StockExchangeTickerName":"AMZ"},{"StockExchangeName":{"@CodeValue":23357,"$":"BMV"},"StockExchangeTickerName":"AMZN"},{"StockExchangeName":{"@CodeValue":23360,"$":"Borse Munchen"},"StockExchangeTickerName":"AMZ"},{"StockExchangeName":{"@CodeValue":23367,"$":"SSE"},"StockExchangeTickerName":"AMZN"},{"StockExchangeName":{"@CodeValue":23378,"$":"SIX Swiss Exchange"},"StockExchangeTickerName":"US1760"},{"StockExchangeName":{"@CodeValue":23378,"$":"SIX Swiss Exchange"},"StockExchangeTickerName":"US1759"},{"StockExchangeName":{"@CodeValue":23378,"$":"SIX Swiss Exchange"},"StockExchangeTickerName":"US1758"},{"StockExchangeName":{"@CodeValue":23398,"$":"BVL"},"StockExchangeTickerName":"AMZN"},{"StockExchangeTickerName":"AMA-U"},{"StockExchangeTickerName":"AMZNn"},{"StockExchangeTickerName":"AMZN"},{"StockExchangeTickerName":"AMZN"},{"StockExchangeTickerName":"AMZN"},{"StockExchangeTickerName":"AMZN"},{"StockExchangeTickerName":"AMZO34"},{"StockExchangeTickerName":"AMZF"},{"StockExchangeTickerName":"AMZN"},{"StockExchangeName":{"@CodeValue":23338,"$":"BVC (Colombia)"},"StockExchangeTickerName":"AMZN"}],"SalesRevenueAmount":{"@CurrencyISOAlpha3Code":"USD","@UnitOfSize":"Million","$":88988},"DisplaySequence":1}]}}}

A: Data is already in json format. You dont need parse it again


text:
Q: How can I use java.lang.instrument in an Eclipse RCP application? In order to use the instrumentation features introduced in JDK 5, you can use the -javaagent flag passed to the JVM. This will inject an instance of an Instrumentation class into the static premain method. For example in a class like this:
public class MyClass {
    public static Instrumentation inst;
    public static void premain(String options, Instrumentation inst) {
        MyClass.inst = inst;
    }
}

With an appropriate manifest file, you can run this as follows:
 java -javaagent:myfiles.jar SomeClass

This calls the premain method then main from SomeClass. This approach is used in the Java.SizeOf Project to guess at the approximate size of a Java object.
OK, now in Eclipse RCP each bundle has its own classloader. This means that the static Instrumentation that we stored in our MyClass is not visible to an Eclipse application. The javaagent uses one class-loader, the Eclipse bundles get loaded with another. When we access MyClass.inst from within a plugin it is null, as that class is not the same class as the one the javaagent loaded and called premain on.
Other clues as to a possible solution are this thread on the rcp mailing list. But nothing conclusive.
Is there any way to work around this? The Eclipse-BuddyPolicy hinted at in the eclipsezone article sounds good. I tried:
Eclipse-BuddyPolicy: app

in my plugins without luck. I need something like Eclipse-BuddyPolicy: javaagent. Any ideas?

A: I think the simplest solution is to use the global properties object. Have pre-main store the instrumentation object as a global properties and then access it from everywhere (the properties object is the same in all class loaders):
[Edit: updated]
public class MyClass {
    private static final String KEY = "my.instrumentation";
    public static void premain(String options, Instrumentation inst) {
        Properties props = System.getProperties();
        if(props.get(KEY) == null)
           props.put(KEY, inst);
    }

    public static Instrumentation getInstrumentation() {
       return System.getProperties().get(KEY);
    }
}


text:
Q: VMware Kernel-Headers I Installed VMware-Player-16.1.2-17966106.x86_64.bundle . When I ran it in the GUI it shows
I use Arch Linux and I installed all required packages as per Arch wiki . Many answers for this kind of questions are Distribution Oriented (I tried didn't work). So please anyone with same problem resolved, post an answer.
Output of
pacman -Q linux
linux 5.12.8.arch1-1

Output of
pacman -S linux-headers

warning: linux-headers-5.12.9.arch1-1 is up to date -- reinstalling
resolving dependencies...
looking for conflicting packages...

Packages (1) linux-headers-5.12.9.arch1-1

Total Installed Size:  129.25 MiB
Net Upgrade Size:        0.00 MiB

Even I tried replacing original tarballs of VMware (vmmon.tar and vmnet.tar in /usr/lib/vmware/modules/source/ ) with patched verson of https://github.com/mkubecek/vmware-host-modules/  github repository , As per Installation guide
When using a downloaded tarball, simply run

  tar -cf vmmon.tar vmmon-only
  tar -cf vmnet.tar vmnet-only

to create the tarballs. In this case, there is no protection against
unwanted local changes.

Whatever way you used to create the tarballs, replace the original ones
provided by VMware

  /usr/lib/vmware/modules/source/vmmon.tar
  /usr/lib/vmware/modules/source/vmnet.tar

by patched versions. It is highly recommended to backup the original
tarballs before replacing them.

Once patched tarballs are installed, you can rebuild the modules as usual:

  vmware-modconfig --console --install-all

When I run  vmware-modconfig --console --install-all
[AppLoader] GLib does not have GSettings support.

(process:1887): GLib-CRITICAL **: 08:21:25.344: g_file_test: assertion 'filename != NULL' failed
Failed to setup build environment.

A: Make sure output of pacman -Q linux linux-headers match , If not perform a system upgrade using pacman -Syu so that kernel and kernel headers match. Refer to this https://wiki.archlinux.org/title/System_maintenance . After that  reboot the system. It will solve the issue.


text:
Q: Get count from SQLITE PCL for a specific month I am using Xamarin.Forms and C#. I am trying to get the count of Products for each month in a year.
string[] months = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

var montlyCount = new Dictionary<string, int>();
foreach (var month in months)
{
      var count = App.Database.GetCount(month);
      montlyCount.Add(month, count);
}

Database.cs:
public int GetCount(string month)
{
    return database.ExecuteScalar<int>("SELECT COUNT(*) FROM Products WHERE MONTH(ProductEntryDate) = ?;", month);
}

However, there is no such function "MONTH" with SQLite PCL. How can I get the count where month = "January", for example?

A: As you already found out there is no function like MONTH() in SQLite.
The function that you can use to extract the month from a properly formatted date (YYYY-MM-DD) is strftime() which will return a left 0 padded string which is the number of the month:
SELECT COUNT(*)
FROM Products
WHERE strftime('%m', ProductEntryDate) = ?

So you must pass as argument a string like '01', '02', ...., '12' and not the month's name.
Or you can pass an integer 1, 2, ..., 12 if you implicitly convert the return value of strftime() to an integer by adding 0:
WHERE strftime('%m', ProductEntryDate) + 0 = ?


text:
Q: How to check if a user exists on a list of multiple servers? I have around 100 servers on which I want to check if a user exists.
Instead of going manually on each and every server, I am trying to write a script to do that. So, far I have written the following script to verify it.
#!/bin/bash
if id user1 >/dev/null 2>&1; then
        echo "user1 user exists"
else
        echo "user1 user does not exist"
fi

I believe I need to do ssh also into the servers using the script but please suggest if there is a better way to perform it.

A: "you have" implies you're an administrator, so can use the root account with a public key... just ensure you keep the private key secure and enable ssh access without a password.
Otherwise, safer to have your own account on all machines and ssh into each one and run that id command @that-other-guy mentioned.
It doesn't matter that a password is required, if you have your ssh public key in your authorized_keys file on every host.  Then on your machine, your ssh-agent maintains the private key, so that you only have to enter your passphrase once, and off you go.


text:
Q: A property of ratio of two polynomials I am given a function $f:\mathbb{R}\rightarrow \mathbb{R}$ such that $f(x)= \frac{p(x)}{q(x)}$ for all x, and $p(x),q(x)$ are two polynomials with integer coefficients. I have two questions related to it.

*

*Suppose $f$ takes integer values on all integers. Then is $f$ itself a polynomial in rational coefficients?

*If above answer is yes, then next question assumes that $p(x),q(x)$ have degree at most $d$. The function $f(x)= \frac{p(x)}{q(x)}$ must take integer values on how many integers, to ensure that it itself is a polynomial in rational coefficients?


text:
Q: Why does calling the security authentication property `principal.displayName` in a decorator throw an exception? Is there a reason why calling the security authentication property principal.displayName in a decorator would cause a problem?
I'm setting it as a variable in a sitemesh decorator:
                <c:set var="displayName">
                    <sec:authentication property="principal.displayName" />
                </c:set>

But it generates this exception:
java.lang.RuntimeException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Invalid property 'principal.displayName' o
f bean class [org.springframework.security.authentication.AnonymousAuthenticationToken]: Bean property 'principal.displayName' is not
readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
        at com.opensymphony.sitemesh.webapp.decorator.BaseWebAppDecorator.render(BaseWebAppDecorator.java:39)
        at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:84)
        at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
        at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
        at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
        at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
        at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
        at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
        at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:70)
        at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:327)
        at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:126)
        at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:195)
        at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:159)
        at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:141)
        at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:90)
        at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:417)
        at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)

A: Your request's Authentication object at that point is an instance of the AnonymousAuthenticationToken class, and that class does not have a property called displayName.
Clearly, SpringSecurity believes that the user is not logged.  You probably need to

*

*change the access rules so that that JSP can only be viewed when the user is logged in, or

*change the JSP so to something like the following (assuming that you are using Spring 3.0.x and you've enabled web security expressions).

<c:set var="displayName">
    <sec:authorize access="isAuthenticated()">
        <sec:authentication property="principal.displayName" />
    </sec:authorize>
</c:set>

References:

*

*Expression-based Access Control

*JSP Tag Libraries

A: Followed by the Answer of Stephen C and the References given by him
I successfully wrote my code As
<sec:authorize access="hasAnyRole('ROLE_DEFINED_1','ROLE_DEFINED_2')">
    <sec:authentication property="principal.displayName" />
</sec:authorize>

Where, ROLE_DEFINED_1 and ROLE_DEFINED_2 are Roles defined in your application.


text:
Q: How to - Looping midi playback using MusicSequence and MusicPlayer I've finally managed to load and playback midifiles using the MusicSequence and MusicPlayer API as well as AUSampler for delivering the sound samples.
Is there any (simple) way of looping the actual midi sequence in the MusicPlayer or do I have to make my own timing calculations and restart the player from the beginning "manually"? I'm afraid of losing exact miditiming if the latter is true, especially because I'm using very short 1-bar loops, so I had to restart the playback very often.
Thanks for any hint!


text:
Q: why does a parameter passed into a stored procedure cause MySQL error 1267? Both of these stored procedures compile in my MySQL 5.1.73 server:
delimiter $$
CREATE PROCEDURE get_admins()
    BEGIN
            SELECT *
            FROM Accounts
                INNER JOIN LINK_Account_Status ON Accounts.account_id=LINK_Account_Status.account_id
                    AND LINK_Account_Status.active_ind=1
            WHERE Accounts.active_ind=1
                AND Accounts.`type`='admin';
    END $$
delimiter ;

delimiter $$
CREATE PROCEDURE get_admins2(
    IN  p_type  varchar(50)
)
    BEGIN
            SELECT *
            FROM Accounts
                INNER JOIN LINK_Account_Status ON Accounts.account_id=LINK_Account_Status.account_id
                    AND LINK_Account_Status.active_ind=1
            WHERE Accounts.active_ind=1
                AND Accounts.`type`=p_type;
    END $$
delimiter ;

Executing CALL get_admins(); returns the results I expect.
Executing CALL get_admins2('admin'); errors:

Error Code: 1267. Illegal mix of collations (utf8_general_ci,IMPLICIT)
  and (utf8_unicode_ci,IMPLICIT) for operation '='

The observant responder will notice there is no functional difference between the two resulting queries. I have double-checked that Accounts.type is, indeed, a varchar(50) (even if it is unfortunately-named).
What in the Sam Hill is going on here?

A: You need to use COLLATE in your WHERE condition to solve this like below
delimiter $$
CREATE PROCEDURE get_admins2(
    IN  p_type  varchar(50)
)
    BEGIN
            SELECT *
            FROM Accounts
                INNER JOIN LINK_Account_Status ON
Accounts.account_id=LINK_Account_Status.account_id
                    AND LINK_Account_Status.active_ind=1
            WHERE Accounts.active_ind=1
                AND Accounts.`type`=p_type COLLATE utf8_general_ci; /* <-- Here */
    END $$
delimiter ;

You can as well add the COLLATION in parameter declaration itself ("As of [MySQL] 5.5.3, COLLATE can be used...") like:
delimiter $$
CREATE PROCEDURE get_admins2(
    IN  p_type  varchar(50) COLLATE utf8_general_ci <-- Here

.....<rest of the code here>.....

EDIT:
After doing some search I found that, this issue may occur if your columns have different collation even though tables have same collation. See the below MySQL Forum post
http://forums.mysql.com/read.php?103,265345,265579


text:
Q: Adding/push to firebase ref with limitToLast? Firebase states 256 MB for maximum read, so....
Is it possible to push a ref with limitToLast?
var ref = firebase.database().ref();

ref.child("projects").limitToLast(1).push({
    username: name,
    email: email,
    profile_picture : imageUrl
  });

Thanks

A: When reading from the database, your query should be limited, filtered or otherwise restricted so that it doesn't hit the 256MB limit, or retrieve excessive amounts of data. When writing to the database, you only need to ensure that the size of a single write request does not exceed 256MB.
Using firebase.database().ref().child() generates a Reference to a specific location in the database, but doesn't perform any database or network operations. This can then be used to read/write data to/from the database.
Calling limitToLast() (or any other filtering methods) on a Reference will produce a Query instead. Similarly, a Query does not perform any database or network operations by itself. However, a Query can only be instructed to perform write operations.
Network operations are only performed when calling specific methods on a Reference or Query:

*

*Read operations are performed when calling on(), once() or variations of these on a Reference or Query.

*Write operations are performed when calling set(), push(), remove(), update() or variations of these on a Reference only.

In summary, writing to the database using push() won't read data first, so you don't need to worry about hitting the 256MB read limit. Finally, because limitToLast() returns a Query, you won't then be able to call push() on this.


text:
Q: Trying to convert UNIX Epoch time into Normal date from JSON I am trying to convert unix epoch time into normal date from JSON.
JSON code (not full):
{"success":true,"lastUpdated":1621365664405

I have this code:
import requests
import json
from datetime import datetime

r = requests.get('https://api.hypixel.net/skyblock/bazaar').json()

#last updated datetime
time = r['lastUpdated']
datetime_time = datetime.fromtimestamp(time).strftime('%Y-%m-%d')

print(datetime_time)

But I get the following error: Line 9, in
datetime_time = datetime.fromtimestamp(time).strftime('%Y-%m-%d'). OSError: [Errno 22] Invalid argument

A: The timestamp returned is in miliseconds, while what you need is a timestamp in seconds. Just divide "time" by 1000 and it should do the trick, I think.
Hope it helped!
EDIT:
Also, you don't need to use strftime. The following should also work:
# Import the whole datetime module
import datetime as dt

time = r['lastUpdated'] / 1000
# Use the date module, instead of the datetime module
datetime_time = str(dt.date.fromtimestamp(time))

This will give back your string in the format you desire. Use whichever you prefer.
The code as you want it can be:
time = r['lastUpdated'] / 1000

Just with that line changed, it should work.
Hope it helped!


text:
Q: Copying jar file from my local hadoop node to a remote hadoop node I am a new to Hadoop. I have installed Hadoop on Mac OSX and I am able to run my Map Reduce java program on dataset present on my local system. Now I want to run this java program on a larger dataset which is stored on a remote Hadoop cluster. How do I copy my jar file onto this cluster in order to run it. I tried the put and copyFromLocal commands but am having no luck.

A: How do I copy my jar file onto this cluster in order to run it.>
For this you can use WINSCP and Copy your jar or Hadoop program file to the remote cluster.
Once you have it on your remote cluster you can use the following command to compile the program.
$ mkdir hadoop_classes
$ javac -cp /usr/lib/hadoop/:/usr/lib/hadoop/client-0.20/ -d hadoop_classess [path to + YourHadoopProgram.java]
$ jar -cvf yourhadoopprogram.jar -C hadoop_classess/ .
$ hadoop jar yourhadoopprogram.jar org.myorg.YourHadoopProgram [input path] [output path]
Check the following link for more understanding
http://www.cloudera.com/content/cloudera/en/documentation/HadoopTutorial/CDH4/Hadoop-Tutorial/ht_usage.html

A: Put your jar file in the edge node of the cluster.Edge node - is the node onto which you log into the cluster.
You need not put your jar file in the HDFS to run the program.
Just run :
  Hadoop jar <jar-name> <arguments> <input_file> <output_path>

In case you pass input and output details then they should be your HDFS paths
Hope this helps !!


text:
Q: QGIS Newsfeed missing on welcome screen I run QGIS 3.18.1 on Ubuntu 20.04, I miss the newsfeed on the welcome page:

Newsfeed is activated in the settings:

I was able to solve the missing Recent Projects according to the answer on this issue: QGIS 3.10 Recent Projects List missing but I was not able to access the newsfeed the same way. Any hints?

A: You can modify the QGIS options settings as :

*

*Go to the QGIS menu Settings > options > Advanced tab

*Promise to be careful

*In the settings tree, go to core > NewsFeed > httpsfeedqgisorg > lastFetchTime

*Edit the value and set it at 0

*Restart QGIS.

PyQGIS Bonus
from qgis.core import QgsSettings

qgis_settings = QgsSettings()
qgis_settings.beginGroup("/core/NewsFeed/httpsfeedqgisorg")
qgis_settings.setValue("lastFetchTime", 0)


text:
Q: Regarding lz4mt compression and linux buffering issue I am using lz4mt multi-threaded version of lz4 and in my workflow I am sending thousands of large size files (620 MB) from client to server and when file reaches on server my rule will trigger and compress file using lz4mt and then remove uncompressed file. The problem is sometimes when I remove uncompressed file, I am not able to get compressed file of right size its because lz4mt returns immediately before sending output to disk.
So is there any way lz4mt will remove uncompressed file itself after compressing as done by bzip2.
Input: bzip2 uncompress_file
Output: Compressed file only

whereas
Input: lz4mt uncompress_file
Output: (Uncompressed + Compressed) file

Below script sync command also not working properly I think.
The script which execute as my rule triggers is:

script.sh
/bin/lz4mt  uncompressed_file output_file
/bin/sync
/bin/rm uncompressed_file

Please tell me how to solve above issue.
Thanks a lot

A: Author here. You could try the following methods

*

*Concatenate commands with && or ;.

*Add lz4mt command line option -q (suppress prompt), and -f (force overwrite).

*Try it with original lz4.


text:
Q: Windows 8 Consumer Preview - Full Core CPU Utilization by system process I have a Lenovo X220 laptop on which I've installed Windows 8 Consumer Preview. Sometimes though it'll get stuck using 100% of a CPU core though in the SYSTEM process, and there's nothing I can do to view the stack here to narrow it down to a specific component, because the system process is "protected".
The strange thing here is that the issue seems to be intermittent. 99% of the time everything works fine, but sometimes it'll just start doing this. Rebooting fixes the issue.
Process Explorer (after getting debug symbols turned on) says the following:

What steps might I take to troubleshoot this?


text:
Q: How can I get a unique value from a fortran pointer I have a fortran pointer, referring to some allocated memory. I want to "hash" it so that I get a unique number referring to that memory. In C, I would convert the pointer location to an integer.

A: In Fortran 95 I don't believe this is possible in a strictly standard conforming way.  You would need to use vendor extensions - the necessary capability is often available via an intrinsic called LOC or similar.
In Fortran 2003, depending on the nature of the object being pointed to by the Fortran pointer, you could convert the C address of the object (its memory location) to an integer.
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_LOC, C_INTPTR_T
TYPE(thing), POINTER :: object
INTEGER(C_INTPTR_T) :: an_integer
!****
ALLOCATE(object)
an_integer = TRANSFER(C_LOC(object), an_integer)


text:
Q: Scala activerecord with implicit json format I have a scala-activerecord:
case class Person(name: String) extends ActiveRecord with Timestamps
object Person extends ActiveRecordCompanion[Person]

Everything works ok.
Suddenly, I want to provide an API and repond with json representation of the entity, so I modified the code:
case class Person(name: String) extends ActiveRecord with Timestamps
object Person extends ActiveRecordCompanion[Person] with DefaultJsonProtocol {
  implicit val jsonFormat = jsonFormat1(Request)
}

Now it causes an exception:
com.github.aselab.activerecord.SchemaSettingException: Cannot find table definition of class Person
  at com.github.aselab.activerecord.ActiveRecordException$.tableNotFound(ActiveRecordException.scala:48)
  at com.github.aselab.activerecord.Config$$anonfun$schema$1.apply(ActiveRecordConfig.scala:29)
  at com.github.aselab.activerecord.Config$$anonfun$schema$1.apply(ActiveRecordConfig.scala:29)
  at scala.collection.MapLike$class.getOrElse(MapLike.scala:128)
  at scala.collection.AbstractMap.getOrElse(Map.scala:59)
  at com.github.aselab.activerecord.Config$.schema(ActiveRecordConfig.scala:29)
  at com.github.aselab.activerecord.ActiveRecordBaseCompanion$class.schema(ActiveRecord.scala:116)
  at Person$.schema$lzycompute(Request.scala:12)
  at Person$.schema(Request.scala:12)
  at com.github.aselab.activerecord.ActiveRecordBaseCompanion$class.table(ActiveRecord.scala:123)
  at Person$.table$lzycompute(Request.scala:12)
  at Person$.table(Request.scala:12)
  at com.github.aselab.activerecord.ActiveRecordBaseCompanion$class.all(ActiveRecord.scala:133)
  at Person$.all(Request.scala:12)
  at com.github.aselab.activerecord.inner.CompanionIterable$class.companionToIterable(Implicits.scala:15)
  at Person$.companionToIterable(Request.scala:12)
  at Person$.<init>(Request.scala:13)
  at Person$.<clinit>(Request.scala)
  ... 34 more

EDIT:
I put two breakpoints in ActiveRecordConfig.scala:
Breakpoint A here:
def schema(companion: ActiveRecordBaseCompanion[_, _]): ActiveRecordTables = {
  val clazz = companion.classInfo.clazz
  tables.getOrElse(clazz, throw ActiveRecordException.tableNotFound(clazz.toString))
}

Breakpoint B here:
def registerSchema(s: ActiveRecordTables) = {
  conf = s.config
  s.all.foreach(t => _tables.update(t.posoMetaData.clasz, s))
}

With the first code (without json implicit) the execution hits the breakpoint B.
With the second code (including json implicit) the execution hits the breakpoint A first, causing the exception.

A: Json support work in the version 0.3.1 of scala-activerecord, see wiki and this issue. As for now, with the latest version 0.3.0 you can use the first code and the form values deserialization:
case class Person(name: String) extends ActiveRecord with Timestamps
object Person extends ActiveRecordCompanion[Person]

And in your e.g. spray controller:
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

requestContext.complete(Person.find(id).toFormValues)

The method toFormValues will return Map[String, String], which can be by spray-json implicitly converted to json.


text:
Q: Event constants for Javascript? In Javascript I have code like:
document.addEventListener("mousedown", mouseDownHandler);

and occasionally I might fat finger something like:
document.addEventListener("mouzedown", mouseDownHandler);

And Javascript won't recognize that I'm a moron and I'll be confused why my handler isn't working.
Actionscript3 specifies event constants like so:
MouseEvent.MOUSE_DOWN // equiv to the String "mouseDown"

If I fat-finger a variable or constant then JS gets mad at me and I can solve the problem real quick. Does JavaScript have anything similar to to this or do I need to make my own JS pseudo-constants for event types?

A: There is no built-in feature to do this for you.
You could create your own list of events:
var EventNames = {
  MOUSE_DOWN : "mousedown",
  MOUSE_UP   : "mouseup",
  CLICK      : "click",
  // etc
};

But that doesn't protect you from typos because then EventNames.MOUZE_DOWN will just give you undefined (which will likely be accepted by addEventListener() but - obviously - not do what you want).
You could create a series of individual global variables and then the browser should give an error if you make a typo on the "constant" name (and your IDE or lint product may detect typos for you):
var Event_MOUSE_DOWN = "mousedown",
    Event_MOUSE_UP   = "mouseup",
    // etc

But of course members of the "globals are evil" brigade are already starting to froth at the mouth just from having read the above. You could do the above without globals by wrapping all of your code (including those "constants") in one big immediately-executed anonymous function, or you could instead do something like this:
// YNH: "Your Namespace Here" (insert your own namespacing
//                             code as desired)
var YNH_Events = {
   validEvents : ["mouseup","mousedown","click","etc"],

   bindEvent = function(element, eventType, handler, isCustomEvent) {
      if (!isCustomEvent && -1 === this.validEvents.indexOf(eventType))
         throw "Invalid event type requested: " + eventType;

      if (element.addEventListener)
         element.addEventListener(eventType, handler, false);
      else if (element.attachEvent)
         element.attachEvent("on" + eventType, handler);
      else
         element["on" + eventType] = handler;
   }
}

YNH_Events.bindEvent(someElement, "mousedown", function() { });         // OK
YNH_Events.bindEvent(someElement, "customevent", function() { }, true); // OK
YNH_Events.bindEvent(someElement, "mouzedown", function() { });     // Error!

Of course, the usual caveat about using Array.indexOf() applies, i.e., not supported in older browsers but you can shim it as described by MDN, blah, blah, blah.
Or you could do like jQuery and define your own .mousedown(), .click() etc methods and only attach events through those methods - you'll definitely get an error if you mistype the method name.

A: There are no predefined constants/properties which can be used as to define an event for addEventListener.
Stripped original answer below (and in the revision history):
The Event object defined the following constants. Using Firefox 8.0, and the following code:

*

*alert(Object.keys(Event).map(function(name){return name + "\t" + Event[name]}).join('\n'))

A: Maybe use jQuery? Big switch for a small problem, but jQuery has aliased functions for a lot of JS handlers, and if you spell a function name wrong you'll definitely get an error.
That is,
document.addEventListener("mousedown", mouseDownHandler); // right
$(document).mousedown(mouseDownHandler); // right

document.addEventListener("mouzedown", mouseDownHandler); // wrong, no error
$(document).mouzedown(mouseDownHandler); // wrong, throws error


text:
Q: Layering divs ordering I am having some difficulty with layering my divs. I have created a sample of the problematic area.
My Fiddle
By looking at it you can see a background image - on top of that are two blue boxes and slightly transparent black box. I require the box to be behind the two boxes but on top of the background image.
Now I did try assigning a z-index to all elements but it didn't change a thing?

                "headline here"

                sub head

.hero{
    position:relative;
    height:60%;
    background-image:url(http://asia.olympus-imaging.com/products/dslr/e520/sample/images/sample_03.jpg);
    background-size:cover;
    float: left;
    width: 100%;
}

.headerband{
    background-color: rgba(0,0,0,0.7);
    height: 20%;
    margin-top: -30px;
    float:left;
    z-index: -1;
    width: 100%;
}

/* Main Container */
.container{
    margin: 0 auto;
    width: 960px;
    padding: 20px 0 0 0;
}

/* Respinsive grid */

.section {
    clear: both;
    padding: 0px;
    margin: 0px;
}

/*  COLUMN SETUP  */
.col {
    display: block;
    float:left;
    margin: 1% 0 1% 1.6%;
}
.col:first-child { margin-left: 0; }

/*  GROUPING  */
.group:before,
.group:after {
    content:"";
    display:table;
}
.group:after {
    clear:both;
}
.group {
    zoom:1; /* For IE 6/7 */
}

/*  Grid of four  */
.span_4_of_4 {
    width: 100%;
}
.span_3_of_4 {
    width: 74.6%;
    background-color: blue;
}
.span_2_of_4 {
    width: 49.2%;
    background-color: #008394;
    color: #FFF;
    padding: 30px 20px 30px 20px;
    font-size: 30px;
    text-align:center;
    margin-bottom: -10px;
    margin-top: 370px;
}
.span_1_of_4 {
    width: 28.8%;
    background-color: #00C1DB;
    color: #FFF;
    padding: 20px 20px 20px 20px;
    font-size: 15px;
    text-align:center;
}

A: I accomplished what you needed by doing this
.headerband{
    background-color: rgba(0,0,0,0.7);
    height: 20%;
    margin-top: -30px;
    float:left;

    /* Drop this line => z-index: 0;  */

    width: 100%;
}

.container{
    margin: 0 auto;
    width: 960px;
    padding: 20px 0 0 0;

    /* You can use a z-index of 1 or higher. I opted for 10 */
    position: relative;
    z-index: 10;
}

See updated fiddle
UPDATE:
The z-index property won't work unless you set the position property of the element. By default the CSS position property is static (Read more about the position property]. Valid values are absolute, relative or fixed, which allows you to position elements by supplying it with a top, left, bottom, or right. Normally you set either the top or bottom properties along with a horizontal location (i.e. left or right). Relative positioning is always relative to its parent element, normally you want to use it within a parent element that has been absolutely positioned. Fixed positioning will ensure that the positioned element will always stay visible, regardless of whether the user scrolls away or not. This one is useful, in my experience, for sticky navigation menus.
Since you weren't using absolute positioning for the .container, I opted to make it relative, then give it a z-index that was higher than the headerband.
As for why I set the .headerband to a non-negative value, this is a design decision on my part. I always work with z-indexes of 0 or higher. You will see in the above link that a negative z-index is valid. To me it's more natural to work with non-negatives. I noticed that .headerband isn't using absolutely positioned. I thought it was. Ignore this paragraph.

A: The z-index property will not work unless you use the position property as well on the element. For example:
position: fixed;
position: absolute;
position: relative;

If you're not familiar with what these do, you can read more about it here. And this blog post details how z-index and positioning work together.


text:
Q: Foundation 4 + Orbit Slider: Can't control animation speed I am using Foundation to create a website that involves the Orbit Slider. Try as I may, I can't change the speed of the slider. Everything is working properly (jquery, slider controls, slider bullets, customized CSS for slider, etc.), I just can't seem to change the parameters of the slideshow.
The head of my document:
<script src="js/vendor/custom.modernizr.js"></script>

<script>
 $(document).foundation('orbit', {
timer_speed: 100,
});
</script>

And at the end of my body:
  <script>
  document.write('<script src=js/vendor/' +
  ('__proto__' in {} ? 'zepto' : 'jquery') +
  '.js><\/script>')
  </script>

  <script src="js/foundation.min.js"></script>
  <script>
    $(document).foundation(
            );
  </script>

Like I said everything is functioning fine, I just can't change the parameter.
Thanks!

A: Try the below structure instead. Your issue is that you're referencing orbit before the foundation script is loaded, so that js in the head is essentially ignored.
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <!-- your content -->

    <script>
      document.write('<script src=js/vendor/' +
      ('__proto__' in {} ? 'zepto' : 'jquery') +
      '.js><\/script>')
  </script>

  <script src="js/foundation.min.js"></script>
  <script>
    $(document).foundation('orbit', {
        timer_speed: 100,
    });
  </script>
</body>
</html>


text:
Q: how do you use a for-loop over an object array and return a string listing information of the objects I have an array of objects and each of those objects has information for a specific person, how can I iterate over each object in that array and return their information in this toString()?
     @Override
 public String toString()
 {
     String tempString = " ";
      for(int i = 0; i < personArray.length; i++)
     {
         tempString = " All people currently residing on the stack: " +personArray[i];
     }

     return ""+tempString;
 }

I know do not need the array to do this, but I just wanted to know how to do it using a for-loop. I will continue to work on this, but I just want to know.

A: You are keep ovveriding the string inside for loop . You should attached one to another. Inshort concatenate your current result with previous results.
 for(int i = 0; i < personArray.length; i++)
     {
         tempString += " All people currently residing on the stack: " +personArray[i];
             --------^
     }

That way you can store the previous objects String notation and add the new result to it. In the end you can have a whole result in tempString.
The more readable and efficient way is to use a StringBuilder
   @Override
 public String toString()
 {
     StringBuilder builder = new StringBuilder();
      for(int i = 0; i < personArray.length; i++)
     {
         builder.append(" All people currently residing on the stack: " +personArray[i]);
     }

     return builder.toString();
 }

Note that you must have implemented the toString method of Person class already otherwise you end up seeing gibberish output in your result.


text:
Q: How to find the measure of the segment in the trapezoid's median being intersected by its diagonals? Given the trapezoid $ABCD$ with EF as median, what is the measure of segment $PQ$? $AB = 16$ cm, $DC = 24$ cm and PQ lies on the median $EF$ being cut by diagonals $AC$ and $BD$.
I have been looking for any theorems on trapezoid for me to be able to answer this problem. I am only able to find the measure of segment by mere illustration. Is there any theorems that can help me answer this question?

A: Say we have points $E-P-Q-F$ on median and $E$ is on $AD$.
Then since $EP$ is median in $ACD$ we have $EP = CD/2$,
and $QF$ is median in $BCD$, so we have $QF = CD/2$.
So $$PQ = EF - EP-QF = {AB+CD\over 2}-CD = {AB-CD\over 2} = 4$$


text:
Q: OpenCV: How to compute the mean of a Grayscale and save the output to a txt-file I am using the openCV library in python. I have read in a video and marked a Region of Interest in it. I have converted the frame from BGR to Grayscale and within the ROI I am taking a threshold on value 60. What I want to do now is: Compute the mean of the intensity values within the ROI. Do this for every frame of the video. And then write the result to a txt-file.
Here is my idea:
ROI_intensity = str(cv2.mean(thresh))
file = open("VelocityAnalysis.txt", "a+")
file.write(ROI_intensity)
file.close()

This, however, doesn't yield the intended result: str(cv2.mean(thresh)) returns a tuple with 4 (!) entries, while I was expecting just one. This is probably related to the three color channels and some last parameter, which I don't know, what it is there for. Possible fix
help = str(cv2.mean(thresh))
ROI_intensity = help[0]

This doesn't look nice to me, however. Is there a better solution?
The other problem with this code is that I want each result to be printed on its own row. And - this is probably the hardest part for me - I want to have a time next to the intensity value. The video has been taken with a framerate of 30 fps. So I should be able to have knowledge about the video time of each frame. I could simply create a count variable and assume that with every frame the count goes up by 1/30 seconds. But, again, is there a more sophisticated solution?

A: Regarding the first problem, you are right. The tuple of 4 represents the mean of 4 channels, R G B and alpha respectively, where alpha denotes transparency (Note that this depends on how you read the image. RGBA or BGRA). So writing help[0] is basically writing the mean value of first channel.
Regarding the second question, if you have the knowledge of the time video started getting recorded, you can get a timestamp like this,
timestamp_of_recorded_video = 0
fps = video.get(cv2.CAP_PROP_FPS)
frame_count = 0
while (True) :
     frame, ret = video.read()
     frame_count = frame_count + 1
     current_time_stamp = timestamp_of_recorded_video + (frame_count/fps) #Convert to datetime format as per your convenience
     file.write(str(current_time_stamp) + ',' + str(ROI_intensity) + '\n')

This is for OpenCV3. Use datetime library of Python add time stamps.


text:
Q: Bootstrap 3 Carousel only semi-responsive. Weird I am having issues with my carousel using bootstrap3.  The image itself is responsive, but I'm having a hard time figuring out how to make the caption, and button also responsive.  Haven't had much luck finding a clear answer. See
http://windstarwd.com/testman/
View the above page, then make your browser narrow and you will see the issues
for the "page header" (above the nav bar) i was able to get the phone number (h2) responsive by adding:
@media (max-width: 767px) {
  .my-header > div > h2 {
  font-size: smaller;
  }
}

But I am having trouble with the social media icons stacking and throwing off the site, and the carousel caption and buttons getting shoved off the top when in mobile.  It would be ideal to have the 32x32 social icons show normally, but the 16x16 when < 768px
So I guess I'm having two issues here :(

A: You could use the same media query for the top buttons, like
@media (max-width: 767px) {
  .socialIcons > img {
     width: 16px;
     height: 16px;
  }
}

or use a second second icon bar that will be shown if the screen size is too small, hiding the big icons bar, with the bootstrap attribute   .visible-sm and .hidden-sm (bootstrap doc).
For the carousel caption, you can once again use the media queries to set a different width when screen size < 768px, or define a width with percents instead of fixed size.
Hope I helped you.


text:
Q: Includes Touch Events clientX/Y scrolling or not? I'm trying to get touch coordinates relative to the viewport of browser from touch events (such as touchstart). I tried to get them from clientX/Y properties, but both actually return values including scrolling.
This is against spec, as it says clientX/Y should return coordinates without scrolling.

*

*I tried adding/removing meta viewport tag - without success.

*I tested it in iOS 4.3 on iPhone and Fennec nightly - both return values with scrolling.

What I'm doing wrong?
Thanks

A: You're not doing anything wrong. It's a bug in older versions of webkit that occur when the page is scrolled. I have seen this bug in iOS4 and a different bug in Android 4.0.
I've found a way to detect the bugs and calculate the correct values. Hope this can be useful for others:
function fixTouch (touch) {
    var winPageX = window.pageXOffset,
        winPageY = window.pageYOffset,
        x = touch.clientX,
        y = touch.clientY;

    if (touch.pageY === 0 && Math.floor(y) > Math.floor(touch.pageY) ||
        touch.pageX === 0 && Math.floor(x) > Math.floor(touch.pageX)) {
        // iOS4 clientX/clientY have the value that should have been
        // in pageX/pageY. While pageX/page/ have the value 0
        x = x - winPageX;
        y = y - winPageY;
    } else if (y < (touch.pageY - winPageY) || x < (touch.pageX - winPageX) ) {
        // Some Android browsers have totally bogus values for clientX/Y
        // when scrolling/zooming a page. Detectable since clientX/clientY
        // should never be smaller than pageX/pageY minus page scroll
        x = touch.pageX - winPageX;
        y = touch.pageY - winPageY;
    }

    return {
        clientX:    x,
        clientY:    y
    };
}

This function has to be called for each touch in the event.touches array.

A: Try this
event.touches[0].pageX

Note that it is always event.touches even if you define your event like this (using jquery here)
$("body").bind('touchmove', function(e){
//stops normal scrolling with touch
e.preventDefault();

console.log(event.touches[0].pageX)

})

;
The Safari guide provides more detail


text:
Q: Sharing variable between QWizard pages in Pyside/PyQt I am building a QWidget in PySide, and running into an issue when trying to share data between pages.
To summarize I utilize user inputs from earlier pages to construct a list of custom objects, which I need to share with the following page.
At the beginning of my code I construct a custom object, with an attribute called .name (among other attributes)
class MyCustomClass():

    def __init__(self, name, other_attributes)
        self.name = name

        ...set other attributes

In my QWizard I open a file and make a list of names to match with another list of MyCustomClass objects.  I then display the names alongside the matched name of the corresponding MyCustomClass object and prompt the user to confirm (or change), before moving to the next page.
Each match is stored as a tuple(name, MyCustomClass) and added to a list.  I then wish to read this list from the next page in order to perform more operations.  I'm trying to use .registerField, but I'm unsure of how to properly do so.  My attempt is below.
First I make a QWizardPage, perform some code and then construct my matches.  I made a function to return the value and used this for the .registerField
class ConfirmMatches(QWizardPage):

    def __init__(self):
        ...

    def initializePage(self):

        # Code to make display and operations and make list of matches
        ...
        self.matches = matches

        self.registerField("matches", self, "get_matches")

    def get_matches(self):
        return self.matches

Then from my next page, I try to call the field, but I only return a None object.
class NextPage(QWizardPage):

    def __init__(self):
        ...

    def initializePage(self):

        # Get relevant fields from past pages

        past_matches = self.field("matches")

type(past_matches) is None, even though when I print self.matches in the previous page it clearly displays them all.

*

*What am I doing wrong with the registerField?

*Is there an easier way to share this type of data between pages?

A: I actually solved it myself.  I was on the right track, just missing a few things, but I'll catalog here for anyone else with similar problems.
Like I said I have a list of matched objects, where each match is a list of a name, and the object that was found to correspond to that name, i.e. match = [name, MyCustomClass]
class ConfirmMatches(QWizardPage):

   # Function to change list
   def setList(self, new_list):

       self.list_val = new_list

       if self.list_val != []:
           self.list_changed.emit()

   # Function to return list
   def readList(self):

       return self.list_val

   def __init__(self):

       self.list_val = [] # Create initial value

       # Code to initialize displays/buttons, and generate matches
       ...

       # Here I assign the matches I made "matches", to the QProperty "match_list"
       self.setList(matches)

       # Then register field here.
       # Instead of the read function, I call the object itself (not sure why, but it works)
       self.registerField("registered_list", self, "match_list")

   # Define "match_list" as a QProperty with read and write functions, and a signal (not used)
   match_list = Property(list, readList, setList)
   listChanged = Signal()

I made the list a QProperty and wrote the Read and Write functions, as well as a Signal (not used). Then, when registering the field, instead of putting the Read function (readList), I put the QProperty itself (match_list).  Not sure why it works, but this conceivable could be used to register other custom objects.

A: If you want to explicitly set the value of the field matches in your ConfirmMatches page, you would need to do one of a few things:

*

*Make an explicit call to self.setField any time your matches change.

*Emit a signal every time your matches are changed after registering the property

*Store your matches in one of the standard Qt inputs, like QLineEdit, and use that widget in the registerField call.

If you check the docs for QWizardPage.registerField, what it does is register to grab the named property of the passed in widget when the widget's signal is emitted. The way your code is now, you would need to add a signal to your ConfirmMatches page that would be emitted whenever your matches variable changes. Otherwise, your page doesn't know when the field should be updated.


text:
Q: JQuery Mobile using simpledialog2 for auth issues I am trying to create a jQuery mobile app which will have an authorisation page, (i.e. a jqm dialog with a text input and a submit button where the user will input their username, this will be checked against a list of users/access rights pulled from Parse and if access is granted  the dialog will be removed and the user can access the app). I realise I a long way from that stage but at the minute I have used the simpledialog2 plugin with Blank mode to create a mockup of how I wanted the dialog to look and I intended to extend this into a fully functioning module.
$(document).delegate('#opendialog', 'click', function() {
   $('
').simpledialog2({
     mode: 'blank',
     headerText: 'App Auth',
     headerClose: true,
     dialogAllow: true,
     dialogForce: true,
     blankContent :
       "
Please enter your username:

"+
       "<form><input/>
"+
       "Submit</form>"
  })
})

When I was trying to extend this code I kept getting errors like "TypeError: 'undefined' is not a function (evaluating ...)" and could not find any cause for them.
I was wondering if anyone could tell me if I'm approaching this in the correct manner? I tried to create an auth page using the Button w. Input Mode as described on http://dev.jtsage.com/jQM-SimpleDialog/demos2/blankin.html#/jQM-SimpleDialog/demos2/button.html
but it also didn't work for me. Any guidance would be much appreciated. :)

A: You could bind to the pagebeforechange event to check if the user is authenticated. If not, you can dynamically create and show an auth dialog:
jQuery("body").live("pagebeforechange", function(e, data) {
    if(typeof data.toPage !== 'string')
        return;
    if(!userIsAuthenticated) {
        showAuthDialog();
        e.preventDefault();
        return false;
    }
});

A dynamically generated dialog can be shown like this:
function showAuthDialog() {
    var dialog = jQuery('

MyAuthDialog

Your auth form here.

');

    // bind events to auth form here
    // ...

    jQuery.mobile.pageContainer.append(dialog);
    jQuery.mobile.changePage(dialog);
}


text:
Q: Which license should I use for my own extension to prevent others to use it without my permission/paying? I developed a few extensions and I try to figure out which license I should use to "prevent" others e.g. our agencies to copy them and spread them to their own customers w/o my permission.

A: According to this site, you don't need a license in my case.

"If you find software that doesn't have a license, that generally
  means you have no permission from the creators of the software to use,
  modify, or share the software."

Edit: Hold on... if you don't have permission to use the software, then it makes no sense. So I still need some license... so ignore this answer please.


text:
Q: getStoreCategories() to get categories by ids I would like to get an array of categories for my magento store.
I need to use following unit for my website to work:
$categories = $helper->getStoreCategories('name', true, true);

However this lists all categories.
I would like to select categories that are important for me. I think I could do that by selecting ids of the categories or names of the categories but I don't know how to do it.
Could anybody help me please?

A: Let's say you have an array with category ids like this:
$ids = array(6,8,99);

You can get the category objects like this:
$collection = Mage::getModel('catalog/category')->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('entity_id', $ids);

if you want only active categories add this line also
$collection->addAttributeToFilter('is_active', 1);

A: Use this function and just pass category Id:
function getCategoryData($_categoryId=null) {
  // For category Collection
  $category = Mage::getModel('catalog/category')->load($_categoryId);

  // For product Collection category wise
  $prodCollection = $category->getProductCollection();

  return $prodCollection;
}


text:
Q: Connect Phone by USB Creates Open/Close Loop I'm trying to transfer some files from my cell to my laptop. the Bluetooth is being a pain and keeps stalling and failing, so I'm trying the USB cable. That's being a problem too. I choose on my phone to transfer files, and then Nautilus just keeps opening it and closing it over and over and seems stuck in a loop. What's going on & how do I stop that? I just want to plug it in & transfer the files. I tried rebooting a couple times and trying the process again, but that doesn't work.
Device: Pixel 2 XL
OS: Ubuntu 18.04

A: I tried to install libmtp and libmtp9, but Ubuntu says it is already the newest version, so all of these did not work for me
But android-file-transfer worked for me for Ubuntu 18.04 lts version and Samsung android version 5.1.1
Install android-file transfer:
$ sudo apt-get install android-file-transfer


text:
Q: graphql-php who to get result by id l am a rookie of graphql, and l never used rest or other language like this.
l can just get the fixed value with my level now.
l have a schema file like follow
demo.schema
schema {
  query: Query
}

type Query {
  id(id: Int): sub
}

type sub{
    name: String
    age: Int
}

here is demo.php:
declare(strict_types=1);
require_once 'vendor/autoload.php';
$typedef = file_get_contents('demo.graphql');

$rootValue = include 'rootvalue.php';

use \GraphQL\GraphQL;
use \GraphQL\Utils\BuildSchema;

// build schema and get query string
$schema = BuildSchema::build($typedef);
$param = file_get_contents("php://input");
$param = json_decode($param, true);
$param = $param['query'];

// get result and print it
$r = GraphQL::executeQuery($schema, $param, $rootValue)->toArray();
print_r(json_encode($r));

here is rootvalue.php
interface Root
{
    public function reslove($root, $args, $context);
}

class age implements Root
{
    public function reslove($root, $args, $context)
    {
        return 30;
    }
}

class name implements Root
{
    public function reslove($root, $args, $context)
    {
        return 'Miami';
    }
}

return [
    'id'       =>  function($root, $args){
        return $root;
    },

    'age'       =>  function($root, $args, $context) {
        $new = new age();
        return $new->reslove($root, $args, $context);
    },

    'name'       =>  function($root, $args, $context) {
        $new = new name();
        return $new->reslove($root, $args, $context);
    },
];

now l a mysql db table named user, it has id, name, age fields
how can l get the result like user.id=1
now, l can just return value like '30', 'Miami'.
But now, l need to fetch data by database, So it will be a query like this from client browser
query{
    id(id: 0){
        name
        age
    }
}

l know l cat get arg's value of id in rootvalue.php
'id'=>function($root, $args){
        $args['id'] // it will be get a value '1'
        return $root;
    },

but it is my limit what l can do. l can't get id in other place, how to do this?
PS:
l know how to get data from database, just don't know the time to fetch database, and how to transfer these data to sub object


text:
Q: How to convert Avro structure to SchemaRDD and back? Is there a way to convert Avro structure to SchemaRDD? I see an example for JavaRDD in https://issues.apache.org/jira/browse/SPARK-2736, but was unable to find anything to create SchemaRDD.
There is a link which shows to how to convert a SchemaRDD to Avro, but I wanted to know if there is something provided inside Spark 1.1
https://issues.apache.org/jira/browse/SPARK-3350

A: Yes, there is a separate package that allows you to do that: https://github.com/databricks/spark-avro
As of now it allows you to do both Avro -> SparkSQL and SparkSQL -> Avro.
It's unlikely that it will be added to Spark itself to keep the scope of the project under control, but there are many useful Spark packages being developed outside of Spark. See more at http://spark-packages.org/


text:
Q: EF Code First - Multiple column index with navigation property I want to put an index on multiple columns (like stated in this question), but one of the properties is a navigation property without a foreign key property in the model.
TL;DR at the bottom.

My model:
public class User
{
    public int Id { get; set; }
    public string Email { get; set; }
    public virtual Shop Shop { get; set; }
}

public class Shop
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Context : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Shop> Shops { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasRequired(u => u.Shop).WithMany();
        modelBuilder.Entity<User>().Property(u => u.Email).HasMaxLength(256);
    }
}

I use an extension (based on the for mentioned question):
internal static class ModelBuilderExtensions
{
    public static StringPropertyConfiguration AddMultiColumnIndex(this StringPropertyConfiguration config, string indexName, int columnOrder, bool unique = false, bool clustered = false)
    {
        var indexAttribute = new IndexAttribute(indexName, columnOrder) { IsUnique = unique, IsClustered = clustered };
        var indexAnnotation = new IndexAnnotation(indexAttribute);

        return config.HasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation);
    }

    public static PrimitivePropertyConfiguration AddMultiColumnIndex(this PrimitivePropertyConfiguration property, string indexName, int columnOrder, bool unique = false, bool clustered = false)
    {
        var indexAttribute = new IndexAttribute(indexName, columnOrder) { IsUnique = unique, IsClustered = clustered };
        var indexAnnotation = new IndexAnnotation(indexAttribute);

        return property.HasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation);
    }
}

I wish to create an index as follows:
modelBuilder.Entity<User>().Property(x => x.Email).AddMultiColumnIndex("UX_User_EmailShopId", 0, unique: true);
modelBuilder.Entity<User>().Property(x => x.Shop.Id).AddMultiColumnIndex("UX_User_EmailShopId", 1, unique: true);

But this gives me an error when scaffolding a migration:

System.InvalidOperationException: The type 'Shop' has already been
  configured as an entity type. It cannot be reconfigured as a complex
  type.

When I try to add the index as follows it gives another error:
modelBuilder.Entity<User>().Property(x => x.Shop).AddMultiColumnIndex("UX_User_EmailShopId", 1, unique: true);

The type 'My.NameSpace.Shop' must be a non-nullable value type in
  order to use it as parameter 'T' in the generic type or method
  'System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration.Property(System.Linq.Expressions.Expression>)

TL;DR
So my question is, how do I add an index using the fluent-api on the email and shop (id) combination when the shop_id is not defined in my model (and I don't want to define it)?
The resultant SQL should look something like:
CREATE UNIQUE NONCLUSTERED INDEX [UX_User_EmailShopId] ON [dbo].[User]
(
    [Email] ASC,
    [Shop_Id] ASC
)

A: TL&DR:  If you want to have multiple indexes in the FLUENT Pattern, you can do the following:
You can now (EF core 2.1) use the fluent API as follows:

modelBuilder.Entity<ClassName>()
            .HasIndex(a => new { a.Column1, a.Column2});

A: There is a couple of things you must do to achieve this using C# and fluent syntax.

*

*Add ShopId (foreign key to User class. EF will understand that this is the foreign key for the Shop navigation property, so no more actions needed
public virtual Shop Shop { get; set; }
public int ShopId { get; set; }

*Use x.ShopId in you modelbuilder index-config
modelBuilder.Entity<User>().Property(x => x.ShopId).AddMultiColumnIndex("UX_User_EmailShopId", 1, unique: true);

*Add MaxLength constraint on your User.Email property config in OnModelCreating. This because index columns can max be 900 bytes, and a regular public string in C# translates into a varchar(max) in sql server.
modelBuilder.Entity<User>().Property(c => c.Email).HasMaxLength(255).AddMultiColumnIndex("UX_User_EmailShopId", 0, unique: true);;

So what you end up with is one extra property in the User class and this OnModelCreating method in your dbcontext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().HasRequired(u => u.Shop).WithMany();
    modelBuilder.Entity<User>().Property(x => x.Email).HasMaxLength(255).AddMultiColumnIndex("UX_User_EmailShopId", 0, unique: true);
    modelBuilder.Entity<User>().Property(x => x.ShopId).AddMultiColumnIndex("UX_User_EmailShopId", 1, unique: true);
}

These small changes will result in this index being created in SQL-server:
CREATE UNIQUE NONCLUSTERED INDEX [UX_User_EmailShopId]
ON [dbo].[Users]([Email] ASC, [ShopId] ASC);

Alternatively using migrations, and not wanting to add the "FK" property ShopId to you User class, you could add the index creation in the migration UP method.
CreateIndex("Users", new[] { "Email", "ShopId" }, true, "UX_User_EmailShopId");

A: You cannot do it using fluent-api without shop_id is defined in the model.
If you noticed, you are using DbModelBuilder, which is refer to model, i.e. the models 'defined' in your code. fluent API goes only one way, from code to DB, but not the opposite.
Still you can create the index without add shop_id to the model but with pure SQL , not the fluent API
You could do it using annotation. Your User class need to be like , but only with with EF  6.1
public class User
{
    [Index("UX_User_EmailShopId", 1, IsUnique =  true)]
    public int Id { get; set; }

    [Index("UX_User_EmailShopId", 2, IsUnique = true)]
    public string Email { get; set; }

    [Index("UX_User_EmailShopId", 3, IsUnique = true)]
    public int ShopId { get; set; }

    [ForeignKey("ShopId")]
    public virtual Shop Shop { get; set; }
}


text:
Q: Providing the DataContext for Sparrow Chart WP8 from ViewModel I am following this tutorial on how to create a basic sparrow chart. Basically involves creating a ViewModel class and setting the ViewModel in the DataContext for the chart.
The ViewModel:
//Create a model
public class Model
{
    public double X { get; set; }
    public double Y { get; set; }

    public Model(double x,double y)
    {
        X = x;
        Y = y;
    }
}

// Create a ViewModel
public class ViewModel
{
    public ObservableCollection<Model> Collection { get; set; }
    public ViewModel()
    {
        Collection = new ObservableCollection<Model>();
        GenerateDatas();
    }
    private void GenerateDatas()
    {
        this.Collection.Add(new Model(0, 1));
        this.Collection.Add(new Model(1, 2));
        this.Collection.Add(new Model(2, 3));
        this.Collection.Add(new Model(3, 4));
    }
}

The XAML:
//Use the viewmodel in the Sparrow Chart
<sparrow:SparrowChart>
   <sparrow:SparrowChart.DataContext>
          **<local:ViewModel/>**
  </sparrow:SparrowChart.DataContext>
        <sparrow:SparrowChart.XAxis>
                <sparrow:LinearXAxis/>
        </sparrow:SparrowChart.XAxis>
        <sparrow:SparrowChart.YAxis>
                <sparrow:LinearYAxis/>
        </sparrow:SparrowChart.YAxis>
       <sparrow:LineSeries PointsSource="{Binding Collection}" XPath="X" YPath="Y"/>

How do i go about defining the local: namespace and then include  ViewModel in it so that it works well in the DataContext?

A: Add following line to your window's XAML code
xmlns:local="clr-namespace:Here.Comes.Your.Namespace"
In my case it looks like
<Window x:Class="MyProgram.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sparrow="http://sparrowtoolkit.codeplex.com/wpf"
        xmlns:local="clr-namespace:MyProgram"
        Title="My Program" Height="306" Width="736" MinWidth="680" MinHeight="440">

Also to actually bind collection you would use to feed data to SparrowChart, set chart's DataContext with your instance of ViewModel.
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public sealed partial class MainWindow
{
    ViewModel myViewModel;

    public MainWindow()
    {
        ...
        myViewModel = new ViewModel();
        mySparrowChart.DataContext = myViewModel;
    }
}

SparrowChart's control name is mySparrowChart of course (
<sparrow:SparrowChart Name="mySparrowChart">).


text:
Q: How to filter a p-orderList with a p-dropdown in Angular I'm new to angular, and I've been struggling to get different pieces to work together.  I have an p-orderList from PrimeNG that displays a list of JSON objects and a p-dropDown that reads a property from the listedObjects and shows all possible options.  I need to filter the orderList so that it shows all possible options when nothing is selected, or filter it to only show the kind selected.
I have the dropdown populated and firing on change.  I also can filter with typscripts built in functions.  What I can't figure out how to do is attach it back to the orderList.  Any help is greatly appreciated.
HTML

    <ng-template let-device pTemplate="item">

            {{device['object_name'] | noquotes}}

            mac: {{device.deviceData.MAC}}

            id: {{device['object_identifier']}}

            type: {{device['object_type']}}

    </ng-template>

TS
onCategoryChange(selectedType){
    var results = this.devices.filter(element => {return element.object_type === selectedType});
    console.log(results);
}

A: You need to point your p-orderList to the filtered results, so you'll have to make results a public variable on your component:
public filteredDevices: any; //make this an Array<x> of whatever your devices are, sames as this.devices
...

onCategoryChange(selectedType){
    filteredDevices = this.devices.filter(element => {return element.object_type === selectedType});
    console.log(results);
}

HTML is mostly the same, just used filteredDevices instead of devices.

    <ng-template let-device pTemplate="item">

            {{device['object_name'] | noquotes}}

            mac: {{device.deviceData.MAC}}

            id: {{device['object_identifier']}}

            type: {{device['object_type']}}

    </ng-template>

You may have to change more that that [value]="filteredDevices", I'm not positive that's where the list of devices for the
 is assigned, but use filteredDevices instead where you assign the devices for the