text:
Q: "Runtime.ImportModuleError: Error: Cannot find module 'oracledb-for-lambda'" when trying to connect oracledb to lambda function using layer? I'm trying to connect my lambda function (node.js) to oracle database. For that, I've decided to use the npm library 'oracledb-for-lambda'.
The steps Ive followed:
1.Created parent folder in system and npm init inside.
2.npm i --save oracledb-for-lambda
3.created nodejs folder and moved node_modules inside
4.Moved libociei.so from \nodejs\node_modules\oracledb-for-lambda\lib to lib folder
[Now, I think I am supposed to COPY this file and not move it BUT this file is over 100mb and so the parent directory becomes ~300mb before zipping which is impossible to use in a Lambda Layer]
This is my folder structure:  [1]: https://i.stack.imgur.com/qMuOg.png
5.Zipped the parent folder and created an s3 bucket and uploaded this file.
6.Create a layer in Lambda and pasted the URL of the zip file from s3
7.Add this custom layer
In Lambda Code:
var os = require('os');
var fs = require('fs');
var oracledb = require('oracledb-for-lambda');

exports.handler = async (event, context) => {
    let str_host = os.hostname() + ' localhost\n';
    fs.writeFileSync(process.env.HOSTALIASES, str_host, function(err) {
        if (err) throw err;
    });
    var connAttr = {
        user: process.env.USERNAME,
        password: process.env.PASSWORD,
        connectString: process.env.CONNECTION_STRING
    };

    const promise = new Promise(function(resolve, reject) {
        oracledb.getConnection(connAttr, function(err, connection) {
            if (err) {
                reject({
                    status: "ERROR"
                });
            }
            resolve({
                status: "SUCCESS"
            });
        });
    });
    return promise;
}

In Lambda Configuration:
Environment variables (4)
CONNECTION_STRING   //ip:port/xyz
HOSTALIASES /tmp/HOSTALIASES
PASSWORD    password
USERNAME    username
8.Then I saved and deployed this function.
In API gateway, Ive connected this lambda function through lambda proxy integration which I deploy and get this message:

{"message": "Internal server error"}

When I go to CloudWatch Logs I can see this:
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module 'oracledb-for-lambda'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module 'oracledb-for-lambda'",
        "Require stack:",
        "- /var/task/index.js",
        "- /var/runtime/UserFunction.js",
        "- /var/runtime/index.js",
        "    at _loadUserApp (/var/runtime/UserFunction.js:202:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:242:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:43:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:1085:14)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)",
        "    at Module.load (internal/modules/cjs/loader.js:950:32)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:790:12)",
        "    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)",
        "    at internal/main/run_main_module.js:17:47"
    ]
}

Not sure where I am going wrong. Any help would be appreciated. Thank you :)


text:
Q: GTK themes not displaying correctly Had to reinstall gdm3 and gnome-shell-common and now my GTK themes are not displaying correctly. Using Ubuntu 19.04
Example:

A: Ended up doing this:
sudo apt-get install --reinstall libgtk-3-common light-themes gtk3.0
dconf reset -f /org/compiz
sudo reboot

Worked like a charm

redpajama_set_name: RedPajamaStackExchange


text:
Q: adding a number to a variable I am trying to get the contents of a txt file "usernum.txt", get the contents, add one to that number, and replace the current number with the new one.  Here is what I have so far
#!/bin/sh
ID=0
cat ''$pwd'usernum.txt' >> $ID
count1=1
IDB=$(($ID+$count1))
rm "usernum.txt"
touch "usernum.txt"
echo $IDB >> usernum.txt

It runs but when I open the file, it stays the same.  Any ideas?
Thanks,
Mike

A: You should store the output from cat into ID instead of using >>. The way you are doing that you always add to a file named '0'. To store the output of cat use:
ID=$( cat 'usernum.txt' )

I have also removed the 'pwd' as you do not need it and also it gets escaped by the single quotes.
EDIT: here is a complete working example. Note that if there is no usernum.txt file this will print some errors(cat and rm fail) but still will work(i.e. will print 1 in the file). You should perform a check to see if the file exists to avoid these errors:
ID=$( cat 'usernum.txt' )
count1=1
IDB=$(($ID+$count1))
rm "usernum.txt"
touch "usernum.txt"
echo $IDB >> usernum.txt


text:
Q: How can I transfer system data to a new 3DS without using System Transfer? I recently punched my 3DS while playing Mario Kart and cracked the screen. I've bought a new 3DS console, but can't do a System Transfer because the broken 3DS can't connect to the internet.
Is there any way I can use the old SD card with all of my saved data in my new 3DS? I tried to transfer the data, from the old card to the new card, but the data will not appear in the new console. I don't want to lose my Ambassador Certificate and NES & Gameboy games!


text:
Q: bash compare variable and variable + string I have a small bash script to do some AWS CLI stuff. I am having issues with line 18 as I need to compare function1 =! (function2 && string) specifically
if [ "$(state)" ] != [ "$(task_name)" && "RUNNING" ]
see below;
#!/bin/bash

region="eu-west-1"
cluster="mis-core-dev"

## Get task name, state and check against "RUNNING"
task_name () {
  aws ecs describe-tasks --region ${region} --cluster ${cluster} --tasks "$task" --query 'tasks[].containers[].name' --output text
}
state () {
  aws ecs describe-tasks --region ${region} --cluster ${cluster} --tasks "$task" --query 'tasks[].containers[].[name, lastStatus]' --output text
}

## Get Task names from Cluster
task_status () {
  mapfile -t tasksInCluster < <(aws ecs list-tasks --region ${region} --cluster ${cluster} | jq -r '.taskArns[]')
  for task in "${tasksInCluster[@]}"; do
      if [ "$(state)" ] != [ "$(task_name)" && "RUNNING" ]
      then
        echo "$(task_name)" "NOT RUNNING!"
        exit 1
      else
        state
      fi
  done
}

task_status

I am trying to aviod using jq as I want to keep dependencies to a minimum

A: I have no AWS CLI stuff, so here is example with stubs:
task_name () {
  echo "$task"
}
state () {
  echo "$task RUNNING"
}

task_status () {
  tasksInCluster=(mis-dev-core mis-dev-other "mis-dev with space")
  for task in "${tasksInCluster[@]}"; do
      if [ "$(state)" != "$(task_name) RUNNING" ]
      then
        echo "$(task_name)" "NOT RUNNING!"
        exit 1
      else
        state
      fi
  done
}

task_status

UPDATE: As noted @charles-duffy, use array instead string.


text:
Q: process url from rss feed as new items come in Can someone recommend an appropriate way to do this.
I'm subscribed to a number of rss feeds. What I would like to do is
obtain the url and then do  DoSomething(url) when i have the url of the new item that has come in.
basically process the new item as it comes in.
What would I need to do to have this automatically? without me having to force the process?

A: Make scheduler to send request to RSS feed source once per munute/hour/other time period.
Parse responce via stuff from System.ServiceModel.Syndication namespace - you'll have a collection of SyndicationItems that represents obtained data.
For each item that you don't have in your storage - run DoSomething with url from SyndicationItem.Links.


text:
Q: show location on google map android I've a EditText and a Button I want to find location in map. I'm using AsyncTask to execute here is my calling of AsyncTask class. When I use Toast msg it display my location but in map it was force closed
new GeocoderTask().execute(location);
Toast.makeText(getApplicationContext(), location, Toast.LENGTH_LONG).show();

Here is my GeocoderTask class to display location in map
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{

            @Override
            protected List<Address> doInBackground(String... locationName) {
                // Creating an instance of Geocoder class
                Geocoder geocoder = new Geocoder(getBaseContext());
                List<Address> addresses = null;

                try {
                    // Getting a maximum of 3 Address that matches the input text
                    addresses = geocoder.getFromLocationName(locationName[0], 3);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return addresses;
            }

            @Override
            protected void onPostExecute(List<Address> addresses) {

                if(addresses==null || addresses.size()==0){
                    Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
                }

                // Clears all the existing markers on the map
                googleMap.clear();

                // Adding Markers on Google Map for each matching address
                for(int i=0;i<addresses.size();i++){

                    Address address = (Address) addresses.get(i);

                    // Creating an instance of GeoPoint, to display in Google Map
                    latLng = new LatLng(address.getLatitude(), address.getLongitude());

                    String addressText = String.format("%s, %s",
                            address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                            address.getCountryName());

                    markerOptions = new MarkerOptions();
                    markerOptions.position(latLng);
                    markerOptions.title(addressText);

                    googleMap.addMarker(markerOptions);

                    // Locate the first location
                    if(i==0)
                        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                }
            }
        }
}

But it doesn't display location.

A: Suppose you got error in line new Geocoder(getBaseContext());, so suggest you use constructor for passing Context to AsyncTask:
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{

        private Context mContext;
        public GeoCoderTask(Context context) {
            super();
            mContext = context;
        }

        @Override
        protected List<Address> doInBackground(String... locationName) {
            // Creating an instance of Geocoder class
            Geocoder geocoder = new Geocoder(mContext);

            ... ...

        }
}

Hope this help!


text:
Q: Keras val_acc and model.evaluate acc not matching I am using Python 3.6.9 (Anaconda), keras 2.2.4 and tensorflow 1.10.0 to make a binary classifier using partial data from celebA dataset. My files are divided as following:
                  dataset
           __________|_________
          |                    |
    training_set        validation_set
     _____|_____          _____|_____
    |           |        |           |
   men        women     men         women
    |           |        |           |
   40k         40k       4k          4k

Running my code I get (set to 2 epochs as example):
Using TensorFlow backend.
Found 80000 images belonging to 2 classes.
Found 8000 images belonging to 2 classes.
Class weights:  {0: 1.0, 1: 1.0}

Epoch 1/2
1250/1250 [==============================] - 341s 273ms/step - loss: 0.3103 - acc: 0.8662 - val_loss: 0.2502 - val_acc: 0.9005

Epoch 2/2
1250/1250 [==============================] - 346s 276ms/step - loss: 0.2094 - acc: 0.9152 - val_loss: 0.2133 - val_acc: 0.9129

8000/8000 [==============================] - 9s 1ms/step
[8.048886075259292, 0.500625]

The problem is, val_acc reaches to 0.9 and the acc I get only 0.5 (understandable). The set, model and weights used to validate are the same used to evaluate yet they give totally different values, why?
Other thing, with a really simple network like this, is the train acc really reaching 0.86 with one epoch? Is this value reliable?
Here's my code:
import os
import numpy as np
import keras
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers import Dense, Flatten
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.optimizers import Adam
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential
import cv2
from keras.models import model_from_json
import psutil

p = psutil.Process(os.getpid())

try:

    p.nice(19) #Ubuntu

except:

    p.nice(psutil.HIGH_PRIORITY_CLASS) #Windows

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

HEIGHT = 128
WIDTH = 128

def prepare_image(file):
    img_path = ''
    img = image.load_img(img_path + file, target_size=(HEIGHT, WIDTH))
    img_array = image.img_to_array(img)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)
    return keras.applications.mobilenet.preprocess_input(img_array_expanded_dims)

model = Sequential()
model.add(Conv2D(32, (3, 3) , padding='same', activation='relu', input_shape=(HEIGHT,WIDTH,3)))
model.add(Conv2D(64, (3, 3) , padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(BatchNormalization())

model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

opt = Adam(lr = 0.0001)

train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input,
    rotation_range=20,
    zoom_range=0.2,
    shear_range=0.2,
    horizontal_flip=True,
    rescale=1./255
    )

valid_datagen=ImageDataGenerator(preprocessing_function=preprocess_input,
    rescale=1./255)

train_generator=train_datagen.flow_from_directory('dataset/training_set',
    target_size=(HEIGHT,WIDTH),
    color_mode='rgb',
    batch_size=64,
    class_mode='binary',
    )

valid_generator=valid_datagen.flow_from_directory('dataset/validation_set',
    target_size=(HEIGHT,WIDTH),
    color_mode='rgb',
    batch_size=64,
    class_mode='binary'
    )

step_size_train=train_generator.n//train_generator.batch_size
step_size_valid=valid_generator.n//valid_generator.batch_size

model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])

from collections import Counter
itemCt = Counter(train_generator.classes)
maxCt = float(max(itemCt.values()))
cw = {clsID : maxCt/numImg for clsID, numImg in itemCt.items()}

print("Class weights: ", cw)

model.fit_generator(
    train_generator,
    steps_per_epoch = step_size_train,
    validation_data = valid_generator,
    validation_steps = step_size_valid,
    epochs=2,
    verbose = 1,
    class_weight=cw
    )

model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

model.save_weights("model.h5")

def load_data():

    path = os.getcwd() + "\\dataset\\validation_set\\"
    lista = os.listdir(path)
    lista.sort()

    data = []
    pred = []

    for i in range(len(lista)):

        listb = os.listdir(path+lista[i])
        listb.sort()

        for j in listb:

            pic = cv2.imread(path+lista[i]+"/"+j)
            pic = cv2.resize(pic, (HEIGHT,WIDTH)) / 255.
            data.append(pic)

            pred.append(i)

    data = np.asarray(data)
    pred = np.asarray(pred)

    return data, pred

data, pred = load_data()

def load_model():

    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()

    loaded_model = model_from_json(loaded_model_json)
    loaded_model.load_weights("model.h5")
    loaded_model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])

    return loaded_model

loaded_model = load_model()

result = loaded_model.evaluate(data, pred)
print(result)

I edited with the corrections suggested but still having the same problem. Am I loading the model the right way?

A: In your code
valid_generator=train_datagen.flow_from_directory('dataset/validation_set',
    target_size=(HEIGHT,WIDTH),
    color_mode='rgb',
    batch_size=64,
    class_mode='binary'
    )

valid_datagen should go here, instead of train_datagen.

Also I think while calling load_data() you are not re-scaling your data by 1./255 which you are doing while training and validating.
This should fix your issue.


text:
Q: Mobile and Desktop media query priority I'm a beginner in front-end web development. I want to know the order of priority when writing CSS media queries in desktop first approach. Do i write mobile queries first and tablet queries below it, in this manner:
 /*Desktop CSS*/
/*Media query for tablet*/
/*Media query for Mobile*/
or the other way around.

A: You can write anywhere but if you are a beginner then I suggest you create a separate file for responsive CSS so that you will not confused.
SO in the style.css desktop approach and in responsive.css all media queries for mobile and tablet.
Standered Media queries:
@media screen and (min-width: 1200px){} /* Desktop */
@media screen and (min-width: 1025px) and (max-width: 1199px){} /* small laptop */
@media screen and (min-width: 768px) and (max-width: 1024px){} /* tablet */
@media screen and (min-width: 575px) and (max-width: 767.98px){} /* tablet and large mobiles */
@media screen and (min-width: 320px) and (max-width: 480px){} /* Mobile*/

Thanks


text:
Q: Почему не работает сортировка в mat-table? Подскажите почему не работает сортировка в табличке, все делаю по примеру из официальной документации Angular Material
Код шаблона:

****************

  <ng-container matColumnDef="Фамилия, имя, отчество">
     Фамилия, имя, отчество
     {{element.name}}
  </ng-container>
  <ng-container matColumnDef="скилл P">
     скилл P
     {{element.skillP}}
  </ng-container>
  <ng-container matColumnDef="скилл A">
     скилл A
     {{element.skillA}}
  </ng-container>
  <ng-container matColumnDef="скилл E">
     скилл E
     {{element.skillE}}
  </ng-container>
  <ng-container matColumnDef="скилл I">
     скилл I
     {{element.skillI}}
  </ng-container>
  <ng-container matColumnDef="Подразделение">
     Подразделение
     {{element.department}}
  </ng-container>
  <ng-container matColumnDef="Должность">
     Должность
     {{element.position}}
  </ng-container>

А здесь код компонента:
import { Component, OnInit, ViewChild } from '@angular/core';
import { Subscription, combineLatest } from 'rxjs';

import { PersonsService } from 'src/app/shared/services/persons.service';
import { PaeiService } from 'src/app/shared/services/paei.service';
import { Paei } from 'src/app/assessment/paei-test/models/paei.model';
import { Person } from 'src/app/shared/models/person.model';
import { MatTableDataSource, MatSort } from '@angular/material';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'mvv-paei-table',
  templateUrl: './paei-table.component.html',
  styleUrls: ['./paei-table.component.scss']
})

export class PaeiTableComponent implements OnInit {

  sub: Subscription;
  personsList: Person[] = [];
  paeiList: Paei[] = [];
  persons: {
    name: string,
    skillP: number,
    skillA: number,
    skillE: number,
    skillI: number,
    department: string,
    position: string
  }[] = [];

  tabledata: any;

  public displayedColumns = [
    'Фамилия, имя, отчество',
    'скилл P',
    'скилл A',
    'скилл E',
    'скилл I',
    'Подразделение',
    'Должность'
];
  isLoaded = false;

  constructor(
    private personsService: PersonsService,
    private paeiService: PaeiService,
  ) { }

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {

    this.sub = combineLatest(
      this.personsService.getPersons(),
      this.paeiService.getAllPaei()
    ).subscribe(value => {
      value[0].forEach(doc => {
        const person = new Person(
          doc.data().name,
          doc.data().middleName,
          doc.data().surname,
          doc.data().gender,
          doc.data().date,
          doc.data().position,
          doc.data().department,
          doc.id
        );
        this.personsList.push(person);
      });

      value[1].forEach(doc => {
        const paei = new Paei(
          doc.data().id,
          doc.data().date,
          doc.data().skillP,
          doc.data().skillA,
          doc.data().skillE,
          doc.data().skillI,
          doc.data().isReaded
        );
        this.paeiList.push(paei);
      });
      for (let i = 0; i < this.paeiList.length; i++) {

        const pers = this.personsList.filter(
          res => res.personId === this.paeiList[i].id);
          const name = pers[0].surname + ' ' + pers[0].name + ' ' + pers[0].middleName;
          this.persons.push(
            {
              name: name,
              skillP: this.paeiList[i].skillP,
              skillA: this.paeiList[i].skillA,
              skillE: this.paeiList[i].skillE,
              skillI: this.paeiList[i].skillI,
              department: pers[0].department,
              position: pers[0].position
            }
          );

          this.tabledata = new MatTableDataSource(this.persons);

        }
        this.isLoaded = true;

        setTimeout(() => {
          this.tabledata.sort = this.sort;
          console.log('проверка сортировки', this.sort);
        }, 1000);

      });

  }

}

На таймаут внимания не обращайте.

A: Вы не совсем делаете все по примеру, потому что используете ngIf директиву
Я предположу, что у вас импортирован MatSortModule, поэтому сразу опишу вашу проблему.
Когда вы используете декоратор @ViewChild - вы говорите компилятору сгененировать определенную структуру данных, которая называется NodeDef (определение узла). В рантайме Angular же не просто строит DOM дерево, а также за вас сеттит все необходимые свойства класса, которые вы декорируете с помощью @Input() | @ViewChild() | @HostBinding() и так далее.
В вашем примере во время первого механизма обнаружения изменений - Angular вызывает функцию checkAndUpdateQuery, которая сеттит свойства, декорируемые с помощью @ViewChild() | @ViewChildren() | @ContentChild() | @ContentChildren(). Вся проблема в том, что элемент table обернут в ng-template (из-за использования директивы ngIf), к тому же isLoaded равен false на начальном этапе, поэтому Angular физически не может получить доступ к инстансу директивы MatSort (потому что он еще не создан) и засеттить свойство. К тому же сам элемент table проджектится в DOM асинхронно.
Дабы убедиться в этом - выведите в консоль sort в хуке ngOnInit:
ngOnInit() {
  console.log(this.sort); // undefined
}

Есть 2 пути решения этой проблемы:
1) Использовать атрибут hidden вместо директивы ngIf:

  ...

2) Заинжектить ссылку на вьюху в конструктор и запустить механизм обнаружения изменений после сеттинга свойства isLoaded = true, который в свою очередь опять вызовет функцию checkAndUpdateQuery, которая засеттит вам свойство sort:
constructor(private ref: ChangeDetectorRef) {}

ngOnInit() {
  combineLatest(...).subscribe(() => {
    ...

    this.isLoaded = true;
    this.ref.detectChanges();
    console.log(this.sort);
    this.tableDataSource.sort = this.sort;
  });
}

A: у вас стоит директива *ngIf в
, mat-sort с ней не работает. Попробуйте заменить ее на [hidden]="!isLoaded"


text:
Q: reportlab background color of page (BaseDocTemplate) I just want simple set background color of page. But with report lab you should use left hand to catch right ear under your knee... I googled for it, but everywhere is simple anser - create Rect with color. BUT HOW?!?!?!?!?!?
doc = BaseDocTemplate(buffer)

Elements=[]

#Two Columns
frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')

Elements.append(Paragraph('HEADING',styles['Heading1']))
Elements.append(Paragraph('Lorem Ipsum Dolor', styles['Normal']))

doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1,frame2]), ])

doc.build(Elements)

I tried to use Drawing, but 0,0 isn't  left bottom coordinates of page but left bottom coordinates of Drawing... But how set Drawing to left bottom - don't know...
 draw = Drawing(500, 200)
 rectangle = Rect(0,0,100,100)
 color = PCMYKColor(15,9,0,8)
 rectangle.fillColor = color
 rectangle.strokeColor = color
 draw.add(rectangle)

 Elements.append(draw)

I found, that doc.width and doc.height would be great for top right coordinates...

A: The solution which works for me:
 Elements=[]

 def setBackground(canvas, document):
     color = PCMYKColor(15,9,0,8)
     canvas.setFillColor(color)
     canvas.rect(0,0,doc.width+doc.leftMargin+doc.rightMargin,doc.height+doc.topMargin+doc.bottomMargin, fill=True, stroke=False)

 #Two Columns
 frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
 frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')

 Elements.append(Paragraph('HEADING',styles['Heading1']))
 Elements.append(Paragraph('Lorem Ipsum Dolor', styles['Normal'])

 doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1,frame2],onPage=setBackground) ])

 #start the construction of the pdf
 doc.build(Elements)


text:
Q: create localhost connection in Oracle SQL Developer Tool I want to create localhost connection in Oracle SQL Developer tool
my credentials are

username : SYSTEM
password : SYSTEM
Hostname :localhost or 127.0.0.1
port     : 1521
sid      : xe

When i connect i gives error The Network Adapter could not establish connection

A: The Network Adapter could not establish connection is caused because:

*

*The database host name or port number is wrong.

*The listener process (service) is not running.  You can re-start it with the "lsnrctl start" command or on Windows by starting the listener service.

A: you have either the wrong SQL Developer URL or you have a basic SQL*Net connectivity issue!  This error is most likely caused by one of these factors:

*

*You are using the wrong URL

*The wrong port number or IP address (or DNS host name) was used

*The listener is not configured properly

*The listener process (service) is not running.  You can re-start it with the "lsnrctl start" command or on Windows by starting the listener service.
For a step by step checklist, see the notes on troubleshooting an Oracle connection problem.


text:
Q: Is the set of the solutions $x+y-(2a^2+2a)|z|=a^3-a$ a subspace? For the parameter $a\in \mathbb{R}$, determine whether the set of solutions of the equation

$$x+y-(2a^2+2a)|z|=a^3-a$$

is a subspace in $\mathbb{R^3}$ or not. Justify.

A: HINT
Let check the properties that a subspace has to fulfill.
Firstly check whether the solution $(x,y,z)=(0,0,0)$ is in the set that is
$$x+y-(2a^2+2a)|z|=a^3-a\implies a^3-a=a(a^2-1)=0 \implies a=0,\pm1$$


text:
Q: Calling a JavaScript function from PHP I have a php script that is a bit of a mess and after a form entry, I need to get an address, and display it on a google map.  The html and php is crammed into the same script so I essentially need to call the JavaScript as the PHP is happening.  Is there a way to do this?
Thanks,
Alex

A: You can POST your from to a different frame (or iframe), so your page would not reload. The response of your PHP file which comes back to that frame can contain JavaScript code, which will be executed. Something like:
echo('<script type="text/javascript"> alert("Executed on client side"); </script>');

A: No, PHP executed by the server and returns the full response to the browser. JavaScript in the page is then executed by the client.

A: You can't call Javascript functions from PHP. You can set the Javascript to run when the page loads instead.

A: What you want is something like this:
<script type="text/javascript"></script>
var userAddress = "<?php echo $_POST['address']; ?>";
doSomethingWithAddress(userAddress);
</script>

If that code is on the page which you are POSTing the address to, it would take the address from the user, and write it into a javascript tag. The PHP will get executed first on the server, before building the HTML document. This new document has the variable available to the javascript.

A: I don't know how you would go about doing that, but this seems like a good place to start looking:
http://code.google.com/intl/en/


text:
Q: Nashorn : are nashorn's js objects extensible I've an issue with nashorn where i want to extend the JFrame instance.
The following code
print(Object.isExtensible(frame));

Where frame is the instance. Well this line throws a TypeError, while :
Object.prototype.toString.call(frame)

returns [Object javax.swing.JFrame]
meaning it is an object whose constructor is javax.swing.JFrame.
I'm confused and would like some suggestion.

A: Java objects by themselves are not extensible (JavaScript objects are.)
You have two options:

*

*Wrap the Java object in a JavaScript object or

*Use Java.extend to create a subclass.  http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html


text:
Q: Could Linux kernel load and run another Linux kernel? I wish to load Linux kernel from USB device that make some actions and load another kernel from HDD. It is possible to force kernel to give control to another one?

A: Yes, kexec does this, and many servers do this for failsafe booting


text:
Q: social media login of my website not working in iphone I'm using facebook and google plus login in my website and it is working fine at all devices except Iphone, I make a lot of searching I found that google has been block native apps from make authentication since 2017
update : the website I'm developing is a splash screen that opened to the user when he try to connect to cisco meraki access point to authenticate him and give him access to the internet ,
when an iphone mobile try to connect to the access point the splash screen opened in the native browser of it so the facebook and google plus buttons doesn't work
Do you have any suggestions or solutions about that issue?

A: I recently resolved this issue on a website I manage with these steps:

*

*login to console.developers.google.com,

*EDIT your APP, under;

*

*Authorized JavaScript origins, and Authorized redirect URIs,

*Enter:

*

*http://yoursitenamehere.com

*https://yoursitenamehere.com if it has ssl and

*Save

Refresh your page and try to sign-in now.
For facebook:

*

*sign-in to your facebook developers platform

*

*under facebook login

*go to Settings

*Valid OAuth Redirect URIs

*

*(after filling your app domain details, Copy and Paste the code below Ctrl&Shift V) https://example.com/?SuperSocializerAuth=Facebook (replace the example.com with the domain name you're activating social login for)


text:
Q: Scala Parser Issues I am having issues testing out the Scala Parser Combinator functionality for a simple Book DSL.
Firstly there is a book class:
case class Book (name:String,isbn:String) {
def getNiceName():String = name+" : "+isbn
}

Next, there is the simple parser:
object BookParser extends StandardTokenParsers {
  lexical.reserved += ("book","has","isbn")

  def bookSpec  = "book" ~> stringLit ~> "has" ~> "isbn" ~> stringLit ^^ {
            case "book" ~ name ~ "has" ~ "isbn" ~ isbn => new Book(name,isbn) }

  def parse (s: String) = {
    val tokens = new lexical.Scanner(s)
    phrase(bookSpec)(tokens)
  }

  def test (exprString : String) = {
     parse (exprString) match {
         case Success(book) => println("Book"+book.getNiceName())
     }
  }

  def main (args: Array[String]) = {
     test ("book ABC has isbn DEF")
  }
}

I'm getting a range of errors trying to compile this - some which seem a strange to me when trying to deconstruct the other examples on the internet. For example, the bookSpec function appears nearly identical to the other examples?
Is this the best way to build a simple parser like this?
Thanks

A: When you use ~> or <~, you are discarding the element from which the arrow comes. For example:
"book" ~> stringLit // discards "book"
"book" ~> stringLit ~> "has" // discards "book" and then stringLit
"book" ~> stringLit ~> "has" ~> "isbn" // discards everything except "isbn"
"book" ~> stringLit ~> "has" ~> "isbn" ~> stringLit // discards everything but the last stringLit

You could write it like this:
def bookSpec: Parser[Book] = ("book" ~> stringLit <~ "has" <~ "isbn") ~ stringLit ^^ {
  case name ~ isbn => new Book(name,isbn)
}

A: You're on the right track. There are a few issues in your parser.  I'll post the corrected code, then explain the changes.
import scala.util.parsing.combinator._
import scala.util.parsing.combinator.syntactical._

case class Book (name: String, isbn: String) {
  def niceName = name + " : " + isbn
}

object BookParser extends StandardTokenParsers {
  lexical.reserved += ("book","has","isbn")

  def bookSpec: Parser[Book]  = "book" ~ ident ~ "has" ~ "isbn" ~ ident ^^ {
            case "book" ~ name ~ "has" ~ "isbn" ~ isbn => new Book(name, isbn) }

  def parse (s: String) = {
    val tokens = new lexical.Scanner(s)
    phrase(bookSpec)(tokens)
  }

  def test (exprString : String) = {
     parse (exprString) match {
       case Success(book, _) => println("Book: " + book.niceName)
       case Failure(msg, _) => println("Failure: " + msg)
       case Error(msg, _) => println("Error: " + msg)
     }
  }

  def main (args: Array[String]) = {
     test ("book ABC has isbn DEF")
  }
}

1. Parser return value
In order to return a book from a parser, you need to give the type inferencer some help. I changed the definition of the bookSpec function to be explicit: it returns a Parser[Book]. That is, it returns an object which is a parser for books.
2. stringLit
The stringLit function you used comes from the StdTokenParsers trait. stringLit is a function that returns Parser[String], but the pattern it matches includes the double-quotes that most languages use to delimit a string literal.  If you are happy with double-quoting words in your DSL, then stringLit is what you want. In the interest of simplicity, I replaced stringLit with ident. ident looks for a Java-language identifier. This isn't really the right format for ISBNs, but it did pass your test case. :-)
To match ISBNs correctly, I think you'll need to use a regex expression instead of idents.
3. Ignore-left sequence
Your matcher used a string of ~> combiners. This is a function that takes two Parser[_] objects and returns a Parser that recognizes both in sequence, then returns the result of the right hand side. By using a whole chain of them to lead up to your final stringLit, your parser would ignore everything except the final word in the sentence. That means it would throw away the book name, too.
Also, when you use ~> or <~, the ignored tokens should not appear in your pattern matching.
For simplicity, I changed these all to simple sequence functions and left the extra tokens in the pattern match.
4. Matching results
The test method needs to match all the possible results from the parse() function. So, I added the Failure() and Error() cases. Also, even Success includes both your return value and the Reader object. We don't care about the reader, so I just used "_" to ignore it in the pattern match.
Hope this helps!


text:
Q: How to add floating label on Spinner After using the Android Design Support Library's TextInputLayout to place a floating label above an EditText component, I was wondering if there is a way to add a floating label to the Spinner component (not necessarily using the Design Library).
By this, I mean something like a TextView placed above the Spinner (obviously no animations like the TextInputLayout), but I want the text size, font and colour to match that of the TextInputLayout's floating label.
For example, it would look something like this (see the labels above the Spinners):

As I mentioned before, my main aim is to have a label above the Spinner, just as in the TextInputLayout - so text size, font, colour, and distances between the label and the component would be the same.
On the Google Design page about floating label text fields, there is a diagram showing dimensions of the label relative to the component, but there is no indication of the label text colour or size:

So, to summarise, I am asking:
- If there is a special component to achieve what I am asking or a custom view I can use, what would it be, and how can I use it.
- If not, what is the floating label text size, colour and font, so that I can place a TextView above my Spinner with the layout dimensions shown in the above image.

EDIT:
From the Google Design guidelines for text fields, it has the following for floating labels:

Hint and input font: Roboto Regular 16sp
  Label font: Roboto Regular 12sp
  Tile height: 72dp
  Text top and bottom padding: 16dp
  Text field divider padding: 8dp

as well as the images shown above.
So the floating label font is: Roboto Regular 12sp. You can therefore use a TextView to display the Spinner label as I do not know of any custom Views or special components you could use.
However, after trying it out, it does not look quite as good as the example shown in the image. A custom view may be better for this, as it could look nicer, but the solution above is just one way of achieving something close to what I originally wanted.

A: I modified Rodrigo's solution to use an adapter, i.e. more like a standard Spinner
https://gist.github.com/smithaaron/d2acd57937d7a4201a79

A: I have an alternative solution that uses the behavior of TextInputLayout and a custom DialogFragment (AlertDialog) to emulate a spinner dialog popup.
layout.xml:
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/your_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/your_label"
        android:maxLines="1"
        android:inputType="textNoSuggestions"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:focusable="false"
        style="@style/Base.Widget.AppCompat.Spinner.Underlined"/>
</android.support.design.widget.TextInputLayout>

Create Custom Spinner via DialogFragment (AlertDialog)
SpinnerFragment.java:
public class SpinnerFragment extends DialogFragment {

private static final String TITLEID = "titleId";
private static final String LISTID = "listId";
private static final String EDITTEXTID = "editTextId";

public static SpinnerFragment newInstance(int titleId, int listId, int editTextId) {
    Bundle bundle = new Bundle();
    bundle.putInt(TITLEID, titleId);
    bundle.putInt(LISTID, listId);
    bundle.putInt(EDITTEXTID, editTextId);
    SpinnerFragment spinnerFragment = new SpinnerFragment();
    spinnerFragment.setArguments(bundle);

    return spinnerFragment;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final int titleId = getArguments().getInt(TITLEID);
    final int listId = getArguments().getInt(LISTID);
    final int editTextId = getArguments().getInt(EDITTEXTID);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    try {
        final String[] items = getResources().getStringArray(listId);

        builder.setTitle(titleId)
                .setItems(listId, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int pos) {
                        EditText et = (EditText) getActivity().findViewById(editTextId);
                        String selectedText = items[pos];
                        if (!TextUtils.isEmpty(selectedText)) {
                            et.setText(selectedText);
                        } else {
                            et.getText().clear();
                        }
                    }
                });

    } catch (NullPointerException e) {
        Log.e(getClass().toString(), "Failed to select option in " + getActivity().toString() + " as there are no references for passed in resource Ids in Bundle", e);
        Toast.makeText(getActivity(), getString(R.string.error_failed_to_select), Toast.LENGTH_LONG).show();
    }

    return builder.create();
}

}
Activity.java:
private void addCustomSpinner() {
    EditText yourEt = (EditText) findViewById(R.id.your_et);
    yourEt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showCustomSpinnerDialog(view);
        }
    });
}

private void showCustomSpinnerDialog(View v) {
    int titleId = R.string.your_label;
    int listId = R.array.spinner_selections;
    int editTextId = R.id.your_et;
    SpinnerFragment spinnerFragment = SpinnerFragment.newInstance(titleId, listId, editTextId);
    spinnerFragment.show(getFragmentManager(), "customSpinner");
}

Result
When you click on the spinner styled TextInputLayout, it will trigger an alert dialog containing your list of selections. Once a selection is chosen, the EditText will be populated with your selection and the label will float like how you want.

A:
I want the text size, font and colour to match that of the TextInputLayout's floating label.

This can be achieved easily without any external libraries. After trying to hack the TextInputLayout and even making my own custom view, I realized that using a simple TextView takes much less code and it's probably more efficient.
The text style can be copied from the AppCompat library.
The style
From the Material Design guidelines we get the following information:

*

*the label should have a bottom margin of 8dp

*the label should be vertically aligned with the input text

Here's what the guidelines do not mention about the Material EditText:

*

*it has a left padding of 4dp

*its label actually doesn't have any spacing of 16dp above it, this is left to the interface designer: this makes sense because if you place it under another EditText, you will only need an additional 8dp of space

Moreover, the Design Support Library contains this style for the label of a focused element:
<style name="TextAppearance.Design.Hint" parent="TextAppearance.AppCompat.Caption">
    <item name="android:textColor">?attr/colorControlActivated</item>
</style>

Inactive elements simply use TextAppearance.AppCompat.Caption.
Implementation
Add the following to your dimens.xml file:
<dimen name="input_label_vertical_spacing">8dp</dimen>
<dimen name="input_label_horizontal_spacing">4dp</dimen>

Then add this to styles.xml:
<style name="InputLabel" parent="TextAppearance.AppCompat.Caption">
    <item name="android:paddingBottom">@dimen/input_label_vertical_spacing</item>
    <item name="android:paddingLeft">@dimen/input_label_horizontal_spacing</item>
    <item name="android:paddingRight">@dimen/input_label_horizontal_spacing</item>
</style>

If you want the label to always have the highlighted (accent) color, replace TextAppearance.AppCompat.Caption with TextAppearance.Design.Hint from the Google Design Support Library. However, this will probably look a bit weird if you also have labeled EditText views on the same screen.
Finally, you can put a TextView above your Spinner (or any other element) with the style applied:
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/category"
    style="@style/InputLabel" />

Result
The following screenshot shows a simple example with two normal TextInputLayout views followed by a label and a Spinner. I didn't apply the additional 8dp spacing to separate them further, but this shows you that the size, font and color are reflected.
The elements inside the Spinner have a different padding, however I prefer to keep the vertical alignment with all the other labels to get a more uniform look.

A: I achieved this by using an AutoCompleteTextView, disabling the keyboard and showing the options on touch.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.locations));

AutoCompleteTextView mTextView = (AutoCompleteTextView) findViewById(R.id.location);

mTextView.setAdapter(adapter);
mTextView.setKeyListener(null);
mTextView.setOnTouchListener(new View.OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event){
        ((AutoCompleteTextView) v).showDropDown();
        return false;
    }
});

A: I have a gist made by myself to solve the same problem that you have.
Check It out:
https://gist.github.com/rodrigohenriques/77398a81b5d01ac71c3b
Now I don't need spinners. You will still having floating label effect with animations included.

A: Here is my trick,
the good things is that everything will work like you want,
but the bad is that it is increasing layout hierarchy, and you have to handle functionality in code, and it is an ugly solution:
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/til"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/edt"
                android:layout_width="match_parent"
                android:layout_height="@dimen/edt_height"
                android:hint="@string/create_gcc_visa_txt_step" />

        </android.support.design.widget.TextInputLayout>

        <Spinner
            android:id="@+id/spn"
            style="@style/MyAppTheme.Base.Spinner"
            android:layout_height="@dimen/edt_height"
            android:layout_alignBottom="@id/til" />

    </RelativeLayout>

and override adapter for spinner, to make selected values transparent
public class MySpinnerAdapter extends SimpleAdapter {
    Context mContext;

    public MySpinnerAdapter(Context context, List<String> data, int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = super.getView(position, convertView, parent);

        TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
            tv.setTextColor(ContextCompat.getColor(mContext, R.color.transparent));
        return convertView;
    }
}

and after selecting in spinner, just get selected text and set it to EditText and it will have the same effect with animation
yourSpinnerView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<String> adapterView, View view, int i, long l) {
            //get your selected text from adapter or from where you want
            String selectedText = adapterView.getItemAtPosition(i));

            if (i != 0) {
                edt.setText(selectedText);
            } else {
                // if in case your spinner have first empty text,
                // then when spinner selected, just empty EditText.
                edt.setText("");
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

if you have any question Ask me

A: I have created a compound View component which displays a label above the Spinner. The text for the label can be set using XML or in Java.
The component has the key features of a Spinner (not all of them) as well as looking similar to the TextInputLayout component.
I have named it a LabelledSpinner, and it is available as part of my UsefulViews Android library on GitHub under the Apache 2.0 License.
To use it, add the library dependency in your build.gradle file:
compile 'com.satsuware.lib:usefulviews:+'

Examples of its usage are available at the GitHub repository (both a sample app, and a usage guide).

A: You can achieve this :

With new Material library styles like this:
<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/fullNameLay"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <androidx.appcompat.widget.AppCompatAutoCompleteTextView
            android:id="@+id/fullNameEt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>

for more information:
https://material.io/develop/android/components/menu/
UPDATE:
Non editable variation:
Disable the user input in the *AutoCompleteTextView* to have a non editable variation of the menu by setting android:inputType="none" on the AutoCompleteTextView.

A: Here is a library that I use for the Floating label spinner
rey5137 Material Library
Also, for future reference, here is a list of some great libraries.
UI Libraries
Core Libraries

A: SpinnerCustom.java
package com.pozitron.tfkb.customviews;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.pozitron.commons.customviews.TextViewFont;
import com.pozitron.tfkb.R;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by so12607 on 31/01/2018.
 */

public class SpinnerCustom extends LinearLayout {

    @BindView(R.id.layoutSpinnerCustomLabel)
    TextViewFont layoutSpinnerCustomLabel;

    @BindView(R.id.layoutSpinnerCustomSpinner)
    TextViewFont layoutSpinnerCustomSpinner;

    @BindView(R.id.layoutSpinner)
    LinearLayout layoutSpinner;

    private View v;

    public SpinnerCustom(Context context) {
        this(context, null);
    }

    public SpinnerCustom(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public SpinnerCustom(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        v = LayoutInflater.from(context).inflate(R.layout.layout_spinner_custom, this, true);
        ButterKnife.bind(this);

        if (!isInEditMode()) {

            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SpinnerCustom, 0, 0);
            final String label = array.getString(R.styleable.SpinnerCustom_label);
            final boolean enable = array.getBoolean(R.styleable.SpinnerCustom_enabled, true);
            layoutSpinnerCustomLabel.setText(label);

            layoutSpinnerCustomLabel.setEnabled(enable);
            layoutSpinnerCustomSpinner.setEnabled(enable);
            layoutSpinner.setEnabled(enable);
            layoutSpinner.setClickable(enable);
            v.setEnabled(enable);
            v.setClickable(enable);
            array.recycle();
        }
    }

    public void setText(String text) {
        layoutSpinnerCustomSpinner.setText(text);
    }

    public void setText(SpannableString text) {
        layoutSpinnerCustomSpinner.setText(text);
    }

    public void setText(CharSequence text) {
        layoutSpinnerCustomSpinner.setText(text);
    }

    public void setLabel(String text) {
        layoutSpinnerCustomLabel.setText(text);
    }

    public void setError(SpannableString text) {
        layoutSpinnerCustomSpinner.setError(text);
    }

    public void setEnabled(boolean enable) {
        layoutSpinnerCustomLabel.setEnabled(enable);
        layoutSpinnerCustomSpinner.setEnabled(enable);
        layoutSpinner.setEnabled(!enable);
        layoutSpinner.setClickable(!enable);
    }
}

layout_spinner_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layoutSpinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.pozitron.commons.customviews.TextViewFont
        android:id="@+id/layoutSpinnerCustomLabel"
        style="@style/TextLabel"
        tools:text="label" />

    <com.pozitron.commons.customviews.TextViewFont
        android:id="@+id/layoutSpinnerCustomSpinner"
        style="@style/SpinnerText"
        android:clickable="false" />

</LinearLayout>

style.xml
<style name="TextLabel" parent="android:Widget.TextView">
    <item name="font">@integer/font_GTEestiDisplay_Regular</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:textSize">14sp</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:gravity">bottom</item>
    <item name="android:textColor">@color/greyLabel</item>
</style>

<style name="SpinnerText" parent="EditText">
    <item name="font">@integer/font_GTEestiDisplay_Medium</item>
    <item name="android:gravity">bottom</item>
    <item name="android:textSize">17sp</item>
    <item name="android:minHeight">35dp</item>
    <item name="android:focusable">false</item>
    <item name="android:background">@drawable/spinner_selector</item>
    <item name="android:text">@string/select</item>
    <item name="android:textColor">@color/selector_spinner_text</item>
</style>


text:
Q: C++ lock-free thread synchronization I have following code:
bool sync=false;
int* ptr=NULL;
std::thread t([&](){
    do_a(); // long-time operation
    while(!sync){
        std::atomic_thread_fence(std::memory_order_acquire);
    }
    do_b(ptr);
});
int val=do_c();  //long-time operation
ptr=&val;
sync=true;
std::atomic_thread_fence(std::memory_order_release);
....

But whet I start this on multiprocessor computer, it sometimes happen, that do_b() is started with null pointer. Indon't uneerstand well this behaviour. Does compiler do some optimalizations? Or do I use fences wrong? Does these fences ensure synchronization of data between threads?
Thank you for your tihe and help.

A: Your program tries to write the two memory locations (ptr, sync) in that order; but you haven't told your compiler and or cpu that this is necessary.   Your compiler is free to re-arrange the order of memory writes to suit its goals (winning meaningless benchmarks).   Your cpu is free to re-arrange memory writes to suit its goals (reduced bus contention, meaningless benchmarks).
So, first you should tell your compiler that it is important that it implement the order you desire.   You can accomplish this with the std::atomic, or possibly volatile directives(*).
Secondly, you need to tell your cpu that you are depending upon the visible ordering of these stores.   In a single cpu, the program order (above) and visible order are the same.  In multiple cpus, they not only aren't necessarily the same, but can vary with current and past system activity.  Thus @DanielLangr's comment about the fence location.  The fence informs the cpu that all stores preceding the fence must be visible before any stores following the fence.
(*) Benchmark-focussed compiler writers have managed to reduce volatile to near meaninglessness, demonstrating the contempt compiler writers hold for their actual customers.  Oddly, the 'write those bits in machine language' has proved to be more maintainable than relying on the artifacts of 'de jour' standards writers.   The advent of 'smart linkers' may finally neuter systems programming languages in a way that 30 years of standards committees failed to.


text:
Q: Como organizar um Array por ordem de Hora? Tenho duas listas com formato de TimeSpan e outra com formato de String. Preciso organizar essas duas listas para crescente e decrescente.
        List<string> horaString = new List<string>()
        {
          "01:04:00",
          "04:04:00",
          "02:02:10",
          "03:05:00",
          "10:07:00",
          "22:20:00"
        };

        List<TimeSpan> horaTimespan = new List<TimeSpan>()
        {
          new TimeSpan(5, 30, 1),
          new TimeSpan(2, 15, 5),
          new TimeSpan(7, 32, 1),
          new TimeSpan(8, 15, 5),
          new TimeSpan(1, 23, 1),
          new TimeSpan(3, 15, 5)
        };

A: Você pode usar o método OrderBy e OrderByDescending.
        List<string> horaString = new List<string>()
        {
          "01:04:00",
          "04:04:00",
          "02:02:10",
          "03:05:00",
          "10:07:00",
          "22:20:00"
        };

        List<TimeSpan> horaTimespan = new List<TimeSpan>()
        {
          new TimeSpan(5, 30, 1),
          new TimeSpan(2, 15, 5),
          new TimeSpan(7, 32, 1),
          new TimeSpan(8, 15, 5),
          new TimeSpan(1, 23, 1),
          new TimeSpan(3, 15, 5)
        };

        horaString = horaString.OrderBy(p => p).ToList();
        horaTimespan = horaTimespan.OrderBy(p => p.Hours).ToList();

        Console.WriteLine("String crescente");
        horaString.ForEach(p => Console.WriteLine(p));

        Console.WriteLine("Time Span crescente");
        horaTimespan.ForEach(p => Console.WriteLine(p));

        horaString = horaString.OrderByDescending(p => p).ToList();
        horaTimespan = horaTimespan.OrderByDescending(p => p.Hours).ToList();

        Console.WriteLine("String decrescente");
        horaString.ForEach(p => Console.WriteLine(p));

        Console.WriteLine("Time Span decrescente");
        horaTimespan.ForEach(p => Console.WriteLine(p));

Veja funcionando no .Net Fiddle

A: Procure por Split String em C# (para dividir a string em array de string, separando por ":"(dois-pontos)), depois transforme as 3 string em um único valor inteiro (criando uma lista de inteiros)
hora = array[0];
minuto = array[1];
segundos = array[2];
valor = hora*3600 + minuto*60 + segundos

, e ordene por ele usando o exemplo
https://stackoverflow.com/questions/3738639/sorting-a-listint.
Depois retorne o inteiro para o valor original
hora = valor/3600;
valor -= hora*3600;
minuto = valor/60;
valor -= minuto*60;
segundos = valor;


text:
Q: Trying to create React component with textarea that auto expands and shrinks based on content height (with Sandbox) I'm trying to build this TextArea component that uses React hook and styled-components.
Everything goes well when my textarea is gaining new lines. The expand feature is working as expected.
What I'm doing, basically, is:

*

*Using textAreaRef- useRef() to store a ref to the textarea element

*Using lastScrollHeight- useRef() to store the last ScrollHeight

*Using idealHeight- useRef() to store the ideal height for the textarea
I calculate the idealHeight based on the value of the lastScrollHeight that has been stored on the previous render. Then I compare with the current value of textAreaRef.current.scrollHeight and I calculate the delta.
Then I calculate the idealHeight.current = idealHeight.current + delta and send it as props to my styled-component TextAreaInput to set the height.
THE PROBLEM
scrollHeight increases when new lines are added and returns a positive delta. But scrollHeight doesn't decrease when lines are removed. So delta comes back zero.
I need a way to measure the height of the text content inside of the textarea. I saw some questions here on SO that recommended to do this by setting height of the element to a very small value before asking for the scrollHeight.
Indeed, that gives me the negative deltas that I want, but that just stops any expanding or shrinking, and I get a scroll bar instead. See that by toggling the commented line textAreaRef.current.style.height = "2px";. Some how the component gets stuck on height='2px'. I don't know.
Code SandBox with working example (mind the console logs)
Any ideas what's going wrong?
TextArea.js
import React, { useRef } from "react";
import styled from "styled-components";

const TextAreaInput = styled.textarea`
  height: ${props => props.idealHeight || "152px"};
  min-height: 32px;
  max-height: 320px;
  line-height: 21px;
  width: 100%;
  resize: vertical;
  box-sizing: border-box;

  border: 1px solid rgb(217, 217, 217);
  padding: 4px 11px;
  text-size-adjust: 100%;
`;

function TextArea(props) {
  const idealHeight = useRef(32);
  const lastScrollHeight = useRef(30);
  const textAreaRef = useRef(null);

  console.log("ANOTHER RENDER...");

  if (textAreaRef.current !== null && textAreaRef.current !== undefined) {
    const scrollHeight = textAreaRef.current.scrollHeight;

    // THIS NEXT LINE MAKES THE DELTA CALCULATION CORRECT ON 'SHRINKING'
    // BUT STOPS THE RESIZING

    // textAreaRef.current.style.height = "2px";

    const delta = scrollHeight - lastScrollHeight.current;
    console.log("Delta is: " + delta);

    console.log("Last ScrollHeight: " + lastScrollHeight.current);
    lastScrollHeight.current = scrollHeight;

    console.log("Current ScrollHeight: " + lastScrollHeight.current);

    idealHeight.current = idealHeight.current + delta;

    console.log("IdealHeight :" + idealHeight.current);
  }

  return (
    <TextAreaInput
      placeholder={props.placeholder}
      value={props.value}
      onChange={e => props.setValue(e.target.value)}
      ref={textAreaRef}
      idealHeight={idealHeight.current + "px"}
    />
  );
}

export default TextArea;

A: Just came up with a solution:
In order to get the content height inside the textarea, first we need to set its height property to 0px and then get its scrollHeight.
But when you do this, you end up creating an inline style with height=0px, and that gets the highest precedence of CSS rules, so you need to unset it with:
textAreaRef.current.removeAttribute('style');
That is needed because all my CSS is being applied by styled-components, that uses the <style> html tag inside <head>, which has lower precedence than inline CSS.
So the final and working code is:
TextArea.js
function TextArea(props) {

  const idealHeight = useRef(32);
  const lastScrollHeight = useRef(30);
  const textAreaRef = useRef(null);

  if (textAreaRef.current != null && textAreaRef.current != undefined) {

    textAreaRef.current.style.height = '0px'; // This creates an inline style

    let scrollHeight = textAreaRef.current.scrollHeight;

    const style = window.getComputedStyle(textAreaRef.current);

    textAreaRef.current.removeAttribute('style'); // The inline style must be removed

    let delta = scrollHeight-lastScrollHeight.current;

    lastScrollHeight.current = scrollHeight;

    idealHeight.current = idealHeight.current + delta;

  }

  return(
    <TextAreaInput
      placeholder={props.placeholder}
      value={props.value}
      onChange={props.onChange}
      ref={textAreaRef}
      idealHeight={idealHeight.current + 'px'}
    />
  );

}


text:
Q: Getting nullpoint error when I try to insert values public boolean addInfo(String username, String DOB, String gender, String password) {

            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues contentValues = new ContentValues();

            contentValues.put(UserProfile.Users.col_02, username);
            contentValues.put(UserProfile.Users.col_03, DOB);
            contentValues.put(UserProfile.Users.col_04, gender);
            contentValues.put(UserProfile.Users.col_05, password);

            long res = db.insert(UserProfile.Users.Table_Name, null, contentValues);

            if (res == -1) {
                return false;
            } else {
                return true;
            }

        }

public boolean updateInfo(String id, String username, String DOB, String gender, String password) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put(UserProfile.Users.col_01, id);
        contentValues.put(UserProfile.Users.col_02, username);
        contentValues.put(UserProfile.Users.col_03, DOB);
        contentValues.put(UserProfile.Users.col_04, gender);
        contentValues.put(UserProfile.Users.col_05, password);

db.update(UserProfile.Users.Table_Name, contentValues, "ID = ?", new String[]{id});

        return true;

    }

    public Cursor readAllInfo(String id) {

        SQLiteDatabase db = this.getReadableDatabase();

        String[] projection = {
                UserProfile.Users.col_01,
                UserProfile.Users.col_02,
                UserProfile.Users.col_03,
                UserProfile.Users.col_04,
                UserProfile.Users.col_05
        };

        String selection = UserProfile.Users.col_01 + "=?";

        Cursor cursor = db.query(UserProfile.Users.Table_Name,
                projection,
                selection,
                new String[]{id},
                null,
                null,
                null);

        return cursor;

    }
  public Integer deleteInfo(String id) {
        SQLiteDatabase db = this.getWritableDatabase();

  return db.delete(UserProfile.Users.Table_Name, "ID = ?", new String[]{id});

    }

These are my methods which I think nothing is wrong with the code, but still every time I call the addInfo method in my add button it says "null point exception trying to invoke virtual method"

A: The likely cause is that you are declaring but not instantiating the Database Helper object i.e. the this.
The methods are likely part of a class that extends SQliteOpenHelper and this will have a constructor, assuming the class is DBHelper then in the activity that invokes these methods
you would have something like
DBHelper myDatabaseHelper;

*

*Note that without the code that invokes (calls) the method then the actual names could be anything. The stack-trace, see Debug your app - View the system log, also provides information that should be copied into such questions as it pinpoints where the exception happened.

before invoking the methods you need to instantiate (construct) myDatabaseHelper which would be something like :-
    myDatabaseHelper = new DBhelper(this); //<<<<<<<<<< You are likely missing this and hence myDatabaseHelper is null.

You could then use
     if (myDatabaseHelper.addInfo("TheUserName","2000-01-01","Female","thepassword"))
         ...... code to run if the info was added
     { else {
         ... code to run if the user was not added
     }

As myDatabaseHelper is null the exception is raised when an attempt is made to access it (addInfo, if it were instantiated/constructed would be part of myDatabaseHelper)
Consider the following Example :-
Your DatabaseHelper (as will be used unchanged for both example runs) :-
public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;

    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE If NOT EXISTS " + UserProfile.Users.Table_Name +
                "(" +
                        UserProfile.Users.col_01 + " INTEGER PRIMARY KEY," +
                        UserProfile.Users.col_02 + " TEXT, " +
                        UserProfile.Users.col_03 + " TEXT," +
                        UserProfile.Users.col_04 + " TEXT," +
                        UserProfile.Users.col_05 + " TEXT" +
                ")"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public boolean addInfo(String username, String DOB, String gender, String password) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(UserProfile.Users.col_02, username);
        contentValues.put(UserProfile.Users.col_03, DOB);
        contentValues.put(UserProfile.Users.col_04, gender);
        contentValues.put(UserProfile.Users.col_05, password);
        long res = db.insert(UserProfile.Users.Table_Name, null, contentValues);
        if (res == -1) {
            return false;
        } else {
            return true;
        }
    }

    public boolean updateInfo(String id, String username, String DOB, String gender, String password) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(UserProfile.Users.col_01, id);
        contentValues.put(UserProfile.Users.col_02, username);
        contentValues.put(UserProfile.Users.col_03, DOB);
        contentValues.put(UserProfile.Users.col_04, gender);
        contentValues.put(UserProfile.Users.col_05, password);
        db.update(UserProfile.Users.Table_Name, contentValues, "ID = ?", new String[]{id});
        return true;
    }

    public Cursor readAllInfo(String id) {

        SQLiteDatabase db = this.getReadableDatabase();
        String[] projection = {
                UserProfile.Users.col_01,
                UserProfile.Users.col_02,
                UserProfile.Users.col_03,
                UserProfile.Users.col_04,
                UserProfile.Users.col_05
        };

        String selection = UserProfile.Users.col_01 + "=?";

        Cursor cursor = db.query(UserProfile.Users.Table_Name,
                projection,
                selection,
                new String[]{id},
                null,
                null,
                null);
        return cursor;

    }
    public Integer deleteInfo(String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(UserProfile.Users.Table_Name, "ID = ?", new String[]{id});
    }
}

*

*Notice that your code is embedded as is within the above.

And consider the invoking activity (WITHOUT instantiating myDatabasehelper) :-
public class MainActivity extends AppCompatActivity {

    DBHelper myDatabaseHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //myDatabaseHelper = new DBHelper(this); //<<<<<<<<<<
        myDatabaseHelper.addInfo("UserX","2000-01-01","Unknown","password");
        Cursor csr = myDatabaseHelper.readAllInfo("1");
        DatabaseUtils.dumpCursor(csr);
    }
}

The you get the Null Pointer Exception (NPE) as per :-
2019-06-06 15:34:46.235 5658-5658/aso.so5647108356471083 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: aso.so5647108356471083, PID: 5658
    java.lang.RuntimeException: Unable to start activity ComponentInfo{aso.so5647108356471083/aso.so5647108356471083.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean aso.so5647108356471083.DBHelper.addInfo(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean aso.so5647108356471083.DBHelper.addInfo(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
        at aso.so5647108356471083.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

The following line being the pertintent line that explains that the variable that has been declared as being a DBhelper is null.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean aso.so5647108356471083.DBHelper.addInfo(java.lang.String,java.lang.String, java.lang.String, java.lang.String)' on a null object reference
A simple change (uncommenting the line myDatabaseHelper = new DBHelper(this);) and using :-
public class MainActivity extends AppCompatActivity {

    DBHelper myDatabaseHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDatabaseHelper = new DBHelper(this); //<<<<<<<<<<
        myDatabaseHelper.addInfo("UserX","2000-01-01","Unknown","password");
        Cursor csr = myDatabaseHelper.readAllInfo("1");
        DatabaseUtils.dumpCursor(csr);
    }
}

works, extracting the added data and writing it to the log as per :-
2019-06-06 15:47:22.579 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@791f7af
2019-06-06 15:47:22.580 I/System.out: 0 {
2019-06-06 15:47:22.580 I/System.out:    _id=1
2019-06-06 15:47:22.580 I/System.out:    col02=UserX
2019-06-06 15:47:22.580 I/System.out:    col03=2000-01-01
2019-06-06 15:47:22.580 I/System.out:    col04=Unknown
2019-06-06 15:47:22.580 I/System.out:    col05=password
2019-06-06 15:47:22.580 I/System.out: }
2019-06-06 15:47:22.580 I/System.out: <<<<<

A: Try below code, here myDatabaseHelper is object of your that class where you create tables.
myDatabaseHelper.getWritableDatabase().insert(UserProfile.Users.Table_Name, null, contentValues);


text:
Q: Update Command Mysteriously not working in ASP.NET I have an ASP.NET application in which I'll be updating some notes, however the command won't update the database notes. It did it once and then decided not to do it anymore. No changes were made between in not working, working once and then not working again. Very odd situation... here's the code. I can't find anything wrong with it.
protected void saveNotes_Click(object sender, EventArgs e)
{
     string theNotes = notes.InnerText;
     string[] vars = { "@notes", "@jobNumber" };
     string[] vals = { theNotes, jobNumber };
     HelperMethods.OleDB_Query("UPDATE [Jobs] SET Notes = @notes WHERE Job_Number = @jobNumber", vars, vals);

     test.InnerText = theNotes;
}

I display the notes in the aspx page to verify that they do indeed populate and they do.
Here's the database access code:
public static void OleDB_Query(string cmd, string[] vars = null, string[] vals = null)
{
    OleDbConnection Connection = new OleDbConnection(connectionString);
    OleDbCommand Command = new OleDbCommand(cmd, Connection);
    if (vars != null) {
        for (int k = 0; k < vars.Length; k++)
            Command.Parameters.AddWithValue(vars[k], vals[k]);
        Command.Connection.Open();
        Command.ExecuteNonQuery();
        Command.Connection.Close();
    }
}

I'm attempting to display the job number and notes on each update attempt.
I'm getting the job number via URL query string. If the job number starts with a zero, then the zeros are all parsed off and and what's displayed is the notes text followed by the parsed job number. If the job number doesn't start with a zero, only the job number is displayed. Makes no sense whatsoever. It's a very basic setup that I've done many times in the past. It's just deciding not to work anymore for some odd reason.

A: I would guess it's related to not disposing of the connection and commands properly. Update your static helper method to use using statements and it should ensure your connections and commands are being cleaned up and ready for the next use.
public static void OleDB_Query(string cmd, string[] vars = null, string[] vals = null)
{
    using(OleDbConnection Connection = new OleDbConnection(connectionString))
    {
        Command.Connection.Open();
        using(OleDbCommand Command = new OleDbCommand(cmd, Connection))
        {
            if (vars != null) {
                for (int k = 0; k < vars.Length; k++)
                    Command.Parameters.AddWithValue(vars[k], vals[k]);

                Command.ExecuteNonQuery();
        }
        Command.Connection.Close();
    }
}

A: Could this have to do with the fact that you are passing your Job_Number as a string? What is the underlying sql datatype? If it is a char or varchar, stripping off the leading zeros will produce a different Job_Number.
Consider parsing your QueryString value to an int before passing it to SQL which will strip all leading zeros.

A: TWO PROBLEMS (ONE SOLVED, ONE SORT OF SOLVED):
SOLVED:
The data wasn't being inputted into the database because the jobNumber variable was being reset on each page load. I tried stopping in by using (!IsPostBack) but then the variable had no value. Since it seemed to be losing its value somehow I just stuck it in ViewState and I was able to successfully update the database.
UNSOLVED (BUT WORK AROUND FOUND) PROBLEM:
When I pass a job number without leading zeros, everything works just fine and dandy. However, when I pass a job number with leading zeros, the query string parses it and I'm left with a job number that is incorrect. I tested the variable just before passing it across the url and just after. It's being parsed in the url. Anyone know anything about this? I'm thinking I'll just pass an extra variable which represents the number of leading zeros so I can stick 'em back on.


text: Q: React Native: Stack Navigator Header vs Custom Header So like title says is there any point to turn off default navigator header and create custom component? Will it be like better solution, maybe better for performance or there is any other reason? Maybe there is some comparing list or any issues with default one?


text:
Q: How to show icons during drag and drop I am working on some NetBeans platform app, and i am currently stuck on some detail in Visual Library. Ok, here is problem. I have Visual Editor for my app, with pallet, scene and everything works great, just there is a problem when i am dragging icons from pallet to scene. They are not displayed during drag event, i would like to create that effect, can someone help on this?

A: I do this in two phases:
1) Create a screenshot (an image) of a palette element. I create the screenshot lazily and then cache it within the view. To create the screenshot, you can use this snippet:
screenshot = new BufferedImage(getWidth(), getHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);// buffered image
// creating the graphics for buffered image
Graphics2D graphics = screenshot.createGraphics();
// We make the screenshot slightly transparent
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
view.print(graphics); // takes the screenshot
graphics.dispose();

2) Paint the screenshot on the receiving view. When the drag gesture is recognized, find a way to make the screenshot available to the receiving view or one of its ancestor (you could make it available on the frame or its content pane, depending on where you want to make the screenshot drag available) and paint the image within the paint method. Something like this:
a. Make the screenshot available:
capturedDraggedNodeImage = view.getScreenshot(); // Transfer the screenshot
dragOrigin = SwingUtilities.convertPoint(e.getComponent(), e.getDragOrigin(), view); // locate the point where the click was made

b. As the mouse is dragged, update the location of the screenshot
// Assuming 'e' is a DropTargetDragEvent and 'this' is where you want to paint
// Convert the event point to this component coordinates
capturedNodeLocation = SwingUtilities.convertPoint(((DropTarget) e.getSource()).getComponent(), e.getLocation(), this);
// offset the location by the original point of drag on the palette element view
capturedNodeLocation.x -= dragOrigin.x;
capturedNodeLocation.y -= dragOrigin.y;
// Invoke repaint
repaint(capturedNodeLocation.x, capturedNodeLocation.y,
   capturedDraggedNodeImage.getWidth(), capturedDraggedNodeImage.getHeight());

c. paint the screenshot in paint method:
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.drawImage(capturedDraggedNodeImage, capturedNodeLocation.x,
        capturedNodeLocation.y, capturedDraggedNodeImage.getWidth(),
        capturedDraggedNodeImage.getHeight(), this);
}

Instead of calling repaint() and perform the painting in the paint() method, you could invoke paintImmediately() as the mouse moves but the rendering will be a lot poorer and you could observe some flickering, so I would not recommend that option. Using paint() and repaint() provides a better user experience and a smooth rendering.

A: If I hear you well, you are creating a graphical editor of some sort, with drag and drop of elements, and you want to create an effect during that drag and drop?
If so, you basically need to create a ghost of the object you're dragging and attach it to the move of the mouse. Easier said than done, of course, but you get the gist.
So what you need is to take the image of what you're dragging (it shouldn't be too much trouble) and move it according to the position of the mouse (think of substracting the relative position of the mouse cursor in the object you're dragging).
But I think that kind of code is available somewhere. I'd advise you to look that up :
http://free-the-pixel.blogspot.fr/2010/04/ghost-drag-and-drop-over-multiple.html
http://codeidol.com/java/swing/Drag-and-Drop/Translucent-Drag-and-Drop/
Hope that helps you!


text:
Q: Голосовой чат Добрый день. Подскажите пожалуйста, как на c++ написать голосовой чат. Кто знает статьи или книги на данную тему. Заранее благодарен
A: XMPP Вам в помощь. Есть либа для Qt.
A: libjingle - библиотека - расширение для XMPP, на основе которой сделан Google Talk. Почти не документирована, но есть пара примеров использования. Плюс есть документация по самому Google Talk.


text:
Q: MMDrawerViewController set up I'm trying to set up a pod called MMDrawerViewController which creates a sliding drawer. I have a navigation controller that has a few table view controllers in it's stack. I inserted this in the NavigationViewController.m file:
- (void)viewDidLoad
{
    [super viewDidLoad];

    //Initializing the MMDrawerController views
    UIViewController * leftDrawer = [[UIViewController alloc] init];
    UIViewController* centerViewController = [[UIViewController alloc] init];

    MMDrawerController * drawerController = [[MMDrawerController alloc] initWithCenterViewController:centerViewController leftDrawerViewController:leftDrawer];
}

However when I put this in I get the following error:

Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_MMDrawerController", referenced from:
        objc-class-ref in NavigationViewController.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with
  exit code 1 (use -v to see invocation)

Is there something different I should be doing?

A: I'm posting this as an answer so that this question is no longer unanswered.
You are experiencing this problem because your project is not compiling the MMDrawerController.m file which you use in NavigationViewController.m. Also, make sure that you are importing MMDrawerController.h into NavigationViewController.m.


text:
Q: What is the Graph Function of a Skewed Normal Distribution Curve? I am looking for functions that, when plugged into a graphing calculator, draw the line of a normal distribution curve that is skewed to the right. I already have a function for a standard normal distribution curve, and I think what I need is either a new function and/or one or more functions manipulating variables within the main graph function in order to graph a skewed normal distribution curve.
Here is a function that draws a standard normal distribution curve:
$$f\left(x\right)=\frac{e^{\left(-\frac{1}{2}\cdot\left(\frac{\left(x-μ\right)}{σ}\right)^{2}\right)}}{σ\cdot\sqrt{2\pi}}$$
Where

*

*"σ" is the standard deviation of your data

*"μ" is the average of your data

*"e" is Eulers' constant

I use this function to draw the normal distribution curve in this Desmos graph.
I need a function like this (and/or functions manipulating variables within the main function) that can graph a skewed normal distribution curve.
UPDATE: Thanks to Gerry Mason, I was able to get a working skewed normal distribution formula! The FULL formula for a skewed normal distribution curve is this massive equation:(you may need to zoom-in to see some of the variables!):
$$f\left(x\right)=\frac{2e^{\left(\frac{-\left(\left(\frac{x-ξ}{\omega}\right)-μ\right)^{2}}{2σ^{2}}\right)}\cdot\left(1+\frac{2}{\sqrt{\pi}}\int_{0}^{\left(\frac{α\left(x-ξ\right)}{\omega\sqrt{2}}\right)}e^{-t^{2}}dt\right)}{2\omegaσ\sqrt{2\pi}}$$
Where

*

*"σ" is the standard deviation of your data

*"μ" is the average of your data

*"e" is Eulers' constant

*"ξ" is the "location parameter (real)

*"ω" is the "scale" parameter (positive, real)

*"α" is the "shape" parameter

See the Wikipedia page on Skew Normal Distribution for more information
Here is a link to the updated Desmos graph with all the necessary functions: https://www.desmos.com/calculator/k5y9glwjee

A: Wikipedia sez,
Let $\phi(x)$ denote the standard normal probability density function $$\phi(x)={1\over\sqrt{2\pi}}e^{-x^2/2}$$ with cumulative distribution function $$\Phi(x)={1\over2}\left[1+{\rm erf}\left({x\over\sqrt2}\right)\right],$$ where "erf" is the error function. Then the probability density function of the skew-normal distribution with parameter $\alpha$ is given by $$f(x)=2\phi(x)\Phi(\alpha x).$$


text:
Q: SearchBox which i have used in fragment class is not responding with the Cardview The Seaarch Box is not responding with the Cardview,which has the names,ex-Employee Name,i need to search by names which are in cardview.
I need to work it as similarly as contact search.The Name we type on Search Box that Cardview Come Up.
Below is the Code.
 for (int i = 0; i < enggFragModels.size() - 1; i++) {
      searchName = enggFragModels.get(i).getEmployeeName();
      Log.i("EnggVIew", "enggViewMInterface: " + searchName);
      enggFragModels.get(i).getEmployeeName()
    };

    strings = new ArrayList<>();
    strings.add(searchName);
    arr[i] = searchName;}

    for (int j = 0; j < arr.length; j++) {
        Log.i("for loop", " arr: " + arr[j]);
    }

    adapter2 = new ArrayAdapter<String>(getActivity(),R.layout.frame_engineer,R.id.name_engineer, arr);

    Log.i("adapter2", "enggViewMInterface: "+arr);

    mListview.setAdapter(adapter2);
    Log.i("mlistView", "enggViewMInterface: "+arr);

    mSearch.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence charSequence,
            int i, int i1, int i2) {
                Log.i("inside overrideloop", "beforeTextChanged: "+arr);
                adapter2.getFilter().filter(charSequence);
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i,       int i1, int i2) {
                Log.i("inside 2nd overrideloop", "beforeTextChanged"+arr);
                adapter2.getFilter().filter(charSequence);
                adapter2.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


text:
Q: Cucumber/Capybara - Using RSpec matchers with a "Page Object" pattern I'm currently refactoring a whole load of cucumber tests to use a "Page Object" pattern, but I'm having a lot of problems using the RSpec matchers.
The existing step I have is as follows:
Then /^I should (not )?see the following alerts:$/ do |negate, alerts|
  expectation = negate ? :should_not : :should

  within(ALERT_TABLE_ID) do
    alerts.hashes.each do |alert|
      page.send(expectation, have_content(alert["Original ID"]))
    end
  end
end

My refactored step is:
Then /^I should (not )?see the following alerts:$/ do |negate, alerts|
  expectation = negate ? :should_not : :should

  @alert_reporting_panel = AlertReportingPanel.new(Capybara.current_session)
  @alert_reporting_panel.verify_contents expectation, alerts
end

And my Panel Object is:
class AlertReportingPanel
  def initialize(session)
    @session = session
  end

  def verify_contents(expectation, alerts)
    @session.within(ALERT_TABLE_ID) do
      alerts.hashes.each do |alert|
        @session.send(expectation, have_content(alert["Original ID"]))
      end
    end
  end
end

Unfortunately, I get undefined method 'have_contents' for #<AlertReportingPanel:0x3f0faf8> (NoMethodError).
I have tried adding require 'rspec' to the top of the class and also tried fully qualifying the have-content method thus:  Capybara::RSpecMatchers::HaveMatcher.have_content,  but I just get uninitialized constant Capybara::RSpecMatchers (NameError).
I'm pretty new to Ruby and I'm sure this is trivial to fix... but I just can't seem to work it out for myself.
Please help.   Thankyou.

A: This was a while back so I'm guessing you may have your answer by now but here goes.
You need to include the necessary modules in order bring in and have access to the likes of *have_content*. So your Panel Object would look like:
class AlertReportingPanel
    include Capybara::DSL
    include Capybara::Node::Matchers
    include RSpec::Matchers

    def initialize... etc

A: Instead of writing your own Page Object system you could try using SitePrism
I'm a little biased (I wrote that gem) but it might make life easier for you.


text:
Q: why does openMP needs so long? I just spent quite some time trying to get this loop openMPed, but for 2 threads, it doubles Wall time! Am I missing something important?
The overall task is to read in a big file (~ 1GB) in parallel, an ifstream is divided into several stringbuffer and these are used to insert the data into the structs Symbol. Up to here everything is fast. Also giving the loop private variables str and locVec to operate on doesn't change something.
vector<string> strbuf; // filled from ifstream
vector< vector <Symbol> > symVec; // to be filled

#pragma omp parallel for num_threads(2) default(none) shared(strbuf, symVec)
for (int i=0; i<2; i++)
{
    string str = strbuf[i];
    std::stringstream ss(str);
    // no problem until here

    // this is where it slows down:
    vector<Symbol> locVec;
    std::copy(std::istream_iterator<Symbol>(ss), std::istream_iterator<Symbol>(), std::back_inserter(locVec));

    symVec[i] = locVec;
}

EDIT::
Sorry for being unprecise, but the file content is already read in sequencially and divided into the strbufs at this point. The file is closed. Within the loop there is no file access.

A: It's much better to do sequential I/O on a file rather than I/O at different sections of a file. This essentially boils down to causing a lot of seeks on the underlying device (I'm assuming a disk here). This also increases the amount of underlying system calls required to read the file into said buffers. You're better off using 1 thread to read the file in it's totality sequentially (maybe mmap() with MAP_POPULATE) and assigning processing to different threads.
Another option is to use calls such as aio_read() to handle reading in different sections if for some reason you really do not want to read the file all at once.
Without all the code I cannot be completely sure but remember that simply opening a file does not guarantee it's content to be in memory and reading from a file will cause page faults that will then cause the actual file contents to be read so even if you're not explicitly trying to read from the file using a read/write the OS will take care of that for you.


text:
Q: ion-item cuts off an absolute positioned element ion-item cuts off an image that i have absolutely positioned. putting ion-item overflow on auto has brought nothing...
Example

Code
<ion-item-sliding class="itemBooksContainer" #slidingBooks>
        <ion-item item-wrap class="itemBooks">
          <ion-icon ios="ios-paper" md="md-paper" item-start></ion-icon>
          {{ "STATISTICS.books" | translate }}
          {{ currentMonthDataBooks }}

        </ion-item>
        <ion-item-options side="left">
          <button ion-button color="danger" icon-only (click)="substractBooks()"><ion-icon ios="ios-remove" md="md-remove"></ion-icon></button>
          <button ion-button color="light">{{ currentMonthDataBooks }}</button>
        </ion-item-options>
        <ion-item-options side="right">
          <button ion-button icon-only (click)="addBooks()"><ion-icon ios="ios-add" md="md-add"></ion-icon></button>
        </ion-item-options>
      </ion-item-sliding>

The hand should be completely visible..... :-) What´s the problem?

A: The solution was set contain: unset; on ion-item! Not it works :)

A: In my case, it was position: flex; that I had to change to position: absolute;


text:
Q: Printing PDF-files via network extremely slow I encounter grave problems trying to print PDF-files, no matter whether I use Evince, Okular or any other linux program. The Documents are printed extremely slowly or even completely fail to print at all. I have tried printing from various Ubuntu-Installations on different network-printers (canon and lexmark), with the same result. On the other hand the same files are printed swiftly through Windows, which is a pity, since I do not want to use Windows.
Are there any solutions?
Thanks in advance!

A: Just for people to who it would also happen: I had the same problem, and in my case the solution was also to change the driver: more precisely change my footmatic/pxl color driver to the footmatic/postscript equivalent.
My printer was a Sharp MX-2300N, and the "Generic PCL5e printer" only enabled to print in grey scale, so I really had to stay on the manufacturer drivers.
Well, actually I have no idea why it worked, I just did it because an other printer on the network had also a postscript driver and was working perfectly well...
What's actually the difference between postscript and pxl drivers?

A: Here are a few suggestions to try:

*

*use xpdf: i.e. xpdf <document name> should automatically direct to your default printer

*if its a laser printer try adding a printer with using "Generic" as the manufacturer, and "Generic PCL5e printer" as the model i.e. most lasers support PCL.

*When printing - print to a file - give it a name and print to a .ps file.  Then open up the .ps file.  It should reopen in evince.  This time print it again to your printer.

source


text:
Q: Run standalone web app in Google Chrome without borders or toolbars I need to run a web-based app inside Chrome but it must appear as if the app is standalone. I dont want any tools or frames to be visible.
Yes I know I can press F11 but this isnt sufficient as I dont want the tools to appear when I move the mouse to the top of the screen.
Do I need to go to the extents of making a Chrome extension and utilizing a possible fullscreen feature?

A: If you want a windowed app with no menus on mac, the steps have changed since @PaulR responded.
The new steps are as follows:
navigate to
chrome://flags

Enable the following two options:

*

*"The new bookmark app system"

*"Allow hosted apps to be opened in windows"
Restart Chrome to enable the options.
Then navigate to the page you want to turn into an "app".
In the tools menu (three dots) click More Tools > Add to Applications
Finally, navigate to
chrome://apps

and right click on the icon for the newly added Application. Enable the "Open as window" option.

A: From the linux man page:
--app=URL
          Runs URL in "app mode": with no browser toolbars.

e.g. invoke it with google-chrome --app=http://example.com

A: Start Chrome with the --kiosk flag. Then, no borders etc. will be shown. Furthermore, pressing F11 will not exit this mode, so it's the most effective way of running a Kiosk-like app.
chromium --kiosk http://example.com/

Replace chromium with the path of your actual Chrome executable (e.g. chrome.exe).
In the new Chrome (v88) it might be required to add --user-data-dir parameter to remove the title bar, so the line would go like this:
chrome.exe --user-data-dir=c:\temp --kiosk http://google.com

If you open Chrome in app mode, like Trever suggests, then borders will still be visible.

A: Go ahead and create the shortcut, then open Chrome Apps chrome://apps. The shortcut icon should be in there. Right click on the app icon and check "Open as window." After that, the shortcut will open as a window.
Credit: Janos_

A: You can create create shortcuts from Chrome itself....
https://support.google.com/chrome/answer/95710?hl=en-GB
^ this link no longer works.
The feature is called "Create application shortcuts". To enable it in newer versions of Chrome, go to:
chrome://flags/

... using the address bar. Then find "The new bookmark app system" and Disable it. Then click Relaunch Now at the bottom of the screen.
Now, in the "More tools" menu there will be the "Create application shortcuts" menu entry.
There may be another way to do this, but this is just clarifying the method that was supposed to be described in the link.

A: Like many others have said, --app=<url> should do it for Chrome Version: 83.0.4103.61. The --kiosk option opens a chrome tab, not a borderless "app" window. I'm on macOS Catalina and decided to brew cast install chromium and ran:
chromium --app=https://netflix.com

Unfortunately I could not stream Netflix from Chromium..