text:
Q: WooCommerce-Send Custom Selected Price in Cart Hello Everyone I have customized the woo-commerce single product page according to my requirement, So now two prices are coming first price is my custom price as per my selection, Second price i have entered from WooCommerce product page(entered from wp-admin dashboard), right now second price is going in cart but i want to pass custom price how can i achieve this please suggest me thank you in advance.
Using ajax I am changing my custom price
 Custom Price:

Default Price:

<?php  echo $product->get_price_html(); ?>

Update:
  I am using this code
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price');
function add_custom_price( $cart_object ) {

  $custom_price = 70; // This will be your custome price
  foreach ( $cart_object->cart_contents as $key => $value ) {
      $value['data']->price = $custom_price;
  }

}
right now 70 is static price instead of this i want to pass paragraph because I am getting my price in paragraph using ajax..

A: add_action('woocommerce_get_price','change_price_custom', 10, 2);
function change_price_custom($price, $productd){
    return $price*2; // do calculation here
}

Try this in theme's function.php


text:
Q: Is it possible to merge 2 signed messages in one transaction? Someone sent me signed message (transfer). I want to broadcast it to Ethereum network on my behalf, and cover up the fees.
I also have my signed message (transfer), and want to combine them both into 1 transaction.
Is it possible to merge them?
Or somehow optimise this using other method?
The main goal is: combined transaction need to be 1 and unique. So this combined amount of tokens will be processed by contract without the risk that a 3rd party will infiltrate the association.

A: The short answer is no. The way ECC encryption works is that you can't predict the outcome of encryption. So you can't just take encrypted result 1 + encrypted result 2 and get encrypted result 3.
Depending on the reason you are trying to do this, I could suggest a feasible solution. For example if you are trying to transact on someone's behalf to save them the gas, perhaps you can look at Meta Transactions.
Alternatively if you are trying to do something requiring multiple parties to sign something you can look at multisig.
I think for an abstract question like this you should probably provide a bit more context, so those answering have a chance to help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "cannot be cast to" error with two images and seekbar I want to have 3 items on screen: SeekBar, Background img, Rotatable img.
Task: to draw 2 images: gauge and a needle and later depending on seekbar progress to rotate the needle.
The problem occurs when i try to uploading to tablet
07-10 09:52:13.680: E/AndroidRuntime(30494): java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.aaa.samples.thermometer/com.aaa.samples.meter.MeterActivity}:
java.lang.ClassCastException: com.aaa.samples.meter.MeterActivity cannot be cast to android.widget.SeekBar$OnSeekBarChangeListener

Tried a lot of different setups with relativelayout etc. no luck

<SeekBar
    android:id="@+id/seekBar1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="150" />

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/spidometras" />
            <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/rodykle" />
        </FrameLayout>

Class if needed:
seekBar = (SeekBar)findViewById(R.id.seekBar1);

    seekBar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this);
    seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            // TODO Auto-generated method stub

            ImageView img = (ImageView)findViewById(R.id.imageView1);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.rodykle);
            // Getting width & height of the given image.
            int w = bmp.getWidth();
            int h = bmp.getHeight();
            // Setting post rotate to 90
            Matrix mtx = new Matrix();
            mtx.postRotate(progress);
            // Rotating Bitmap
            Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, w, h, mtx, true);
            BitmapDrawable bmd = new BitmapDrawable(rotatedBMP);
            img.setImageDrawable(bmd);

        }
    });

}

A: Remove seekBar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this); line
Look closely in your class code
Below line:
 seekBar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this);

Tries to type case Activity into OnSeekBarChangeListener and on next line you are attaching a new  OnSeekBarChangeListener. So just remove this line.

A: Sounds like your generated files are corrupted/not updated.
Try going to Project-> Clean.


text:
Q: Reading in environment variables from an environment file I'd like to run in a local environment a Python script which is normally run in a Docker container. The docker-compose.yml specifies an env_file which looks (partially) like the following:
DB_ADDR=rethinkdb
DB_PORT=28015
DB_NAME=ipercron

In order to run this locally, I would like these lines to be converted to
os.environ['DB_ADDR'] = 'rethinkdb'
os.environ['DB_PORT'] = '28015'
os.environ['DB_NAME'] = 'ipercron'

I could write my parser, but I was wondering if there are any existing modules/tools to read in environment variables from configuration files?

A: If your system/environment/workflow supports using shell scripts, you can create a script that wraps these 2 operations:

*

*Sourcing the .env file and exporting them as environment variables

*

*Using the set -a option where "Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands".

*Calling your Python script/app that has plain os.environ.get code

Sample .env file (config.env):
TYPE=prod
PORT=5000

Sample Python code (test.py):
import os

print(os.environ.get('TYPE'))
print(os.environ.get('PORT'))

Sample bash script (run.sh):
#!/usr/bin/env bash

set -a
source config.env
set +a

python3 test.py

Sample run:
$ tree
.
├── config.env
├── run.sh
└── test.py

$ echo $TYPE

$ echo $PORT

$ python3 test.py
None
None

$ ./run.sh
prod
5000

When you run the Python script directly (python3 test.py) without source-ing the .env file, all the environ.get calls return None.
But, when you wrap it in a shell script that first loads the .env file into environment variables, and then runs the Python script afterward, the Python script should now be able to read the environment variables correctly. It also ensures that the exported env vars only exist as part of the execution of your Python app/script.
As compared with the other popular answer, this doesn't need any external Python libraries.

A: I use Python Dotenv Library. Just install the library pip install python-dotenv, create a .env file with your environment variables, and import the environment variables in your code like this:
import os
from dotenv import load_dotenv

load_dotenv()

MY_ENV_VAR = os.getenv('MY_ENV_VAR')

From the .env file:
MY_ENV_VAR="This is my env var content."

This is the way I do when I need to test code outside my docker system and prepare it to return it into docker again.

A: This could also work for you:
env_vars = [] # or dict {}
with open(env_file) as f:
    for line in f:
        if line.startswith('#') or not line.strip():
            continue
        # if 'export' not in line:
        #     continue
        # Remove leading `export `, if you have those
        # then, split name / value pair
        # key, value = line.replace('export ', '', 1).strip().split('=', 1)
        key, value = line.strip().split('=', 1)
        # os.environ[key] = value  # Load to local environ
        # env_vars[key] = value # Save to a dict, initialized env_vars = {}
        env_vars.append({'name': key, 'value': value}) # Save to a list

print(env_vars)

In the comments, you'll find a few different ways to save the env vars and also a few parsing options i.e. to get rid of the leading export keyword. Another way would be to use the python-dotenv library. Cheers.
UPDATE: I setup my own envvar_utils.py to handle conversion from string etc..
"""Utility functions for dealing with env variables and reading variables from env file"""
import os
import logging
import json

BOOLEAN_TYPE = 'boolean'
INT_TYPE = 'int'
FLOAT_TYPE = 'float'
STRING_TYPE = 'str'
LIST_TYPE = 'list'
DICT_TYPE = 'dict'

def get_envvars(env_file='.env', set_environ=True, ignore_not_found_error=False, exclude_override=()):
    """
    Set env vars from a file
    :param env_file:
    :param set_environ:
    :param ignore_not_found_error: ignore not found error
    :param exclude_override: if parameter found in this list, don't overwrite environment
    :return: list of tuples, env vars
    """
    env_vars = []
    try:

        with open(env_file) as f:
            for line in f:
                line = line.replace('\n', '')

                if not line or line.startswith('#'):
                    continue

                # Remove leading `export `
                if line.lower().startswith('export '):
                    key, value = line.replace('export ', '', 1).strip().split('=', 1)
                else:
                    try:
                        key, value = line.strip().split('=', 1)
                    except ValueError:
                        logging.error(f"envar_utils.get_envvars error parsing line: '{line}'")
                        raise

                if set_environ and key not in exclude_override:
                    os.environ[key] = value

                if key in exclude_override:
                    env_vars.append({'name': key, 'value': os.getenv(key)})
                else:
                    env_vars.append({'name': key, 'value': value})
    except FileNotFoundError:
        if not ignore_not_found_error:
            raise

    return env_vars

def create_envvar_file(env_file_path, envvars):
    """
    Writes envvar file using env var dict
    :param env_file_path: str, path to file to write to
    :param envvars: dict, env vars
    :return:
    """
    with open(env_file_path, "w+") as f:
        for key, value in envvars.items():
            f.write("{}={}\n".format(key, value))
    return True

def convert_env_var_flag_to(env_var_name, required_type, default_value):
    """
    Convert env variable string flag values to required_type
    :param env_var_name: str, environment variable name
    :param required_type: str, required type to cast the env var to
    :param default_value: boolean, default value to use if the environment variable is not available
    :return: environment variable value in required type
    """
    env_var_orginal_value = os.getenv(env_var_name, default_value)
    env_var_value = ""
    try:
        if required_type == INT_TYPE:
            env_var_value = int(env_var_orginal_value)
        elif required_type == FLOAT_TYPE:
            env_var_value = float(env_var_orginal_value)
        elif required_type == BOOLEAN_TYPE:
            env_var_value = bool(int(env_var_orginal_value))
        elif required_type == STRING_TYPE:
            env_var_value = str(env_var_orginal_value)
        elif required_type == LIST_TYPE:
            env_var_value = env_var_orginal_value.split(',') if len(env_var_orginal_value) > 0 else default_value
        elif required_type == DICT_TYPE:
            try:
                env_var_value = json.loads(env_var_orginal_value) if env_var_orginal_value else default_value
            except Exception as e:
                logging.error(f"convert_env_var_flag_to: failed loading {env_var_orginal_value} error {e}")
                env_var_value = default_value
        else:
            logging.error("Unrecognized type {} for env var {}".format(required_type, env_var_name))

    except ValueError:
        env_var_value = default_value
        logging.warning("{} is {}".format(env_var_name, env_var_orginal_value))

    return env_var_value

A: I think you should leave it for external tools to manage the environment for you.
This way you can easily use secret manager like 1password cli to get the environment variables loaded from encrypted vault like so
op run --env-file=.env -- python your_script.py

Having that said load_dotenv is smart enough not to load .env variables if they are present in the environment but some of the other solutions aren't.
And if you don't have any external tool at your disposal just use 'bash':
set -o allexport; source .env; set +o allexport

Solution taken from: Set environment variables from file of key/value pairs

A: You can use ConfigParser. Sample example can be found here.
But this library expects your key=value data to be present under some [heading]. For example, like:
[mysqld]
user = mysql  # Key with values
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb      # Key without value
skip-innodb

A: Dewald Abrie posted a good solution.
Here's a slight modification that ignores breaklines (\n)
def get_env_data_as_dict(path: str) -> dict:
    with open(path, 'r') as f:
       return dict(tuple(line.replace('\n', '').split('=')) for line
                in f.readlines() if not line.startswith('#'))

print(get_env_data_as_dict('../db.env'))

A: Using only python std
import re

envre = re.compile(r'''^([^=]+)\s+?=\s+?(?:[\s"']*)(.+?)(?:[\s"']*)$''')
result = {}
with open('/etc/os-release') as ins:
    for line in ins:
        match = envre.match(line)
        if match is not None:
            result[match.group(1)] = match.group(2)

A: How about this for a more compact solution:
import os

with open('.docker-compose-env', 'r') as fh:
    vars_dict = dict(
        tuple(line.replace('\n', '').split('='))
        for line in fh.readlines() if not line.startswith('#')
    )

print(vars_dict)
os.environ.update(vars_dict)

A: In situations where using the python-dotenv wasn't possible, I've used something like the following:
import os

def load_env_file(dotenv_path, override=False):
    with open(dotenv_path) as file_obj:
        lines = file_obj.read().splitlines()  # Removes \n from lines

    dotenv_vars = {}
    for line in lines:
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue

        key, value = line.split("=", maxsplit=1)
        dotenv_vars.setdefault(key, value)

    if override:
        os.environ.update(dotenv_vars)
    else:
        for key, value in dotenv_vars.items():
            os.environ.setdefault(key, value)

It reads the given file and parses lines that have the "=" symbol in them.
Value before the symbol will be the key, and value after is the value.
Current environment variables with the same keys as in the env file can either be left untouched or overwritten with the override parameter.

A: python-decouple is a good option for these types of files. While it is often used for django applications, it is extensible for arbitrary environment files.
from decouple import Config, RepositoryEnv

env=Config(RepositoryEnv('.env'))

env.get('DB_ADDR') #=> 'rethinkdb'
env.get('DB_PORT') #=> '28015'
env.get('DB_NAME') #=> 'ipercron'

A: I'm not very proud of this, however, in contrast to other answers, it seems to work if one has lines which end with a comment (after data in the same line). Adapted @Tom's answer.
# have to parse manually since dotenv package is not available
def get_env_data_as_dict(dotenv_path):
    result = {}
    with open(dotenv_path) as file_obj:
        lines = file_obj.read().splitlines()  # Removes \n from lines

    for line in lines:
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        if "#" in line:
            line = line.split("#")[0].strip()
        key, value = line.split("=", maxsplit=1)
        result[key] = value
    return result

A: I would not recommend directly reading .env files from within your program. The idea of the config part in 12 factor app is that you read the config from the environment variables -- i.e. not from files.
.env files are just a convenient way to get those variables into the environment (see below). If you start reading the files directly in your code, you're short cutting this step over the environment variables with all consequences and are basically back to square one, reading config from files.
So what you should do instead, use a tool such as dotenv-cli that reads .env files, exports the variables into the environment and runs your app with the temporary modified environment, like so:
$ dotenv yourapp


text:
Q: Where to specify server id's using jqgrid/tabletogrid I am using the tableToGrid method from jqgrid to generate a grid from an existing html table. My table is defined something like this:

            My Title

Item 321

Item 111

Item 495

           ...

The ids all come from the database and I will need them to perform updates.  When I call tableToGrid, it seems to overwrite all my ids with its own that just count from 1 to how ever many rows are in the table.  It would be nice if the onSelectRow method was passed the actual server id, but id that is not possible what is the best way to store the server id on the table, not display it and still have access to it for updates etc.
My tableToGrid call is like the following:

tableToGrid("#myTable", {
        width:230,
        height: 500,
        onSelectRow: onSelectMethod,
        colModel: [{ name: 'MyTitle', index: 'MyTitle', sortable: false}]
    });

Thanks.

A: I personally prefer to create jqGrid directly instead of the usage of tableToGrid. In the case you would has no described problems.
If you do prefer to use tableToGrid I can suggest you to use the following trick. The current code of tableToGrid can get the rowids, but it get it not from id attributes of the
. Instead of that it uses value attribute from the radio button from the first column of the table. It will be clear on your example. You can modify your original table to the following

      	My Title

<input type="radio" name="sel" value="321"/>	Item 321

<input type="radio" name="sel" value="111"/>	Item 111

<input type="radio" name="sel" value="495"/>	Item 495

In the example the value attribute of the radio button from the first column should contain the rowid. The JavaScript code can be
tableToGrid("#myTable", {
   width: 230,
   height: 'auto',
   onSelectRow: function (id) {
       alert(id);
   },
   colNames: ['My Title'],
   colModel: [
       { name: 'MyTitle', index: 'MyTitle', sortable: false}
   ]
});

The demo will now work like you as need.
The usage of additional column with the radio button can look unneeded. I personally don't like this way. If you examine the code of tableToGrid you will see that it's not complex. You can modify it so that it will get the rowids not from radio buttons but from the id of
 instead.


text:
Q: extract text from h1 and id with python beautiful soup I'm trying to extract the text from HTML id="itemSummaryPrice" but I couldn't figure it out.
html = """

Item Report

 |

Friday, January 15, 2021, 8:38 AM EST

                    Forest Green Endo

                **
200 - 300
**

"""

my code:
price_checker_site = requests.get(price_checker_url + match2)
price_checker_site_soup = BeautifulSoup(price_checker_site, 'html.parser')
price_check_item = price_checker_site_soup.find('h1', {'id': 'itemSummaryPrice'})

print(price_check_item)

returns with:

What I'm trying to extract:

200 - 300

OR

200 - 300

OR
200 - 300

A: Because I can't place comments yet an answer then. Shouldn't you call .text behind the price_check_item?
So the python code looks like this.
price_checker_site = requests.get(price_checker_url + match2)
price_checker_site_soup = BeautifulSoup(price_checker_site, 'html.parser')
price_check_item = price_checker_site_soup.find('h1', {'id': 'itemSummaryPrice'})

print(price_check_item.text) #Also possible to do print(price_check_item.text.strip())

I think this is the correct answer. Unfortunately not able to test now. Will check my code for you tonight.

A: As discussed in the comments, the content you seek is loaded dynamically using JavaScript. Therefore, you must either use a library like Selenium to dynamically run the JS, or find out where/how the data is loaded and replicate that.
Method 1: Use Selenium
from selenium import webdriver

url = 'https://rl.insider.gg/en/psn/octane/grey'
driver = webdriver.Firefox(executable_path='YOUR PATH')  # or Chrome
driver.get(url)
price = driver.find_element_by_id('itemSummaryPrice')
print(price.text)

In this case its easy, you just make the request and use find_element_by_id to get the data you want.
Method 2: Trace & Replicate
If you look at your browser's debugger, you can find where/how the itemSummaryPrice it set.
In particular, we find that its set using $('#itemSummaryPrice').text(itemData.currentPriceRange) in https://rl.insider.gg/js/itemDetails.js.
The next step is to find out where itemData comes from. It turns out, this is not from some other file or API call. Instead, it appears to be hard-coded in the HTML source itself (presumably loaded server-side).
If you inspect the source, you'll find the itemData is just a JSON object defined on one line within a script tag on the page itself.
There are two different approaches you can use here.
Use Selenium's execute_script to extract the data. This gives you the JSON object in a ready-to-use format. You can then just index it to get the currentPriceRange.
from selenium import webdriver

driver = webdriver.Firefox(executable_path='YOUR PATH')  # or Chrome
driver.get(url)
itemData = driver.execute_script('return itemData')
print(itemData['currentPriceRange'])

Method 2.1: Alternative to Selenium
Alternatively, you can extract this in Python using traditional methods. Then, convert that to a usable Python object using json.loads and then, index the object to extract the currentPriceRange -- this gives you the desired output.
import re
import requests
import json

# Download & convert the response content to a list
url = 'https://rl.insider.gg/en/psn/octane/grey'
site = str(requests.get(url).content).split('\\n')

# Extract the line containing 'var itemData'
itemData = [s for s in site if re.match(r'^\s*var itemData', s)][0].strip()

# Remove 'var itemData' and ';' from that line
# This leaves valid JSON which can be converted from a string using json.loads
itemData = json.loads(re.sub(r'var itemData = |;', '', itemData))

# Index the data to extract the 'currentPriceRange'
print(itemData['currentPriceRange'])

This approach doesn't require Selenium to run the JavaScript and also doesn't require BeautifulSoup to parse the HTML. It does rely on the itemData being initialized in a certain way. Should the developers of that site decide to change the way this is done, you'll have to adapt it slightly in response.
Which method should I use?
If all you really want is the price range and nothing else, then use the first method. If you're interested in other data as well, you'd be better off extracting the full itemData JSON from the source and using that.
One could argue Selenium is more reliable than manual parsing of the HTML, but in this case you're probably fine. In both cases, you assume there is some itemData defined somewhere. If the format does change slightly, then the parsing may break. The other disadvantage is if part of the data relied on JS function calls -- which Selenium would execute, whereas manual parsing couldn't account for. (This isn't the case here, but it could change).


text: Q: How to handle UIView background image color with single Image I have to display a image in UIView background color (I don't want to use UIImageView) by using colorWithPatternImage, I am able to display it. But how to do this with single image without using multi-dimension images?


text:
Q: Issue with saving canvas data to an array I am creating a web application using HTML5  canvas to draw images ( like paint web ), I try to implement the "undo" (ctrl+Z) and "redo" features and here I am facing a strange problem with an array of canvas elements.
Sometimes, when I hit ctrl+Z to undo, a blank image appears, however the data is in the array and I point to the correct element (because when I play with undo/redo I manage to have the corrects images in the right order).
If you can have a look at the following code I would be grateful, I've spent a lot of time already and I'm not able to locate the problem... :-(
function Stack(firstImg , size) {
    var drawStack = new Array();
    var stackIndex = 0;
    var stackTop = 0;
    var stackFloor = 0;
    var stackSize = size;

    drawStack[0] = firstImg;

    this.add = function() {
        drawStack[++stackIndex%stackSize] = cvs.toDataURL("image/png");
        if (stackIndex >= stackSize) stackFloor = (stackIndex +1) % stackSize ;
        stackTop = stackIndex % stackSize;
    }

    this.undo = function () {
        if (stackIndex%stackSize == stackFloor ) return;
        clearCanvas();
        var tmpImg = new Image();
        tmpImg.src = drawStack[--stackIndex%stackSize];
        cvsCtx.drawImage(tmpImg, 0, 0);

    }

    this.redo = function () {
        if (stackIndex%stackSize == stackTop) return;
        clearCanvas();
        var tmpImg = new Image();
        tmpImg.src = drawStack[++stackIndex%stackSize];
        cvsCtx.drawImage(tmpImg, 0, 0);
    }
}

Any solution or workaround, I will take, thank you very much !!

A: I have implemented undo/redo functionality a few times and, while I cannot post the code for licensing reasons, I can give you some psuedocode that should demonstrate how simple undo/redo actually is:
first, you need two arrays. call these "undo" and "redo".
Every time the state changes, push that state to the undo stack.
When the user presses ctrl-z (undo), pop the last saved state from the undo stack. push this state to the redo queue, and also make it the current state.
When the user presses ctrl-y (redo), pop the last saved state from the redo queue.
If either of the arrays begins to fill up past the # of states you want to save, use shift to discard the oldest state.
For references on push, pop, and shift, see the MDN documentation.
Also, you will probably find yourself wishing arrays had peek, so here it is:
Array.prototype.peek = function () {
    var theArray = this;
    var temp = theArray.pop();

    if (temp !== undefined) {
        theArray.push(temp);
    }

    return temp;
};

edit: there was a bug in my snippet, calling .peek() on an empty array would push undefined.


text:
Q: How to define latitude & longitude instead of address in google map? I am displaying Map in my Application.I have added the code below and now the map is displaying correctly for particular city name. My Problem is i need to fetch location by using latitude and longitude of a particular city.
I don't want any new code.  Is it possible the get the latitude and longitude values within this code itself by pass @item.Latitude@item.Longitude  instead of @item.city

A: There are a number of different ways to display Google Maps in your browser.
but the two most easy and good ways are:
 1. to Use Goggle MAP API https://developers.google.com/maps/?hl=en
 2. Google Polymer as shown below:

<link rel="import" href="components/google-map/google-map.html">

<google-map latitude="37.790" longitude="-122.390"></google-map>

A: Try { 'latlng': latitude + ',' + longitude } instead of { 'address': address }.
I didn't test it but it seems to work according to googlemap webservice api : https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding


text:
Q: Mi grid-template-areas no aparece en el navegador como lo ordené en código Sin importar el min-width en el que esté el media query, siempre me aparece a la derecha el el grid-area "link", a pesar de que en el grid-template-areas lo puse hasta abajo. ¿Cómo hago que aparezca abajo?
En el momento en que uso un media query para intentar hacerlo responsive con el tamaño de el navegador pero siempre se vuelve a estar el "link" a la derecha.
Llevo dos horas analizando el código y repasando mis apuntes pero no comprendo qué está mal con mi código.

El código CSS está correctamente, según he repasado durante dos hora.

@media(min-width:1200px){
    #main{
      display:grid;
      grid-template-areas:
        "header header header header"
        "img-div img-div img-div section"
        "tribute_info tribute_info tribute_info tribute_info"
        "link link link link";
    }
    #header{
    display:grid;
     grid-area:header;

    }

    #title{
    text-align:center;
    }

    #title_description{
      text-align:center;
    }

    #img-div{
      display:grid;
      grid-area:img-div;
    }
    #image{
     align:center;
    }

    #img-caption{
      text-align:justify;
    }
    #section{
    display:grid;
    grid-area:section;
    }
    #tribute-info{
      display:grid;
      grid-area:article;
    }

    #tribute-link{
      display:grid;
      grid-area:link;
    }

Porfirio Diaz

Un padre duro

      <figurecaption id="image_caption">Descripción</figurecaption>

Eventos importantes en los que participó

Exilio

Tiene un desayuno en la parroquia

<time>15 septiembre 1830</time> Nace el viejo bigotón

Para más información, revisa
    este link

A: Tenías varios errores tipográficos que he solucionado, pero el mayor de ellos era el siguiente:
CSS
#main {
  display:grid;
  grid-template-areas:
    "header header header header"
    "img-div img-div img-div section"
    "tribute_info tribute_info tribute_info tribute_info"
    "link link link link";
}

#tribute-info {
  display:grid;
  grid-area:article;
}

HTML

En el #main has definido el área "tribute_info" pero al elemento que se supone que debería tenerlo le estás asignando grid-area: article; Esto ocasiona que ocupe solamente una de las celdas del grid en vez de las cuatro que estás buscando que ocupe.
Por otro lado tienes definido en el HTML un elemento id="tribute_info", pero en el CSS haces referencia a un elemento #tribute-info ocasionando que sus reglas CSS no afecten a elemento alguno. Con el elemento id="tribute_link te está ocurriendo exactamente lo mismo.

@media(min-width:1200px) {
  #main {
    display:grid;
    grid-template-areas:
      "header header header header"
      "img-div img-div img-div section"
      "tribute_info tribute_info tribute_info tribute_info"
      "link link link link";
  }

  #header {
    display:grid;
    grid-area:header;
  }

  #title {
    text-align:center;
  }

  #title_description {
    text-align:center;
  }

  #img-div {
    display:grid;
    grid-area:img-div;
  }

  #image {
   text-align:center;
  }

  #img-caption {
    text-align:justify;
  }

  #section {
    display:grid;
    grid-area:section;
  }

  #tribute_info {
    display:grid;
    grid-area:tribute_info;
  }

  #tribute_link {
    display:grid;
    grid-area:link;
  }

Porfirio Diaz

Un padre duro

      <figurecaption id="image_caption">Descripción</figurecaption>

Eventos importantes en los que participó

Exilio

Tiene un desayuno en la parroquia

<time>15 septiembre 1830</time> Nace el viejo bigotón

Para más información, revisa este link


text:
Q: Jquery contains method not work if the string has space jQuery's :contains selector does not work if the string has space with it.
For example, I want to select a dropdown value (Ex: 1st Letter) through jQuery.
If I give like below, it is working fine
$('.z-comboitem-text:contains(1st)')

If I give like below, it is not working
$('.z-comboitem-text:contains(1st letter)')

Please give your suggestions
Thanks in Advance.

A: Well its working:

$('.div:contains(1st letter)').css('color', 'red');

  asdfasfafd asdfas
  dfa

   d asdf
  asdf
  asdf
  1st letter
  a
  sdf
  asdf
  as
  fas
  df
  a

Now your question: I want to select a dropdown value

$('select option:contains(1st letter)').css('color', 'red');

console.log($('select option:contains(1st letter)'));

<select>
  <option>select...</option>
  <option>1st letter</option>
  <option>2nd letter</option>
  <option>3rd letter</option>
</select>


text:
Q: What's wrong with my SQL query? Syntax errors This SQL query worked fine until I tried adding the CASE statement in, but now I get syntax errors as described at the bottom of this post. Here's the SQL (pretty epic, but the syntax errors take place around the CASE, maybe with the SageAccount select prior)
SELECT CurrentBalance.Value AS CurrentBalanceValue,
       Debt30Balance.Value AS Debt30BalanceValue,
       Debt60Balance.Value AS Debt60BalanceValue,
       Debt90Balance.Value AS Debt90BalanceValue,
       WIP.Value AS WIPValue, CurrentBalance.Value + Debt30Balance.Value +
           Debt60Balance.Value + Debt90Balance.Value AS SLDebt,
       CurrentBalance.Value + Debt30Balance.Value + Debt60Balance.Value +
           Debt90Balance.Value+ WIP.Value AS TotalDebt,
       (SELECT CreditTerms FROM SageAccount WHERE ID=@CustomerID)
       AS CreditTerms,
CASE WHEN CreditTerms <= 30 THEN
CurrentBalance.Value + Debt30Balance.Value +
    Debt60Balance.Value + Dept90Balance.Value
ELSE WHEN CreditTerms <= 60 THEN
Debt30Balance.Value + Debt60Balance.Value + Dept90Balance.Value
ELSE WHEN CreditTerms <= 90 THEN
Debt60Balance.Value + Dept90Balance.Value
ELSE
Debt90Balance.Value
END AS Overdue
FROM (SELECT TOP (1) Value, Customer FROM DebtBreakdown
       WHERE (Type = 0) AND (Customer = @CustomerID)
       ORDER BY Timestamp DESC) AS CurrentBalance
       INNER JOIN (SELECT TOP (1) Value, Customer
       FROM DebtBreakdown AS DebtBreakdown_1
       WHERE (Type = 1) AND (Customer = @CustomerID)
       ORDER BY Timestamp DESC) AS Debt30Balance ON
       CurrentBalance.Customer = Debt30Balance.Customer
       INNER JOIN (SELECT TOP (1) Value, Customer FROM
       DebtBreakdown AS DebtBreakdown_2
       WHERE (Type = 2) AND (Customer = @CustomerID)
       ORDER BY Timestamp DESC)
       AS Debt60Balance ON Debt30Balance.Customer = Debt60Balance.Customer
       INNER JOIN (SELECT TOP (1) Value, Customer FROM DebtBreakdown AS
       DebtBreakdown_3 WHERE (Type = 3) AND (Customer = @CustomerID)
       ORDER BY Timestamp DESC) AS Debt90Balance ON
       Debt60Balance.Customer = Debt90Balance.Customer
       INNER JOIN (SELECT TOP (1) Value, Customer FROM DebtBreakdown AS
       DebtBreakdown_4 WHERE (Type = 4) AND (Customer = @CustomerID)
       ORDER BY Timestamp DESC) AS WIP ON Debt90Balance.Customer = WIP.Customer

Sorry, forgot the errors!
Error in WHERE clause near 'WHEN'. Error in WHERE clause near ','. Error in WHERE clause near 'ORDER'. Unable to parse query text.

A: Try changing the "ELSE WHEN" statements to just "WHEN"  (leave the final ELSE as-is)


text:
Q: Como usar o javascript sem caixas de diálogos? Eu quero pedir uma informação ao usuário só que sem usar aquelas caixas de diálogos e sim deixar impresso lá no site, com o uso do input. É com o javascript que se faz isso? Tentei pesquisar algo no google e eu não achei nada. Eu quero muito poder programar meu site, mas eu não faço ideia de por onde começar a aprender, ou coisa do tipo. Se tiverem uma dica eu agradeço.
Obs.: Este é um exemplo do que eu estou tentando fazer,já que eu não expliquei tão bem...
Obs2.: Eu li o que vocês colocaram, só que pra pedi uma informação como essa, onde eu vou armazenar a resposta, eu não sei outra forma sem usar o prompt... Mas se eu usa-lo eu terei que usar o javascript, que consequentemente ele irá aparecer em uma caixa de diálogos.

A: Vejamos, você pode fazer um input e um botão submit, este que quando clicado (onClick) chamará uma função javascript que irá pegar os dados inseridos no input e fazer o que você deseja.
Lembrando que usando JavaScript o usuário poderá ver o código do seu script, então ele poderá saber todo o processo envolvendo o input.

A: Não sei se eu entendi bem o que você quer, mas pelo que eu li você quer dar uma mensagem ao usuário, em alguma posição na sua página que não seja por alert() ou algo parecido. Você pode usar o InnerHtml do javascript para isso, se é isso que eu estou entendendo. Com ele você dá a mensagem em uma determinada posição, como uma <div>, ou um input text e etc..., seria mais ou menos assim:
Defina uma área com um id de preferência. Essa área é onde você vai dar a mensagem. Vamos supor que seja de id="txt_msg". Aí você faz:
function ExibeMensagem(pNomeParametroQualquer) {
    document.getElementById('txt_msg').innerHTML = 'Minha Mensagem';
}

No seu Form(web), você num evento qualquer, tipo click ou change do textbox, você chama a função:
<input button id="ffff" onclick="ExibeMensagem(qualquer_coisa)" />

Acho que foi isso que eu entendi o que você quer.


text:
Q: PHP - Upload CSV to textarea of html and get its value to store in textarea I want to upload Csv file and output its content in text-area of HTML.
example is i have 92133302,2391235,28743903 in Csv and if i upload this the text-area should contain this number i have tried this but couldn't put it inside the text-area, so what supposed to happen is i will be using the $_POST[text-area]; and pass it again to another file but my problem is storing it's value in text-area. i am also using cloud server so i will store all my file to filezilla.

A: First you need to receive the CSV file you uploaded at your page. Then, you can pass the contents to a variable. Example:
$csvData = file_get_contents($fileName);

After this, you can echo the contents you got inside the textarea or another element:
<textarea>
    <?php
        echo $csvData;
    ?>
</textarea>


text:
Q: How can I unpack an integer into a float in PostgreSQL? I'm using Python's struct.pack function to pack various data types into a common 32-bit integer field in PostgreSQL.  The drawback is that I can't operate with these values in the database, I have to perform a struct.unpack in Python on the data to know what it represents.
If I pack a 32-bit float into this field, is there any way to get PostgreSQL to do the conversion for me?
I tried this but it didn't work:
select cast(cast(value as bit(32)) as float4) ...

It will successfully cast the integer to bit(32) but it won't convert that back to a float.

A: An answer you are probably not looking for: Don't do that.
This is a violation of the basics: a value in a database should be atomic, not divisible into other values.  All of the database's operations (did I mention all) are tuned to handling individual values.  You are "fighting the framework" here.
Even if you can pull it off, it will be a drag on performance.  Plus the database is not reportable, it's not just that you are having this issue now, every attempt to read this data for any reason will run into this problem.
Well, I don't want to go into a rant, 'nuf said.

A: The simplest solution, and one I'm sure you considered and abandoned, is to store 32-bit floating point values in a column defined to use a 32-bit floating point data type.
CAST() won't work for you, because a) CAST() doesn't know anything about C structs, endian-ness, or padding bytes, and b) you can't cast a bit data type to a floating point data type. (You can cast a bit data type to integer, though.)


text:
Q: Replace alt text with image in assets file Javascript This is my folder structure
-- assets
      |
   - missing.jpg

and this is the function I used to render the movie div
function showMovies(movies) {
  main.innerHTML = "";

  movies.forEach((movie) => {
    const { title, poster_path, vote_average, overview } = movie;

    const movieEl = document.createElement("div");

    movieEl.classList.add("movie");

    movieEl.innerHTML = `

${title}

          ${vote_average}

Overview

              ${overview}

    `;
    main.appendChild(movieEl);
  });
}

I am trying to change the alt image in this function to display an image in my assets folder instead of just the text title.

A: If I understand you correctly you want to add an image when there is no image found right?
ok, so there are multiple approaches to this problem, first, if you have an invalid path, use the terniary operator to src your image correctly
 src=`${IMG_PATH ? IMG_PATH + poster_path : '/assets/missing.jpg'}`

But... if the image fails to load because of the server being unavailable or some 400/500 error then that's a different story, My personal approach is to make a div with the size of the image and set multiple backgrounds using css properties for instance....
background: url("/path_to_movie_poster.gif"), url("/assets/missing.jpg");

This way if the first source failed for some reason then the default image will kick in.
Make sure your default image is the last in the least otherwise it will be on top.


text:
Q: Can I query the version of OpenOffice Writer from an AddIn? I am currently developing an OpenOffice-addin and I was wondering if I can query openoffice (writer) for its version. I would like to avoid adding more libraries if possible and rather use built-in mechanisms to do so.
Any ideas?

A: Use the ConfigurationProvider service as shown in the Basic code at https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=40282.
A Java example that uses the service is at:  How do I override ODF Root RSID using the API.
Note: IIRC, a similar question was answered on stackoverflow about a week ago.  However the question and answer seems to have been deleted.


text:
Q: Diagonalisable real matrix. Conclusion A matrix $A\in\mathbb{R}^{n,n}$ is diagonalisable on $\mathbb{R}$. Then:
a.  characteristic polynomial of $A$ is product of polynomials degree $1$ with real coefficients
b. matrix $A^2$ is also diagonalisable
c. $A=A^T$  .
b. is obviously true, we know that $A^2=(PDP^{-1})^2 = PD^2P^{-1}$  Due to $D^2$ is still diagonal then b. is true.
a.
We know that $A$ is similar to some diagonal matrix $D$. Therefore, $A$ has the same characteristic polynomial as $D$, so it is product of $(x-\lambda)$ where $\lambda$ is any eigenvalue. Lets consider:
$A=\left( \begin{array}{ccc}
2 & 0  \\
0 & 2 \\
\end{array} \right)=\left( \begin{array}{ccc}
1 & 0 \\
0 & 1 \\
\end{array} \right) \left( \begin{array}{ccc}
2& 0 \\
0 & 2 \\
\end{array} \right)\left( \begin{array}{ccc}
0& 1  \\
1 & 0 \\
\end{array} \right)$ is diagonalisable, but $P_A(x)=(x-2)^2$.  So it is not prodcut of degree 1 polynomials. Hence, a. is not true.
What about these solutions ?  Can you help me solve c. ?

A: For $c)$ , just take the matrix $\pmatrix{1&2\\3&4}$ which is not symmetric , but real diagonalizable.


text:
Q: What optimization model is used to divide groups of objects with feature according to some coefficient and percentage? We have N groups of objects. Objects could be triangles and rectangles (it's just an example to generalize question). Number of triangles and rectangles are not the same. Each group contains $r_{i}$ - rectangles, $t_{i}$ - triangles, so overall $k_{i} = t_{i} + r_{i}$ number of objects.
Problem: I want to divide these groups into three subgroups with ratio (80/10/10 percent of object per group). And at the same time I want, that ratio of triangles and rectangles will be approximately the same in each group (minimize difference between ration among all groups).
My attempts: Obviously, we may compute ratio $c_{i} = \frac{r_{i}}{t_{i}}$ for each group and check all variants, overall $3^{N}$. I wrote algorithm, that slightly better, than exhaustive search. Maybe we should use methods like https://en.m.wikipedia.org/wiki/Branch_and_bound ? (Which is also has complexity about $3^{N}$)

A: $ \sum_i \sum_{j=1}^3 t_{i,j} = \sum_it_i$
$ \sum_i \sum_{j=1}^3 r_{i,j} = \sum_ir_i$
$t_{i,1}+r_{i,1} = 8(t_{i,2}+r_{i,2}) = 8(t_{i,3}+r_{i,3}) \ \ \forall i$ where $t_{i,j}, r_{i,j}$ are vars $ \in R^+$ assigning triangles/rectangles to each of the 3 subgroups $j$ within each of the groups $i$
$ r_{i,j} = c_{i,j}t_{i,j} \ \ \forall j \in \{1,2,3\}, \ \ \forall i$ where $c_{i,j}$ is continuous variable $ \in R^+$
To minimize the difference between $c$s one way could be to minimize the range between $max(c_{i,j})$ and min
So additional cosntraints
$ c_{i,j} \le l \ \forall j \ \forall i$
$ z \le c_{i,j}\ \forall j \ \forall i$
$l$, $z$ track the min & max values.
Then min $ l-z$


text:
Q: Website validation in AngularJs I have a field that accepts a URL. How do I validate this URL in angularjs.

   <input type="text" ng-model="controller.data.PropertyWebsite"/>

Any ideas and suggestions are appreciated !!!!

A: Add a html input[url] to a form and mark it as required, then use angular to check if the form is valid or not:
html:
<form name="form">

        <input type="url" name="url" required>

        <button type="submit" ng-click="SubmitForm('form')">submit</button>

</form>

controller:
$scope.submitForm = function () {

    if (this.form.$invalid)
        //not valid
    } else {
        //valid
    }
}

More information about url input:
https://docs.angularjs.org/api/ng/input/input%5Burl%5D

A: You can use ng-pattern to validate against a RegEx. https://docs.angularjs.org/api/ng/directive/input


text:
Q: How to use string pattern while creating S3 Batch operation manifest file? I have tens of thousands of objects in my S3 bucket. And I want to encrypt all the existing objects using a KMS key. With my research, I could see S3 Batch Operations does this in single request.
My existing files in my S3 bucket are following a pattern. Lets assume sample_file_*.log. How to use such pattern in my manifest file?
Sample Manifest File (csv):
<source_bucket_name>,objectName1
<source_bucket_name>,objectName2
<source_bucket_name>,*.log

When I tried the Batch job with the above manifest file, it throws me Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: XYZ123; S3 Extended Request ID: xyz123; Proxy: null) error.
Please help me.

A: S3 Batch Operations does not work that way. You have to provide the key explicitly. If you have numerous S3 objects in a bucket, you can make use of S3 Inventory to collect all keys.


text:
Q: How can I write each character from string to separate div using JavaScript? This is what I have been far
This is my code:
function createWordTiles() {
            var word = ['Example'];
            var innerDiv;

            var iDiv = document.createElement('div');
            iDiv.id = 'tileBlock';
            iDiv.className = "tileBlock";

Code works only i remove loop :
            for (var l = 0; l <= word.length ; l++) {

                innerDiv = document.createElement('div');
                innerDiv.id = 'Block' + l;
                innerDiv.className = 'Block';
                innerDiv.innerHTML = word.charAt(l);
            }

            iDiv.appendChild(innerDiv);

            document.getElementsByTagName('body')[0].appendChild(iDiv);
        }

This is what I have made

How can I write each character from string to separate div using JavaScript?

A: Move your iDiv.appendChild(innerDiv); inside the for loop, like this:
for (var l = 0; l <= word.length ; l++) {

    innerDiv = document.createElement('div');
    innerDiv.id = 'Block' + l;
    innerDiv.className = 'Block';
    innerDiv.innerHTML = word.charAt(l);

    iDiv.appendChild(innerDiv);
}

A: HTML

Hello world

js
jQuery(document).ready(function($) {
var sourceText = $('.source-text').text(); // get the source text
var $destinationElm = $('.list'); // get destination

var i;
for(i = 0; i < sourceText.length; i++) {  // eterate through all characters
    $destinationElm.append('
' + sourceText[i] + '
'); // appends html element with text
}});


text:
Q: How to reference Google Cloud Storage image with "img src" (link direct to the image) Say I do this
./gsutil cp /home/blah/blah/post-images/google/cube.jpg gs://(bucket-name)/google/cube.jpg
The image is supposed to be here
<img src="https://console.developers.google.com/storage/(bucket-name)/google/cube.jpg
(as per https://developers.google.com/storage/docs/access-public-data) but it doesn't work...
That URL is fine if you want to see the image in the "bucket" and browse the bucket's directory structure, but useless if you want to link to the image directly.
I can go here https://console.developers.google.com/m/cloudstorage/b/(bucket-name)/o/google/cube.jpg to link directly to the image, BUT is this "/m/cloudstorage/b/" an arbitrary location or can I always find my images in there?  Also what is "/o/" that's not a subdirectory I created.  Are these random letters of the alphabet or is there a method to Google's madness or is it always "/o/" ?
In short, what's the correct way to directly link to my Google Cloud Storage images?

A: That URL is for the developer's console UI.
See Request URIs for a list of access points.
You probably want:
https://storage.googleapis.com/bucketname/google/cube.jpg


text:
Q: fields are not inserting into mysql Database android I am trying to store an android form data into MySQL database but the thing is other fields are completely fine and their values are storing into DB, the only name, and email are not inserting into DB. All code is fine, I am not even getting any errors. Please tell me what I have done wrong. If you can see the picture, there are some fields which are taking the value as 0. I don't understand why.Please tell me a proper solution if you know
This is my Code
MainActivity.java
public class MainActivity extends AppCompatActivity {

    private EditText etid, etname, etstorename, etemail, etphone, etdoj;
    Button btnregister;
    TextView tvlogin;
    private ParseContent parseContent;
    PreferenceHelper preferenceHelper;
    private final int RegTask = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        preferenceHelper = new PreferenceHelper(this);
        parseContent = new ParseContent(this);

        if(preferenceHelper.getIsLogin()){
            Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            this.finish();
        }
        etid = (EditText) findViewById(R.id.etmi_id);
        etname = (EditText) findViewById(R.id.etname);
        etstorename = (EditText) findViewById(R.id.etstore_name);
        etemail = (EditText) findViewById(R.id.etemail);
        etphone = (EditText) findViewById(R.id.etphone);
        etdoj = (EditText) findViewById(R.id.etdoj);
        btnregister = (Button) findViewById(R.id.btn);
        tvlogin = (TextView) findViewById(R.id.tvlogin);

        tvlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });

        btnregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    register();
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void register() throws IOException, JSONException {

        if (!AndyUtils.isNetworkAvailable(MainActivity.this)) {
            Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
            return;
        }
        AndyUtils.showSimpleProgressDialog(MainActivity.this);
        final HashMap<String, String> map = new HashMap<>();
        map.put(AndyConstants.Params.MI_ID, etid.getText().toString());
        map.put(AndyConstants.Params.NAME, etname.getText().toString());
        map.put(AndyConstants.Params.STORE_NAME, etstorename.getText().toString());
        map.put(AndyConstants.Params.EMAIL, etemail.getText().toString());
        map.put(AndyConstants.Params.PHONE, etphone.getText().toString());
        map.put(AndyConstants.Params.DOJ, etdoj.getText().toString());
        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                try {
                    HttpRequest req = new HttpRequest(AndyConstants.ServiceType.REGISTER);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss", result);
                onTaskCompleted(result, RegTask);
            }
        }.execute();
    }

    private void onTaskCompleted(String response,int task) {
        Log.d("responsejson", response.toString());
        AndyUtils.removeSimpleProgressDialog();  //will remove progress dialog
        switch (task) {
            case RegTask:

                if (parseContent.isSuccess(response)) {

                    parseContent.saveInfo(response);
                    Toast.makeText(MainActivity.this, "Registered Successfully!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    this.finish();

                }else {
                    Toast.makeText(MainActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
                }
        }
    }
}

PreferenceHelper.java
public class PreferenceHelper {
    private final String MI_ID = "mi_id";
    private final String NAME = "name";
    private final String STORE_NAME = "store_name";
    private final String EMAIL = "email";
    private final String PHONE = "phone";
    private final String DOJ = "doj";
    private SharedPreferences app_prefs;
    private Context context;

    public PreferenceHelper(Context context) {
        app_prefs = context.getSharedPreferences("shared",
                Context.MODE_PRIVATE);
        this.context = context;
    }

    public void putIsLogin(boolean loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putBoolean(PHONE, loginorout);
        edit.apply();
    }
    public boolean getIsLogin() {
        return app_prefs.getBoolean(PHONE, false);
    }

    public void putMi_id(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(MI_ID, loginorout);
        edit.apply();
    }
    public String getMi_id() {
        return app_prefs.getString(MI_ID, "");
    }

    public void putName(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(NAME, loginorout);
        edit.apply();
    }
    public String getName() {
        return app_prefs.getString(NAME, "");
    }

    public void putStore_name(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(STORE_NAME, loginorout);
        edit.apply();
    }
    public String getStore_name() {
        return app_prefs.getString(STORE_NAME, "");
    }

    public void putEmail(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(EMAIL, loginorout);
        edit.apply();
    }
    public String getEmail() {
        return app_prefs.getString(EMAIL, "");
    }
    public void putPhone(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(PHONE, loginorout);
        edit.apply();
    }
    public String getPhone() {
        return app_prefs.getString(PHONE, "");
    }

    public void putDoj(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(DOJ, loginorout);
        edit.commit();
    }
    public String getDoj() {
        return app_prefs.getString(DOJ, "");
    }
 }

Simplereg.php
<?php

   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
 //including the database connection file
       include_once("dbConfig.php");
        $mi_id = $_POST['mi_id'];
        $name = $_POST['name'];
        $store_name = $_POST['store_name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $doj = $_POST['doj'];

     if($mi_id == '' || $name == '' || $store_name == '' || $email == '' || $phone == '' ||$doj == ''){
            echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
     }else{

            $query= "SELECT * FROM registerdemo WHERE name='$name'";
            $result= mysqli_query($con, $query);

            if(mysqli_num_rows($result) < 1){
               echo json_encode(array( "status" => "false","message" => "Username already exist!") );
            }else{
            $name = $_POST['name'];

             $query1 = "INSERT INTO registerdemo (mi_id,name,store_name,email,phone,doj) VALUES ('$mi_id','$name','$store_name','$email','$phone','$doj')";
             if(mysqli_query($con,$query1)){

                 $query2= "SELECT * FROM registerdemo WHERE name='$name'";
                         $result2= mysqli_query($con, $query2);
                     $emparray = array();
                         if(mysqli_num_rows($result2) > 0){
                         while ($row = mysqli_fetch_assoc($result2)!=NULL) {
                                     $emparray[] = $row;
                                   }
                         }
                echo json_encode(array( "status" => "true","message" => "Successfully registered!" , "data" => $emparray) );
             }else{
                 echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
            }
        }
     }
     } else{
            echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
    }

 ?>


text:
Q: Netbeans auto-completion Java is there a way to disable the auto-completion for String in netbeans for java?
Example I type " netbeans writes "". I hope you know what i mean.

A: Goto Tools->Options->Editor->Code Completion and uncheck Insert Closing Brackets Automatically


text:
Q: JavaScripts, AJAX, PHP: can't set field values after getting json string Here is my code for product.php:

<form id="frmAddEditProduct" name="frmAddEditProduct" method="post" action="addproduct.php">
  <select class="form-control"  id="companyname" name="companyname">
    <option value"xyz">XYZ</option>
  </select>
  <input type="onlytext" class="form-control" name="productname" id="productname" placeholder="Product Name" required  />
  <input type="number" class="form-control" name="productlength" id="productlength" placeholder="Product Length" required  />
  <input type="number" class="form-control" name="productwidth" id="productwidth" placeholder="Product Width" required  />
  <input type="number" class="form-control" name="productheight" id="productheight" placeholder="Product Height" required  />
  <input type="number" class="form-control" name="productdeckle" id="productdeckle" placeholder="Deckle" required  />
  <input type="number" class="form-control" name="productcutting" id="productcutting" placeholder="Cutting" required  />
  <input type="number" class="form-control" name="productprice" id="productprice" placeholder="Price" required  />
  <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-lg btn-success btn-block" />
</form>

Edit

Here is my code for editproduct.php
<?php
    $connection = mysql_connect("localhost", "root", "") or die("Could Not Connect to DB: ".mysql_error());
    $db = mysql_select_db("proshell", $connection) or   die("Could Not Connect to DB: ".mysql_error());

    $json = array();
    $ID = $_GET['Id'];

    $result = mysql_query("SELECT * FROM product where Id=$ID");
    while($row = mysql_fetch_array($result))
    {
         $row_array['Id'] = $row[0];
         $row_array['Company'] = $row[1];
         $row_array['Name'] = $row[2];
         $row_array['Length'] = $row[3];
         $row_array['Width'] = $row[4];
         $row_array['Height'] = $row[5];
         $row_array['Deckle'] = $row[6];
         $row_array['Cutting'] = $row[7];
         $row_array['Price'] = $row[8];

         array_push($json, $row_array);
    }

    echo json_encode($json);
?>

Here is my code for product.js
function EditProduct(id) {
    //RemoveValidation();
    $('#status').html('');
    var userid = $('#id').val();
    $.ajax({
        type: "GET",
        url: 'editproduct.php',
        data: { "Id": id},
        success: function (data) {
            if (data != "Error") {
                $('#companyname').val(data.Company);
                $('#productname').val(data.Name);
                $('#productlength').val(data.Length);
                $('#productwidth').val(data.Width);
                $('#productheight').val(data.Height);
                $('#productdeckle').val(data.Deckle);
                $('#productcutting').val(data.Cutting);
                $('#productprice').val(data.Price);
                $('#productname').focus();
            }
            else {
                $('#status').attr("style", "color:Red;");
                $('#status').html("There was some error while getting data please refresh page and try again.");
            }
        }
    });
}

here after clicking on Edit button in product.php It comes to javascript function and it goes in to if condition when i watch my code in console of firefox it also give me string as response like this:
[{"Id":"1","Company":"Chintan Co.","Name":"Chintan's Box","Length":"7","Width":"8","Height":"9","Deckle":"17","Cutting":"18","Price":"99"}]

In if condition of EditProduct.php method
if I do like this: $('#productlength').val(data.Length);
then textbox shows nothing but if I do like this $('#productlength').val(data.length); then it shows me the length of the json array but I can't set any field.
So help me out here please.
Thank you

A: You are wrapping the data object in a needless array.
So in the javascript you would actually need to change data.Company to data[0].Company and similar for other properties.
I would suggest you get rid of the extra array in php
Instead of array_push($json, $row_array); just send $row_array
ALso note your php is very insecure using mysql extension which is deprecated and not sanitizing input for query


text:
Q: Microsoft Office InfoPath 2007/2010: Unable to load the view. The View may have been modified to contain unsupported HTML such as iframes I am trying to create a new blank form in InfoPath and i get the error
"InfoPath cannot load the view. The view may have been modified to contain unsupported HTML such as frames."
I am running windows XP, with IE7. No idea why im getting this error as this is the first time opening Office 2010.
I'm thinking the default templates got corrupted somehow.. Help!

A: The default view go corrupted and i had to start fresh..


text:
Q: I am unable to disable future date in jquery datepicker Here is my code.For any help thanks in advance.
<input type="text" id="hoDate" name="date" class="startDatePicker" required/>

And my jquery code is:
    $(function() {
      $( "#hoDate" ).datepicker({  maxDate: newDate() });
    });

A: Add space between new Date(). Try this:
$( "#hoDate" ).datepicker({  maxDate: new Date() });

To automatically set end date as start date selected:
<input type="text" id="hoDate" name="date" class="startDatePicker" required/>
<input type="text" id="endDate" name="enddate" class="endDatePicker" required/>

$( "#hoDate" ).datepicker({
    maxDate: new Date(),
    onSelect: function(){
    var selected = $(this).val();
    $("#endDate").val(selected)
    }
});


text:
Q: Avoid multiple DOCTYPE and html tags when using ui:include we are using several ui:include tags in the "main" page. The page that is to be included looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=".." xmlns:ui="..." ...>
    <ui:fragment rendered="${foo}">
       some html code
    </ui:fragement>
    <ui:fragment rendered="${!foo || bar}">
       some more html code
    </ui:fragement>
</html>

Using the ui:include for templating results in repeating the DOCTYPE and html tag several times in the source code, which is pretty ugly. (Sure, the user doesn't see, but I'm a fan of tidy html)
However, if I remove the DOCTYPE and html tag from the to-be-included-xhtml, the Faces Servlet throws an exception stating that the prefix ui for ui:fragment is not bound.
Does anybody know, how I can include another XHTML page without the multiple DOCTYPEs and htmls?

A: You should take a look at the ui:composition tag.
We also use ui:include to include jsf2 pages, and to solve the problem you have I believe you could alter your included page by adding the ui:composition tag as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=".." xmlns:ui="..." ...>
    <ui:composition>
    <ui:fragment rendered="${foo}">
       some html code
    </ui:fragement>
    <ui:fragment rendered="${!foo || bar}">
       some more html code
    </ui:fragement>
    </ui:composition>
</html>


text:
Q: Static GCS Website bucket and http root domain not workiing I created a GCS bucket www.example.com and have setup a CNAME record with my DNS provider (DNSimple) to point at c.storage.googleapis.com.  I can now access my domain with www but also want to make the root domain point at the bucket. Reading through threads on the same subject this seems to be possible with a synthetic record (google domains) or ALIAS record (other dns providers). I don't seem to be able to get this to work with DNSimple though so was wondering if anyone can spot my error?
I get the following error when accessing the root domain:
<Error>
NoSuchBucket
<Message>The specified bucket does not exist.</Message>
</Error>

I set my ALIAS record to point my root domain example.com at www.example.com but still no luck. So basically the below two records:
ALIAS   example.com www.example.com
CNAME   www.example.com c.storage.googleapis.com

Am I missing something or is this a limitation of DNSimple as this apparently seems to work with Google Domains (after reading through other questions)?
Just to add the bit from the Google documentation which states the same:

Note: DNS does not support creating a CNAME record on a root domain,
such as example.com, so in most cases, you must create your CNAME
record on a subdomain, such as www.example.com or myblog.example.com.
Some DNS providers offer a non-standard feature that allows a root
domain to be aliased to another name without the use of CNAME. Consult
your DNS provider documentation to determine if such a feature is
available.

A: I am not highly familiar with GCS, as I've used AWS for the same purpose. However, there's a few recommendations:

*

*Make sure to verify the domain

*Make sure you have both the www and apex associated to the bucket/configuration. This is often the missing step. www.example.com and example.com are two different hostname, if you point both DNS records to Google but you configure only www.example.com in your Google Account, then the apex won't work (which may be your scenario).

Finally, I recommend you configure the ALIAS to point to the target (c.storage.googleapis.com) and not to the www local hostname.

A: This was simpler than I thought. Instead of adding an ALIAS record I had to add an URL record pointing example.com at http://www.example.com to make the redirect work.


text:
Q: Can someone explain why the moment of inertia of a circular current carrying loop is $\frac12 mr^2$? Can someone explain why the moment of inertia of this circular current carrying ring about its diameter is $\frac12 mr^2$?

A: Because the moment of inertia is the 2nd moment of the mass distribution, which is fixed at $mr^2$ (all mass is at a distance of $||r||$).
If you pick any 2 orthogonal axes (in the plane of the ring), then that moment is divided between them equally (by symmetry), so for one axis it has to be $\frac 1 2 mr^2$.

A: The moment of inertia of the ring around the axis perpendicular to the ring going through its center is $mr^2$. Let this be $I_z$.
Let the moment of inertia of the ring around the x- and y-axes be $I_x$ and $I_y$, respectively. By symmetry, $I_x = I_y$. By the perpendicular axis theorem, $I_z = I_x + I_y$. Thus $I_x = I_y = \frac 12 mr^2$.


text:
Q: Link Excel sheet to SQL Server Is it possible to link an Excel sheet to a SQL Server database? I want to be able to join the Excel columns to the tables in SQL Server and run queries. I can find plenty of examples to link the tables from SQL Server to Excel, but I want the other way around.
Thank you in advance for any suggestions.

A: Use SQL Server Import and Export Wizard.
Set your worksheet as a Data Source

Excel file path
Specify the path and file name for the spreadsheet
from which to import the data. For example, C:\MyData.xlsx or
\Sales\Database\Northwind.xlsx. Or, click Browse.
Browse
Locate the spreadsheet by using the Open dialog box.
Excel version Select the version of Excel that is used by the source
workbook.


text:
Q: In Grails, how do I combine the head tags of a view and a template? I'm creating a Grails plugin which has a template. The idea is that the developer can just call  and get all of the rendering functionality that I build in the template.
The issue I'm facing has to do with the head tags of both the view and the template. Currently, the template in the plugin has a  tag with multiple JS files. If the developer of another Grails project decides to use <g:render/>and call my template, the head tag of the view is getting replaced by the head tag of the template.
Is there any way to combine the two? Essentially, if view.gsp has a head tag and my own template (pulled in from another plugin) has a head tag, I want them to be combined.

A: From this
http://docs.grails.org/3.1.1/guide/theWebLayer.html#layouts
It shows that you can have the head tag of a template and view exists as long as the :
<g:layoutHead />

is in the head of the template to load the head of the view

8.2.4 Layouts with Sitemesh
Creating Layouts
  Grails leverages Sitemesh, a decorator engine, to support view layouts. Layouts are located in the grails-app/views/layouts directory. A typical

       <title><g:layoutTitle default="An example decorator" /></title>
        <g:layoutHead />

            <g:layoutBody />

The key elements are the layoutHead, layoutTitle and layoutBody tag invocations:

layoutTitle - outputs the target page's title
layoutHead - outputs the target page's head tag contents
layoutBody - outputs the target page's body tag contents


text:
Q: What's an adjective for "alone but not lonely"? I always thought that the adjective for "alone but not lonely" was "lonesome" but apparently "lonely" and "lonesome" mean the same thing:
What's the difference between "lonely" and "lonesome"
Is there an adjective for somebody who's alone but not... sad? For example, I'm an introvert. I've been telling people that I'm a lonesome person because I prefer being alone. Being alone does not make me feel lonely. However, now that I learned that "lonesome" and "lonely" mean the same thing I'm wondering what adjective I'd use in place of "lonesome".

A: (1) An apt adjective is self-contained which means quietly confident and self-sufficient, comfortably alone in a positive sense.

adjective: self-contained
1.(of a thing) complete, or having all that is needed, in itself.
"every section of the painting is a self-contained unit"
synonyms:   complete, independent, separate, free-standing, enclosed
2. (of a person) quiet and independent; not depending on or influenced by others.
"he's very self-contained"

https://www.google.co.in/search?client=ms-android-samsung&ei=XD8qWdHSJ8eAvwSMxZXAAw&q=self-contained&oq=self-contained
(2) a good concept for your personal use: Aloneness is a word specifically used to mean 'alone' in a positive sense. Even if defined negatively as a synonym of solitude or loneliness in some standard dictionaries, it is used self-affirmingly as a contrast to loneliness which has negative connotations.
My sister who is an expert psychologist and ace in spirituality has suggested this word (which I had never heard of till now!) AND confirmed the positive connotation and usage of 'aloneness' as a positive attitude to being alone.
Example of usage: Loneliness vs. Aloneness: What's the Difference?
By Pragito Dove at Huffpost blog (These are not definitions but contrasting interpretations by the author.)

Loneliness is a lack, a feeling that something is missing, a pain, a depression, a need, an incompleteness, an absence.
Aloneness is presence, fullness, aliveness, joy of being, overflowing love. You are complete. Nobody is needed, you are enough.

My sister (who is herself an extrovert, but spiritual) asked me in relation to this question, "why should being alone be perceived as being lonely? When I am alone I am with myself."
I suspect that spiritually advanced people have reclaimed and redefined the word 'aloneness' specially to counter the negative connotations acquired by 'loneliness' because of the herd mentality that 'man is / must be a social animal.' However this word is not yet widely used and may only convey the meaning of loneliness if you use it to describe yourself to others, unless you are willing to explain its positive connotations.
See this article for the full text of the above extract:
http://m.huffpost.com/us/entry/8032702

A: I would say self-sufficient here. This word has positive meaning and it could work in the described situation.

A: I believe solitary fits the bill...

: not gregarious, colonial, social, or compound

Most cats are solitary creatures.

from m-w.com

A: It's a noun, not an adjective, but you could use the term loner to convey your meaning. From Cambridge Dictionaries:

someone who prefers to be alone and to do things without other people

I think this most strongly conveys the fact that when you are alone it is by choice, and that you find the solitary state comfortable rather than lonely. It's also a term that has some fairly positive connotations, at least in US culture, conjuring up heroes who always stand a little bit apart, from John Wayne to Bruce Wayne. There's a certain "cool" factor to being a loner, as Pee-Wee Herman knew. (However, negative connotations of anti-social-ness also apply; see for example Batman, above.)
And if you really need an adjective, at a pinch you can use it attributively. For example:

So, the question is, for a loner engineer with no need to worry about distribution, supply, and other such factors, what materials common in our modern world would be rendered useless? ("What materials in modern culture would be useless to an engineer ahead of his time?", WorldBuilding SE)
And how do you develop a happy loner personality? ("I Am a Loner: The Happy Loner Personality", HealDove.com, January 10 2017)

So you could say things like:

I'm not lonely, I'm just a loner.
Eh, I'm not really up for the office holiday party. You know me, I'm kind of a loner.
I'm the loner-type, I don't do well in crowds.

Or, of course,

"You don't wanna get mixed up with a guy like me. I'm a loner, Dottie. A rebel." (Pee-Wee's Big Adventure)

A: I'd suggest solo. Often used in contexts such as "solo bushwalk", "solo bike ride". "Going solo" has, if anything, positive connotations of self-reliance and independence.

(adjective) alone; without a companion or partner:

http://www.dictionary.com/browse/solo (def #10)
Here's an article entitled "When solo travel feels lonely", which seems to confirm that "solo"-ness is not, by default, lonely.

A: How about "lone". There's the "Lone ranger" and there's also the "Lone Star State"

A: How about "on my own"? That seems to me to not have negative connotations.
True, "solo" can be seen as positive, too, but it seems to suit only activities rather than just states of being. You might say "I live on my own" or "I've spent the last few days on my own".

A:
Independent
indəˈpendənt/
adjective

*

*free from outside control; not depending on another's authority.

*not depending on another for livelihood or subsistence.

Or

Individualistic
indivij(o͞o)əˈlistik/
adjective

*

*characterized by individualism; independent and self-reliant.

*marked by or expressing individuality; unconventional.

Or

Recluse
rek-loos, ri-kloos/
noun

*

*A person who lives in seclusion or apart from society, often for religious meditation.

adjective
Also reclusive.

*

*shut off or apart from the world; living in seclusion, often for religious reasons.

*characterized by seclusion; solitary.

A: Think about solitude. It is a nice word, which perfectly describes the state of a person. Also good versions are on my own and solo.

A:
lone wolf
  :  a person who prefers to work, act, or live alone
  - https://www.merriam-webster.com/dictionary/lone%20wolf

Normally a noun, but at a stretch you could use it as an adjective e.g. "A lone wolf guy"

A: Phrases I've heard used for this with positive connotations:

*

*"I enjoy (or prefer) solitude."

*"I highly value my alone-time."
But not....

*

*"I really don't like people very much. In fact, would you please leave?"

A: One might say "single" or "singular," but I'm not sure that fits your connotation.
How about one of the following? by oneself, on one's own, solitary, singly, solo, solus (my favorite for what I think you mean); unescorted, unaccompanied, partnerless, companionless (thank you Apple thesaurus).

A: Can fit couple of more related adjectives :

*

*restrained

*Close-mouthed

A: Solace may convey less negative connotations than solitude.
Definition from Oxford Dictionaries):

comfort or consolation in a time of distress or sadness.

This one explicitly states not being lonely, but implies being alone, whereas solitude implies being not lonely but explicitly states being alone.

A: Solitary and Solo are good options as others have mentioned.
Culturally, English has a slightly negative connotation for words that relate to removing oneself from society. So, it'll be a bit difficult to find one single adjective to encompass that in place of a more descriptive sentence.
Since you're introverted, a good description could be that you prefer solitude, as someone else suggested. This indicates a peaceful, quiet environment where you're by yourself, rather than one in which you have forcefully been removed (see Isolated) or have removed yourself for antisocial reasons (see Reclusive).
Another word that may suit your needs even better is "Unaccompanied." If you prefer to go out or be by yourself, you can say you prefer to go/be unaccompanied, for example. It's simple, clear, and to the point without necessarily conveying sadness or loneliness!

A: Monkish or hermitic is where one found (or trying to find) peace within oneself, so one isn't lonely but alone.

A: I guess "misanthropic" could be going just a bit too far. However if you do not like to be with other people, it can only be that you are antisocial. There times when we all like to be alone but if it is a permanent condition with a person it can only mean that you don't like the company of others. I think "misanthropic" would suit.


text:
Q: XPATH - Ignore 1 page element, grab the rest I can't seem to figure this out due to the square brackets issue. I have an html page full of h3 tags with hrefs that I need to grab but one has a class on that I don't want. Example:
I want all H3s hrefs but not this one:

Leave me alone!

To grab all the hrefs I am using this:
//h3/a/@href

Tried a few variations but no luck.
REMOVED CONFUSING EXAMPLE, APOLOGIES


text:
Q: Computer only detects SSD after booting twice This is a problem I have been having for years on an old laptop that I don't use anymore, but it wasn't a big deal to me so I never bothered to fix it. I just recently put Windows 10 on it for my parents to use, and I'd rather fix the problem before I give it to them. When I used the laptop I had it on Linux Mint and I had the same problem, so it isn't OS related.
I removed the hard drive of my laptop (HP Probook 4330s) to put in a 64GB SSD (OCZ Vertex 4).
Since then, when I boot the laptop, it tells me "BootDevice not found", I press Escape, it restarts, tells me to press Escape to continue booting, and then boots normally (here's a gif to make it clear: https://imgur.com/zeRfTN7).
It's like the drive takes too long to start and isn't detected the first time it boots (which I find weird for an SSD).
I've tried to change most options in the BIOS settings, but I never see any change (here are the BIOS settings: https://imgur.com/a/r6zqxH1).
I also just flashed the BIOS to the latest version I could find on HP's website, but I don't see any difference.
And something else that I just noticed on Windows 10, if I try to put the computer to sleep, it won't be able to restart. It will just say "your computer encountered a problem" and restarts a few times doing checks on the drive. I assume it's linked to the first problem, something about the disk.
Any ideas?
Thanks


text:
Q: Elements don't take FallbackValues (for the Style properties) I'm facing a problem with a UserControl development.
The UserControl exposes a couple of DPs (of the Style type). The UserControl's elements bind their's Style properties to them. In order to show something if Styles are not defined by the user, the UserControl provide FallbackValues (Styles defined in the UserControl.Resources section) for those bindings. The issue is that the only one of the UserControl's elements take the FallbackValue, the others - not. It seems like something just overrides FallbackValues.
Moreover, the VS designer show the UserControl itself normally (I mean, it seems that FallbackValues are taken properly). But when the UserControl resides in the other UserControl or a Window I see the behaviour descibed previously.
Here is the xaml of the UserControl:
<UserControl
Background="White" Style="{Binding UserControlStyle}"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<UserControl.Resources>
    <LinearGradientBrush x:Key="GeneralKeyBackground" StartPoint="0.5,0" EndPoint="0.5,1">
        <GradientStop Offset="0" Color="#FFA0A9B2" />
        <GradientStop Offset="1" Color="#FF5B626A" />
    </LinearGradientBrush>

    <LinearGradientBrush x:Key="StationNameBackground" StartPoint="0.5,0" EndPoint="0.5,1">
        <GradientStop Offset="0" Color="#FFC4E3FF" />
        <GradientStop Offset="0.462" Color="#FFE7F3FF" />
    </LinearGradientBrush>

    <Style x:Key="DefaultStationNameForSearchingStyle" TargetType="TextBox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <TextBox TextAlignment="Center" Text="{TemplateBinding Text}"
                                 Background="Transparent" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="FontSize" Value="22" />
        <Setter Property="Foreground" Value="Black" />
    </Style>

    <Style x:Key="DefaultButtonsStyle" TargetType="customControls:RoundButton">
        <Setter Property="Template" Value="{DynamicResource RoundButtonTemplate}" />
        <Setter Property="Width" Value="85" />
        <Setter Property="Height" Value="75" />
        <Setter Property="FontFamily" Value="Verdana" />
        <Setter Property="FontSize" Value="22" />
        <Setter Property="Background" Value="{StaticResource GeneralKeyBackground}" />
        <Setter Property="Foreground" Value="White" />
        <Style.Triggers>
            <Trigger Property="IsEnabled" Value="false">
                <Setter Property="Foreground" Value="Gray" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <DataTemplate x:Key="StationTemplate">
        <customControls:RoundButton MinWidth="350" MinHeight="60" DataContext="{Binding}" Content="{Binding }" />
    </DataTemplate>

    <Style x:Key="DefaultTitleStyle" TargetType="TextBlock">
        <Setter Property="Control.FontSize" Value="48" />
        <Setter Property="Control.Foreground" Value="Black" />
    </Style>

    <Style x:Key="DefaultStationNameForSearchingBorderStyle" TargetType="Border">
        <Setter Property="BorderBrush" Value="#FF2C8BF5" />
        <Setter Property="Background" Value="{StaticResource StationNameBackground}" />
    </Style>
    <!-- EndRegion -->

</UserControl.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBlock Text="Select Station"
               Style="{Binding TitleStyle, FallbackValue={StaticResource DefaultTitleStyle}}" />

    <userControls:ScrollableWrapPanel x:Name="StationsPanel" Grid.Row="1"  ItemsSource="{Binding FilteredStations}"
                                      ItemTemplate="{StaticResource StationTemplate}"
                                      ButtonsStyle="{StaticResource DefaultButtonsStyle}" />

    <Border Grid.Row="2" MinWidth="460" MinHeight="65"
            Style="{Binding StationNameForSearchingBorderStyle, FallbackValue={StaticResource DefaultStationNameForSearchingBorderStyle}}">
        <TextBox x:Name="StationName" Width="420" Height="55" SelectionChanged="TextBoxBase_OnSelectionChanged"
                 Style="{Binding StationNameForSearchingStyle, FallbackValue={StaticResource DefaultStationNameForSearchingStyle}}" />
    </Border>

    <Border Grid.Row="3" Style="{Binding KeyboardBorderStyle}">
        <virtualKeyboard:VirtualKeyboard x:Name="VirtualKeyboard"
                         GeneralKeyStyle="{Binding KeyboardButtonsStyle, FallbackValue={StaticResource DefaultButtonsStyle}}"/>
    </Border>
</Grid>

VirtualKeyboard buttons take the FallbackValue always, it just works. The others are not.
What can you advice to debug this very strange behaviour?

A: The documentation for BindingBase.FallbackValue states
A binding returns a value successfully if:

*

*The path to the binding source resolves successfully.

*The value converter, if any, is able to convert the resulting value.

*The resulting value is valid for the binding target (target) property.
If 1 and 2 return DependencyProperty.UnsetValue, the target property is set to the value of the FallbackValue, if one is available.
So, if any of your DependencyProperties are being set or returning a [null] value, it will be considered a valid bind and the FallbackValue will not be used.
I do not know if this is your problem as I would need to see more of your solution, but it would be worth checking into.
I hope this helps.

A: Like @EngineerSpock said in the comments above, use TargetNullValue instead.


text:
Q: REDIS Error: ERR unknown command `CONFIG when trying to set dir I'm trying to run the following
redis-cli --raw -a '<password censored>' 'CONFIG SET dir /var/www/html'

However I keep getting:
ERR unknown command `CONFIG SET dir /var/www/html`, with args beginning with:

Any advice?


text:
Q: Easy way to change Firemonkey button pressed color on Android This might be one of those forehead-slapping questions, but what I want to do, is make my buttons show orange (xFFFCB447) when they are pressed, just like the Android dialogs do. (picklist for example)
There doesn't seem to be a specific "pressed" TRectangle in the Default Style, and my adding different TRectangles (coloured appropriately doesn't seem to do it either), so my only alternative seems to be to use the Bitmap Style designer to Export the style.png; hope I figure out which part of the image is used for the button pressed before tomorrow afternoon, and Update the image again.
Is there not an easier/quicker way to do it?

A: Option A) Drop a TRectangle on your button. Set it's Align to Contents. Set it's fill color to Orange. Set it's Opacity to 0.50. Set it's HitTest to False. Set it's Visible to False. In the TButton.OnMouseDown set the TRectangle Visible to True. In the TButton.OnMouseUp set the TRectangle Visible to False. You will also need to set the OnMouseMove of the control that TButton is on to set TRectangle Visible to False as well so if you mouse down and then move away it will be hidden as well.
Option B) Drop a TFillRGBEffect on the TButton. Set it to Orange. Do the same as above to enable and disable the effect on mouse down and up. However, be aware that TFillRGBEffect may be slower than the TRectangle way.
Option C) Just use a TRectangle instead of a TButton. Put a TText or TLabel inside it for the text and align to Contents. Change it's Fill color in OnMouseDown and OnMouseUp.


text:
Q: Trying to horizontally align and center an image next to a div Would love to have a way to center and horizontally align my header image with the div holding my social media and statement next to it. For the life of me I can't figure it out.
You will see that inside the social div I have my links butted up next to each other but I don't know how to accomplish all this centering simply. Here's the code:

My Social Handle

CSS:
header {
    margin:10px auto 0px auto;
    background-color:blue;
    line-height: 0px;
    text-align:center;
    clear:both;
    position:relative;
    }

.hdrimg {
    display:block;
    font-family: arial, helvetica, sans-serif;
    font-size: 12pt;
    font-style: italic;
    font-weight: regular;
    letter-spacing: 1px;
    background-color: red;
    float:left;
    }

#social {
    text-align:center;
    margin: 0px;
    padding: 0px;
    vertical-align:middle;
    background-color:red;
    float:right;
    }

img.twitter{
    position:absolute;
    top:0px;
    left:0px;
}
img.facebook{
    position:absolute;
    top:40px;
    left:40px;
}
img.linkedin{
    position:absolute;
    top:40px;
    left:0px;
}
img.google{
    position:absolute;
    top:0px;
    left:40px;
}

#social p{
    display:inline-block;
    vertical-align:middle;
    position:absolute;
    top: 25px;
    left: 80px;
}

A: It's always the same trick for vertically centering elements in other elements.
take a look here.
You need to create an empty span before the element you want to center.
this empty span will be called the Centerer.
give the Centerer display:inline-block; height:100%; vertical-align:middle;
and for the element you want to center, give display:inline-block; vertical-align:middle;
It's as simple as that.
Edit:
This method don't make you specify any static width (px, or even %).
so your layout stays very flexible.
now that you can verticaly align anything within everything..
you can create a simple layout that will achive your header problem.
Edit 2
I've created your layout for you.
as you can see.. its a very simple one (I'm using the vertical alignment trick).
http://jsfiddle.net/avrahamcool/N5Q2W/2/
now take this basic layout, and aplly your css to it.


text:
Q: Why is my PayPal IPN script failing? I'm developing a lightweight e-commerce solution that uses PayPal as the payment gateway. However, my IPN callback is constantly returning an INVALID response. I even tried using the sample PHP script provided by PayPal:
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
  $value = urlencode(stripslashes($value));
  $req .= "&$key=$value";
}

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];

if (!$fp) {
  // HTTP ERROR
}
else {
  fputs ($fp, $header . $req);
  while (!feof($fp)) {
    $res = fgets ($fp, 1024);
    if (strcmp ($res, "VERIFIED") == 0) {
      // check the payment_status is Completed
      // check that txn_id has not been previously processed
      // check that receiver_email is your Primary PayPal email
      // check that payment_amount/payment_currency are correct
      // process payment
    }
    else if (strcmp ($res, "INVALID") == 0) {
      // log for manual investigation
    }
  }
  fclose ($fp);
}

But as I say, I keep getting an INVALID response. This is in fact the response I get using a PHP class that writes the response to a log file:
[2011-06-02 19:18:49] - FAIL: IPN Validation Failed.
IPN POST data from PayPal:
test_ipn=1,
payment_type=instant,
payment_date=11:07:43 Jun 02, 2011 PDT,
payment_status=Completed,
payer_status=verified,
first_name=John,
last_name=Smith,
payer_email=buyer@paypalsandbox.com,
payer_id=TESTBUYERID01,
business=seller@paypalsandbox.com,
receiver_email=seller@paypalsandbox.com,
receiver_id=TESTSELLERID1,
residence_country=US,
item_name1=something,
item_number1=AK-1234,
quantity1=1,
tax=2.02,
mc_currency=USD,
mc_fee=0.44,
mc_gross=15.34,
mc_gross_1=12.34,
mc_handling=2.06,
mc_handling1=1.67,
mc_shipping=3.02,
mc_shipping1=1.02,
txn_type=cart,
txn_id=4362187,
notify_version=2.4,
custom=xyz123,
invoice=abc1234,
charset=windows-1252,
verify_sign=AjbdIvvDAW2fh1O9jAbEym4myX.WAV7-jCEiEWMqoSkewvM6L3Co6oUQ

This is from the official PayPal IPN test tool. So something between PayPal's sample code and test tool is causing my script to fail. Any one have any ideas?

A: what is encoding of your html/php page ? (charset=windows-1252) ?


text:
Q: Running code between certain times I have php code that is suppose to run between 04:00am and 05:00am but it does not run, i cant see the problem with this?
  $begin = new DateTime('04:30');
    $end = new DateTime('05:00');

    while (!connection_aborted() || PHP_SAPI == "cli") {
        $now = new DateTime();

    if(date("Hi") <= $begin && date("Hi") >= $end){
    //run code
    }

}

A: Your problem lies here:
if(date("Hi") <= $begin && date("Hi") >= $end){

You are trying to do "greater than" and "less than" comparisons on strings. You should use the integer values (epoch time) then you can do this.
if(time() >= strtotime('14:00') && time() <= strtotime('15:00')) {
    echo 'In Range2';
} else {
    echo 'out of range2';
}

Note: This is for between 2:00pm and 3:00pm just to show it works (it currently is 2:00pm where I am located).
Demo: https://3v4l.org/NhnfM


text:
Q: Can outside matter decrease the event horizon size of a black hole? My question is related to this one, but no one actually answered his question.
The event horizon is where gravity from the singularity is so strong that nothing can escape. Assume you're located directly at the event horizon. Now assume another massive body (not necessarily another black hole) was placed above you. Shouldn't the gravity from that body "help you escape" and lower the event horizon in that spot? I know GR is different from simply adding forces, so what would really happen?


text:
Q: Sandbox Node.js child_prosess I'm creating a manager to run indiviual Node.js apps in a shared enviorment.
I have this master.js:
var spawn = require('child_process').spawn,
  _ = require('underscore');

var env = {
  PORT: 3001
}

_.extend(env, process.env);

var child = spawn('node', [ 'child.js' ], {
  env: env
});

// trying to get something like this to work
child.on('bindtoaport', function (port) {
  if (port !== env.PORT) {
    child.kill();
  }
});

The last statement, obviously, does not exist. I want to intercept the system call (before it reaches the system), see which port it will bind to, and then kill it if it's the wrong port.
Is this possible in vanilla node.js? or does it require some crazy binding to some native OS module?


text:
Q: CSS: Social Icons show a different text color than the one I have set I have created social icons using w3schools and when pasting the code into my sidebar widget the text within the icons shows black instead of white.
This is my code:

.fa {
  padding: 15px;
  font-size: 30px;
  width: 30px;
  text-align: center;
  text-decoration: none;
  margin: 5px 3px;
  border-radius: 50%;
}

.fa:hover {
  opacity: 0.7;
}

.fa-facebook {
  background: #3B5998;
  color: white;
}

.fa-instagram {
  background: #E1306C;
  color: white;
}

.fa-pinterest {
  background: #cb2027;
  color: white;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Thanks for your help!

A: You've used hover. Remove this to get same color which you've given in CSS.
.fa:hover {
    opacity: 0.7;
}

A: I've tested your code and it seems to work correctly outside the side-bar.
So the problem might be the side-bar-widget. Do you wrote the widget yourself?
If not, maybe there is a default-style for a-tags in your sidebar that over-writes your color. You could change that, if possible.
Another way would be to increase the specificity of your css, for example by using:
a.fa-facebook {
  background: #3B5998;
  color: white;
}

If nothing helps, you could try adding an important-statement to your color:
.fa-facebook {
  background: #3B5998;
  color: white !important;
}

But use !important with care, it is not considered best-pracitce.