Q: How do I make a Two argument python function? Is anyone able to help me on the below, I am struggling to understand what the question means by "where {person} is replaced by the first name in the visitors to be identified as a member." The below code is my attempt but I am not sure how to incorporate visitors into the function too...
members = ['Danny', 'Alex', 'Kieran', 'Zoe', 'Caroline']
visitors = ['Scott', 'Helen', 'Raj', 'Danny']

def check_group(members,visitors):
for m in members:
    if m == 'Danny':
        return f'Member present: {m}.'
    else:
        return 'No members.'

check_group(members, visitors)

A: You have to loop over the visitors and then check if the visitor is a member. If you reach the end of the loop you haven't found any member and return "No members".
members = ['Danny', 'Alex', 'Kieran', 'Zoe', 'Caroline']
visitors = ['Scott', 'Helen', 'Raj', 'Danny']

def check_group(members, visitors):
    for visitor in visitors:
        if visitor in members::
            return f'Member present: {visitor}.'
    return 'No members.'

check_group(members, visitors)


Q: Justifying differentiation under the integral sign with Dominated Convergence Problem: Justify why you can use differentiation under the integral to differentiate:
$$ I(t) := \int_{(0,\infty)}e^{-tx} \, m(dx).$$ Then use $I(t) = 1/t$ to show for all $n \in \mathbb{N}$ that $$
\int_{(0,\infty)} x^ne^{-x} \,m(dx) = n!\, .$$
Attempt: We have that: $$ \dfrac{d}{dt} I(t) = \lim_{h \rightarrow  0} \dfrac{I(t+h) - I(t)}{h} = \lim_{h \rightarrow 0} \int_{(0,\infty)} e^{-tx}\left( \dfrac{e^{-hx}-1}{h}\right). $$ Since $\mathbb{R}$ is separable, it suffices to consider a sequence $\{h_n\}_{n \in \mathbb{N}}$ with $h_n \rightarrow 0$ as $n \rightarrow \infty$. Then, we consider: $$ \lim_{n \rightarrow \infty} \int_{0,\infty)} e^{-tx}\left( \dfrac{e^{-h_nx}-1}{h_n}\right)$$ and presuming that $\left| e^{-tx}\left( \dfrac{e^{-h_nx}-1}{h_n}\right) \right|$ is bounded by an integrable function for all $n$, we may apply the Dominated Convergence Theorem to swap the integral sign and the limit.
Question: What can I use to bound $\left| e^{-tx}\left( \dfrac{e^{-h_nx}-1}{h_n}\right) \right|$? Certainly we can't use $e^x$ or just $e$, since neither is integrable on $(0, \infty)$. Any suggestions?

A: One can check that $e^u\geq 1+u$ for all $u\in\mathbb{R}$, hence $1-e^u\leq -u$. Applying this with $u=-h_nx$, we obtain
$$ \Big|\frac{e^{-h_nx}-1}{h_n}\Big|=\frac{1-e^{-h_nx}}{h_n}\leq \frac{h_nx}{h_n}=x $$
if $h_n>0$, and
$$ \Big|\frac{e^{-h_nx}-1}{h_n}\Big|=\frac{e^{-h_nx}-1}{-h_n}=\frac{1-e^{-h_nx}}{h_n}\leq \frac{h_nx}{h_n}=x $$
if $h_n<0$.
Therefore
$$ \Big|e^{-tx}\frac{e^{-h_nx}-1}{h_n}\Big|\leq xe^{-tx} $$
which is integrable on $(0,\infty)$ if $t>0$.


Q: modify url by clicking a div I have a page in php, and I'm trying to add an ?id=variable_value extension to it's url when I click on a div, but when I click it gives me an undefined url error with the extension
Here is the script:

And the div :

A: Don't use two separate ways of attaching handlers when you only need one. Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead.
The problem is that when assigning the handler via onclick, the this in changeUrl is undefined, because the calling context is global. Feel free to avoid using this when it can cause confusion.
Just use addEventListener alone. Also, you'll have to use getAttribute('href') instead of .href because divs are not supposed to have href properties.

const Pokemon_ID = '5';
document.getElementById('right-btn').addEventListener('click', function(e) {
  // location.href = e.target.getAttribute('href') + '?id=' + Pokemon_ID;
  console.log('changing URL to ' + e.target.getAttribute('href') + '?id=' + Pokemon_ID);
});

text

A: Try this instead:
location.href += '?id=' + Pokemon_ID;

A: Because you call changeUrl() within the onclick method you loose the context of this. This in changeUrl is not your div. Maybe you have to pass this into the method with changeUrl(this) or you just pass the href with changeUrl(this.href).
Than use:
function changeUrl(target){
location.href=target.href+'?id='+Pokemon_ID;
}

A: As mentioned by CertainPerformance above, you are not passing the right arguments to you function to work correctly; Using you code as a reference, you can either pass the original event to you changeUrl() function, then use the e.target to get to your 'right-btn' element.
Javascript:
var Pokemon_ID = 1;

function changeUrl(e) {
     var href = e.target.getAttribute('href');
     console.log(href +'?id=' + Pokemon_ID);
     return false;
 }

 document.getElementById( 'right-btn' ).onclick = function(e) {
     changeUrl(e);
 };

HTML:

Click Me 4

However, if you realy want to use this in your function to refer to the 'right-btn' element, then you can change the code to;
Javascript:
var Pokemon_ID = 1;

function changeUrl() {
     var href = this.getAttribute('href');
     console.log(href +'?id=' + Pokemon_ID);
     return false;
 }

 document.getElementById( 'right-btn' ).onclick = function(e) {
     changeUrl.call(e.target);
 };

The changes being the call in the event handler:
changeUrl.call(e.target);, which calls you function in the 'context' of the e.target, making the this in your changeUrl() function to the element. Then you can use the this as in var href = this.getAttribute('href');


Q: Bootstrap tagsinput + typeahead Есть текстовая форма, где введённые пользователем значения превращаются в теги (tagsinput). При вводе снизу появляется подсказка (typeahead).
Позже я получаю из этого поля массив значений и сохраняю в базу. Всё работает отлично и как нужно, однако при клике в подсказку, появляющуюся снизу или при нажатии enter (в обоих случаях введённое значение превращается в тег) в консоль валится ошибка:

bootstrap3-typeahead.min.js:1 Uncaught TypeError: Cannot read property
  'apply' of undefined

Связка typeahead + tagsinput для данного поля настроена так:
$($myField).tagsinput({
            itemValue: 'id',
            itemText: 'name',
            typeahead: {
              displayKey: 'name',
              source: data['security_list']
            }
          });

где 'id', 'name' - названия соответствующих атрибутов из справочника, который загружен в виде JSON.
Среда: backbone, все разбито по модулям, которые грузятся через require. (если данные о среде тут вообще нужны)
Где выпрямлять руки?


Q: Is it safe to use integers as hash keys? Is it safe to use integers as hash keys?
my %hash;
my $str = ...

for $str.NFC {
    %hash{$_} = ...
}

A:
A normal Hash coerces all its keys to strings:
my %a = '1' => 'foo', 2 => 'bar';

say %a.pairs.perl;  # ("1" => "foo", "2" => "bar").Seq

Note how the second key became the string "2", even though it was originally passed to the Hash as an integer.
When you do hash look-ups, the subscript is also automatically converted to a string before it is used:
say %a{"2"}.perl;   # "bar"
say %a{2}.perl;     # "bar"

Note how the subscript 2 correctly found the element with key "2".
The conversion from integers to strings is well-defined in Perl 6, yielding a unique string for each unique integer, so the example you gave is fine.

If you don't want your Hash keys to be converted to strings, you can override the key handling using the {} notation in the declaration:
my %b{Any} = '1' => 'foo', 2 => 'bar';

say %b.pairs.perl;  # ("1" => "foo", 2 => "bar").Seq

say %b{"1"}.perl;   # "foo"
say %b{1}.perl;     # Any

say %b{"2"}.perl;   # Any
say %b{2}.perl;     # "bar"

Note how in this case the second key 2 stays an integer, and doing a look-up with the string subscript "2" does not find it, nor does the subscript 1 find the entry with key "1".
%b{Any} means "accept keys of any type, and don't coerce them". This is sometimes called an 'object Hash' because it can map from any object to a value.
%b{Int} would mean "accept only Int keys, and don't coerce them". In this case you'll get an error if you even try to use anything that isn't already an Int.


Q: Save Visual Studio Build Configuration Currently I use Visual Studio 2013 and I want to use my own build configuration (like Debug or Release for example) which I've created in project A, in project B. Is there a possibility to save and import a build config in general and to use it in other projects?
Jonas

A: To my understanding, this is not possible directly, as the representation of the configuration is implicitly represented in the solution file (*.sln) and the project file (*.vcproj) by its name and conditions; however, similar to the answer to this question, the project files can be edited manually and similar parts can be factored out using the Import element, which is documented here.


Q: Android camera doesn't work after cordova compile I just compiled my cordova project to a .apk for android. You can open the (android) camera with a button.
When I was debugging my project the camera opened when you clicked on said button, but after compiling the project and installing it on my android smartphone, it wouldn't open the camera anymore.
Do you know how to make sure the camera opens, if you need more information, please let me know.
The camera opens with this code
HTML
<button onclick="capturePhotoWithData()">Capture Photo With Image Data</button>

Javascript / JQuery
function onPhotoDataSuccess(imageData) {
    var smallImage = document.getElementById('smallImage');
    smallImage.style.display = 'block';
    smallImage.src = "data:image/jpeg;base64," + imageData;
}

function onFail(message) {
    alert('Failed because: ' + message);
}

function capturePhotoWithData() {
    navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
}


Q: RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback): initialization failed Goal: Run a GPT-2 model instance.
I am using the latest Tensorflow and Hugging Face  Transformers.

*

*Tensorflow - 2.9.1

*Transformers - 4.21.1

Notebook:
pip install tensorflow

pip install transformers

from transformers import pipeline, set_seed

generator = pipeline('text-generation', model='gpt2')
set_seed(42)

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
ImportError: numpy.core.multiarray failed to import

The above exception was the direct cause of the following exception:

SystemError                               Traceback (most recent call last)
SystemError: <built-in method __contains__ of dict object at 0x7f5b58a64d00> returned a result with an error set

The above exception was the direct cause of the following exception:

ImportError                               Traceback (most recent call last)
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
   1001         try:
-> 1002             return importlib.import_module("." + module_name, self.__name__)
   1003         except Exception as e:

~/anaconda3/envs/python3/lib/python3.8/importlib/__init__.py in import_module(name, package)
    126             level += 1
--> 127     return _bootstrap._gcd_import(name[level:], package, level)
    128

~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _gcd_import(name, package, level)

~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _find_and_load(name, import_)

~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _load_unlocked(spec)

~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap_external.py in exec_module(self, module)

~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/__init__.py in <module>
     36 from ..utils import HUGGINGFACE_CO_RESOLVE_ENDPOINT, http_get, is_tf_available, is_torch_available, logging
---> 37 from .audio_classification import AudioClassificationPipeline
     38 from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/audio_classification.py in <module>
     19 from ..utils import add_end_docstrings, is_torch_available, logging
---> 20 from .base import PIPELINE_INIT_ARGS, Pipeline
     21

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/base.py in <module>
     33 from ..feature_extraction_utils import PreTrainedFeatureExtractor
---> 34 from ..modelcard import ModelCard
     35 from ..models.auto.configuration_auto import AutoConfig

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/modelcard.py in <module>
     43 )
---> 44 from .training_args import ParallelMode
     45 from .utils import (

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/training_args.py in <module>
     25 from .debug_utils import DebugOption
---> 26 from .trainer_utils import (
     27     EvaluationStrategy,

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/trainer_utils.py in <module>
     46 if is_tf_available():
---> 47     import tensorflow as tf
     48

~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/__init__.py in <module>
     36
---> 37 from tensorflow.python.tools import module_util as _module_util
     38 from tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader

~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/__init__.py in <module>
     36 from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
---> 37 from tensorflow.python.eager import context
     38

~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/eager/context.py in <module>
     34 from tensorflow.python import tf2
---> 35 from tensorflow.python.client import pywrap_tf_session
     36 from tensorflow.python.eager import executor

~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/client/pywrap_tf_session.py in <module>
     18 from tensorflow.python import pywrap_tensorflow
---> 19 from tensorflow.python.client._pywrap_tf_session import *
     20 from tensorflow.python.client._pywrap_tf_session import _TF_SetTarget

ImportError: initialization failed

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_4924/2487422996.py in <cell line: 1>()
----> 1 from transformers import pipeline, set_seed
      2
      3 generator = pipeline('text-generation', model='gpt2')
      4 set_seed(42)

~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _handle_fromlist(module, fromlist, import_, recursive)

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in __getattr__(self, name)
    990             value = self._get_module(name)
    991         elif name in self._class_to_module.keys():
--> 992             module = self._get_module(self._class_to_module[name])
    993             value = getattr(module, name)
    994         else:

~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
   1002             return importlib.import_module("." + module_name, self.__name__)
   1003         except Exception as e:
-> 1004             raise RuntimeError(
   1005                 f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
   1006                 f" traceback):\n{e}"

RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback):
initialization failed

def query(payload, multiple, min_tokens, max_tokens):
    nlp_setup()
    list_dict = generator(payload, min_length=min_tokens, max_new_tokens=max_tokens, num_return_sequences=multiple)
    return [d['generated_text'].split(payload)[1].strip() for d in list_dict

output = query("Banking customer's needs:", 3000, 50, 50)

RunTime, SystemError and ImportError all occur during import of transformers:
RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback): initialization failed

A: Changed Kernel: conda_tensorflow2_p38


Q: Storing references to components created at runtime Given the following Blazor component:
@foreach (var col in columns)
{
    @foreach (row in rows)
    {
        <MyInput @onkeydown="KeyDown" @ref="NewInput"></MyInput>
    }
}

@code {
    private List<MyInput> inputs = new List<MyInput>();

    private MyInput NewInput
    {
        get { return _NewInput; }
        set
        {
            _NewInput = value;
            inputs.Add(_NewInput);
        }
    }
    MyInput _NewInput;

    private async Task KeyDown(KeyboardEventArgs args)
    {
        if (args.Code == "ArrowDown")
        {
            //TODO: Find out which dynamic MyInput-instance
            //      within the inputs collection triggered the event
        }
    }
}

I'm trying to add cursor navigation between the MyInputs using the arrow keys. For this to work, I obviously need to know which MyInput component triggered the key-event.
I managed to store all MyInput instances into a List by abusing the @ref property, but I can't figure out which instance within my list triggered the event.
Does Blazor offer any way to find out which dynamically created MyInput-instance triggered the event?

A: Suppose you've defined a component named"
ChildComponent.razor

@ID.ToString()

@code {

    [Parameter]
    public int ID { get; set; }

}

Which has a parameter property ID, provided by the parent component, like this:
ParentComponent.razor
@for (int i = 0; i < 10; i++)
{
    <ChildComponent @ref="component" ID="i" />
}

@code
{
    private ChildComponent component { set => components.Add(value); }

    List<ChildComponent> components = new List<ChildComponent>();

    protected override void OnInitialized()
    {
        foreach (var component in components)
        {
           Console.WriteLine(component.ID);
        }
    }
}

Now, you can identify the component by its ID. A simple and effective way, though you may do that in other ways.
Note: This is wrong:
<MyInput @onkeydown="KeyDown" @ref="NewInput"></MyInput>

because you assign the name of a method, the "KeyDown", to the @onkeydown compiler directive, which is only applicable to Html tags, not to component.
You can do something like this:
<MyInput ID="id" @ref="NewInput"></MyInput>

ID should be a parameter property defined in MyInput component, which is a child component, mind you. You also have to define an EventCallback which should be triggered from an event handler for the keydown event. In the cuurent case the EventCallback should return to the parent component, the ID of the child component in whose html tag, say an input html element, the keydown event occurs. I hope you succeed to get what I'm saying... if not, don't hesitate to ask questions.
UPDATE:
Note: I've added some code to my previous code sample to demonstrate how to return the ID of each ChildComponent when you hit the KeyDown button of an input Html element embedded in each child component. Additionally, my code also demonstrate how to return a reference to each component when its KeyDown event takes place:
ChildComponent.razor
<input type="text" @onkeydown="@KeyDown" />

@code {

    [Parameter]
    public int ID { get; set; }

   // [Parameter]
   // public EventCallback<int> CallBack { get; set; }

    [Parameter]
    public EventCallback<ChildComponent> CallBack { get; set; }

     private void KeyDown(KeyboardEventArgs args)
    {
      //  if (args.Code == "ArrowDown")
      //  {
      //      InvokeAsync(() => { CallBack.InvokeAsync(ID); });
      //  }

        if (args.Code == "ArrowDown")
        {
            InvokeAsync(() => { CallBack.InvokeAsync(this); });
        }
    }

}

ParentComponent.razor

@output

@for (int i = 0; i < 10; i++)
{
    <ChildComponent CallBack="ShowID" @ref="component" ID="i" />
}

@code
{
    private ChildComponent component { set => components.Add(value); }

    List<ChildComponent> components = new List<ChildComponent>();

    protected override void OnInitialized()
    {
        foreach (var component in components)
        {
           Console.WriteLine(component.ID);
        }
    }

    private string output = "";

    // private void ShowID(int id)
    // {
    //     output = id.ToString();
    // }

    private void ShowID(ChildComponent child)
    {
        output = child.ID.ToString();
    }
}


Q: Life cycle of an iphone app? I am confused of how an iphone app goes when it start running. I mean when I am trying to write a app, I get confused and lost of terms like "viewDidLoad", "viewDidUnload", "dealloc", "applicationDidLoad" etc. I have no idea when one comes first, which one comes later when an app runs. For instance, say, I would like to add a view(or picture) showing my app logo when the app is just opened (just like what most apps would do). So, where (viewDidLoad or applicationDidLoad) should I put my code in?
Well, this is just an example. I will appreciate it if you can tell me the answer. But what I am most concerned is about the life cycle of running a app, i.e at which state, which method will be called. Thanks in advance!

A: To start, you might want to know this:
the first code you get to run after the application has finished launching, is the one you put in the Application Delegate in the method application:didFinishLaunchingWithOptions. The app delegate is the class that is set to receive general notifications about what's going on with the app, like it finished launching :)
The other kind of 'notifications' of changes in the state of the app, or the life cycle of views are:
-viewDidLoad
-viewWillAppear:animated:
-viewDidAppear:animated:
-viewWillDisappear:animated:
-viewDidDisappear:animated:
-viewDidUnload

Those methods are declared in UIViewController, and you can implement them in your UIViewController subclasses to customize the behaviour of a view in those situations (each method name is self explanatory)
The life cycle of an app is pretty well covered here: http://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf page 27
About showing a logo when the app launches, apps achieve that setting a "splash" image by putting its name in the info.plist property-list file, in the UILaunchImageFile key.

A: I think the official developer guide delivered by apple will help you.  This is the link:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html


Q: serializing separate address string into one in javascript you may already know how to parse an address into separate sections such as unit number / street number / street name / town / state and etc...
Almost similar issue here. I want to serialize those separately entered data into one. For example, I have
Level /
Unit number /
Street number /
Street name /
Street type /
Town /
State /
Post code / Etc...

Let's say user entered

blank / blank / 10 / Flinders / lane / blank / VIC / 3000

Then I would like to have the information in one string like

10 Flinders Lane VIC 3000

I'm currently doing this as the follow
if (level !== '' && level !== 0) {string = level + '/';}
if (unit !== '' && unit !== 0) {string += unit;}
if (streetNo !== '' && streetNo !== 0) {string += '/' + streetNo + ' ';}
else {string += ' ';}
string += streetName + ' ' + streetType + ' ';
if (town !== '' && town !== '--' && town !== 0) {string += town + ' ';}
else {string += ' ';}
string += state;

it is hard coded but I cannot come up with any better way. I would like to know if there is any better and efficient + professional way to achieve this.

A: Because the delimiters you want on the string seem to vary according to which part of the string they follow (some have '/', others have ' '), there's probably not a lot you can do there.
If the delimiter were always the same (such as a space), you might use an array and then use join:
var parts = [];
if (level      !== '' && level      !== 0)      parts.push(level);
if (unit       !== '' && unit       !== 0)      parts.push(unit);
if (streetNo.g !== '' && streetNo.g !== 0)      parts.push(streetNo.g);
if (streetName !== '' && streetName !== 0)      parts.push(streetName);
if (streetType !== '' && streetType !== 0)      parts.push(streetType);
if (town !== '' && town !== 0 && town !== '--') parts.push(town);
if (state      !== '' && state      !== 0)      parts.push(state);
string = parts.join(' ' );


Q: Tachograph Card Authentication I am trying to remote authentication for tachograph. I have a problem between tachograph and can bus communication. i am successful open session 10 7E and send company card ATR. But when i passed to authentication of company card.
i send :      0x31,0x01,0x01,0x80,0x03.
tacho respond: 10 0C 71 01 01 80 04 00
i send fc : 30 00 14 00 00 00 00 00

but tacho not respond me. Can anyone give me any idea?


Q: $\lim_{p \to \infty}{\rho_p(x,y)}$, where $\rho_p$ is a metric on $\mathbb{R}^n$ I need to prove that for $\rho_p(x,y):=(\sum_{i=1}^n |x_i-y_i|^p)^{\frac{1}{p}}$
$\lim_{p \to \infty}{\rho_p(x,y)} = \max_{1\le i\le n}|x_i-y_i|$
Not sure how to proceed.

A: Hint
Show that
$$\max_{i=1,...,n}\{|x_i-y_i|\} \leq \rho_p(x,y)\leq n^{1/p}\max_{i=1,...,n}\{|x_i-y_i|\}$$


Q: What is the difference between static_cast and Implicit_cast? What is implicit_cast? when should I prefer implicit_cast rather than static_cast?

A: Prefer implcit_cast if it is enough in your situation. implicit_cast is less powerful and safer than static_cast.
For example, downcasting from a base pointer to a derived pointer is possible with static_cast but not with implicit_cast.  The other way around is possible with both casts. Then, when casting from a base to a derived class, use implicit_cast, because it keeps you safe if you confuse both classes.
Also keep in mind that implicit_cast is often not needed.  Using no cast at all works most of the time when implicit_cast does, that's where 'implicit' comes from.  implicit_cast is only needed in special circumstances in which the type of an expression must be exactly controlled, to avoid an overload, for example.

A: I'm copying over from a comment i made to answer this comment at another place.

You can down-cast with static_cast. Not so with implicit_cast. static_cast basically allows you to do any implicit conversion, and in addition the reverse of any implicit conversion (up to some limits. you can't downcast if there is a virtual base-class involved). But implicit_cast will only accept implicit conversions. no down-cast, no void*->T*, no U->T if T has only explicit constructors for U.

Note that it's important to note the difference between a cast and a conversion. In the following no cast is going on
int a = 3.4;

But an implicit conversion happens from double to int. Things like an "implicit cast" don't exist, since a cast is always an explicit conversion request. The name construct for boost::implicit_cast is a lovely combination of "cast using implicit conversions". Now the whole implementation of boost::implicit_cast is this (explained here):
template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }

The idea is to use a non-deduced context for the parameter t. That will avoid pitfalls like the following:
call_const_version(implicit_cast(this)); // oops, wrong!

What was desired is to write it out like this
call_const_version(implicit_cast<MyClass const*>(this)); // right!

The compiler can't deduce what type the template parameter Dst should name, because it first must know what identity<Dst> is, since it is part of the parameter used for deduction. But it in turn depends on the parameter Dst (identity could be explicitly specialized for some types). Now, we got a circular dependency, for which the Standard just says such a parameter is a non-deduced context, and an explicit template-argument must be provided.

A: implicit_cast transforms one type to another, and can be extended by writing implicit cast functions, to cast from one type to another.
e.g.
int i = 100;
long l = i;

and
int i = 100;
long l = implicit_cast<long>(i);

are exactly the same code
however you can provide your own implicit casts for your own types, by overloading implicit_cast like the following
template <typename T>
inline T implicit_cast (typename mpl::identity<T>::type x)
{
    return x;
}

See here boost/implicit_cast.hpp for more
Hope this helps
EDIT
This page also talks about implicit_cast New C++
Also, the primary function of static_cast is to perform an non changing or semantic transformation from one type to another. The type changes but the values remain identical e.g.
void *voidPtr = . . .
int* intPtr = static_cast<int*>(voidPtr);

I want to look at this void pointer, as if it was an int pointer, the pointer doesn't change, and under the covers voidPtr has exactly the same value as intPtr.
An implicit_cast, the type changes but the values after the transformation can be differnet too.

A: Implicit conversions, explicit conversions and static_cast are all different things. however, if you can convert implicitly, you can convert explicitly, and if you can convert explicitly, you can cast statically. The same in the other direction is not true, however. There is a perfectly reasonable relationship between implicit casts and
static casts. The former is a subset of the the latter.
See section 5.2.9.3 of the C++ Standard for details

Otherwise, an expression e can be
  explicitly converted to a type T using
  a static_cast of the form static_-
  cast(e) if the declaration T t(e);
  is well-formed, for some invented
  temporary variable t (8.5).

C++ encourages use of static_casts because it makes the conversion 'visible' in the program. Usage of casts itself indicates some programmer enforced rule which is worth a look so better use static_cast.


Q: Is there a way to install Ubuntu (specifically with Gnome) and not get all of the software that comes along with it? I just installed Ubuntu with Gnome and there is a lot of software (i.e. Books Calendar Color Profile Viewer that I do not want and have to manually uninstall.
Is there a way to install Gnome and Ubuntu without this software?

A: From the Ubuntu minimal CD installation we will be asked what we are going to install.

*

*On booting the minimal ISO choose Install

*Answer several question regarding locale, user, keyboard etc.

*Select from a list what to install

We can choose a complete desktop environment from the list above but then all recommended packages for that DE will also be installed.
Selected nothing from above to reboot to a command line but with fully supported networking and package management. From there we can further fine-tune our individual installation (e.g. install just a minimal GNOME shell).

A: Ubuntu mini.iso in BIOS mode
If you want to install your Ubuntu system in BIOS mode (alias CSM alias legacy mode), you can start from the very small  Ubuntu mini.iso file.
Ubuntu Server amd64 iso file in UEFI mode and BIOS mode
If you want to install your Ubuntu system in UEFI mode, the mini.iso does not work. But you can start from the Ubuntu Server amd64 (64-bit) iso file. The result will be almost exactly the same (in BIOS mode) as from the mini.iso file, and it works in UEFI mode, so this is a good alternative :-)
Install a minimal system or select from the Software Selection menu
You can install a minimal system with a text screen interface, boot into it and from there install only the program packages, that you want. This way you can install a simple window manager and a minimal amount of software, or as in your case, a minimal gnome shell as suggested in the answer by @Takkat.
You can also select some of the alternatives from the Software Selection menu in the installer.


Q: Pull-back divisor being Cartier Let $\pi \colon X \rightarrow Y$ be a projective morphism with connected fibers between normal quasi-projective varieties. Let $N$ be a $\mathbb{Q}$-Cartier divisor on $Y$ so that $\pi^*(N)$ is Cartier. Does it follows that $N$ is itself Cartier?

A: Following the clarification in the comments, I am interpreting the question as follows.
Question. For an effective Weil divisor $N$ on $Y$, for an effective Cartier divisor $A$ on $X$, for a positive integer $\ell$ such that the effective Weil divisor $\ell N$ is Cartier and such that the pullback effective Cartier divisor $\pi^*(\ell N)$ equals $\ell A$ as effective Cartier divisors, is $N$ Cartier?
The answer to that question is no. The following example is a modification of the example in my comment avoiding the mistake identified by Stefano.
The minimal resolution of a cone over a smooth plane cubic is a ruled surface.  Let $C\subset \mathbb{P}^2$ be a smooth, plane cubic (a genus $1$ curve).  Let $Y$ be the projective cone in $\mathbb{P}^3$ over $C$.  The minimal desingularization of $Y$, $$\pi:X\to Y,$$ is the closure in $Y\times C$ of the graph of the linear projection from $Y$ to $C$.  Denote by $\rho$ the projection, $$ \rho:X\to C.$$  This morphism is a $\mathbb{P}^1$-bundle.  The morphism $\rho$ maps the exceptional locus $E$ of $\pi$ isomorphically to $C$, and $E$ is a relative hyperplane class for $\rho$. The normal sheaf $\mathcal{O}_X(\underline{E})|_E$ is isomorphic to $\mathcal{O}_{\mathbb{P}^2}(-1)|_C$.
Effective Weil divisors "torsion-equivalent" to a conical hyperplane class.
Let $H\subset C$ be the restriction to $C$ of a general hyperplane in $\mathbb{P}^2$. Let $D\subset C$ be a degree $3$ effective divisor such that the divisor $H-D$ has finite order $\ell>1$ in the Picard group of $C$, i.e., $\ell H - \ell D$ is the divisor of a rational function $f$ on $C$.
Let $M\subset Y$, resp. $N \subset Y$, be the cone over $H$, resp. $D$.  Note that $\ell N$ and $\ell M$ are linearly equivalent Cartier divisors on $Y$ in the linear equivalence class of $\mathcal{O}_{\mathbb{P}^3}(\ell)|_Y$. In fact, $\ell$ is the smallest positive integer such that $\ell N$ is a Cartier divisor on $Y$.
Denote by $\widetilde{M}\subset X$, resp. by $\widetilde{N}\subset X$, the strict transform under $\pi$ of $M$, resp. of $N$.  Note that $\ell \widetilde{M}-\ell\widetilde{N}$ equals the Cartier divisor of $f\circ \rho$, as does the total pullback under $\pi$ of the Cartier divisor $\ell N-\ell M$.  Thus, the coefficient of $E$ in the pullback of $\ell M$ equals the coefficient of $E$ in the pullback of $\ell N$.
Already $M$ is an effective Cartier divisor on $Y$, and the pullback of $M$ is the strict transform $\widetilde{M}$ plus the exceptional divisor $E$.  One way to see this is to deform $M$ to a hyperplane section of $Y$ that is disjoint from the vertex of the cone.  Since the intersection number of the total transform of $M$ with $E$ equals $0$, it follows that the coefficient of $E$ equals $1$.    Thus, the total pullback of $\ell M$ equals $\ell \widetilde{M} + \ell E$.
Therefore also $\ell N$ equals t$\ell \widetilde{N} +\ell E$.  Although $N$ is not Cartier on $Y$, the pullback of $\ell N$ equals $\ell A$ on $X$ for the effective Cartier divisor $A=\widetilde{N}+E$.


Q: Line-wrapping `less` in OS X (specifically for use with 'git diff') Using less +-S does not work (although it does ask Chop long lines  (press RETURN)), and entering -S once inside less also does not work. Is there a solution?
I am usig OS X Mavericks (10.9.3).
less 418 (default) or less 458 (via MacPorts)

A: You can use fold to first wrap the text, then pipe to less:
fold -w 78 | less

Of course, -w sets the number of characters. By default it's 80. fold is POSIX and bundled with OS X.

Apparently, using less -r as the default Git pager will also achieve folding of long lines.
Otherwise, while the diff is being displayed, you can type -S, then Enter to toggle chopping/folding long lines.


Q: Git post-commit /post-receive hook not working I have a Git repo one one server. i want that whenever an admin pushes changes to git repo, those changes may automatically be deployed to a folder on the same server, where git repo is hosted.
As my repo is in /opt/myrepo.git , i have created the scripts /opt/myrepo.git/hooks/post-commit .
when i perform any commit on the repo, the above script should run, but it does not. i have wrote simple Echo commands in it to test its output to a file, but it doesnt run at all.

A: For pushes you should use the post-receive hook and not the post-commit hook.
I made the same mistake due to the odd naming convention

A: Apart from using the post-hook you should make sure that the your hook file is executable. So take a look at the file permissions make sure that you have chmoded the file to a+x.
chmod a+x post-receive
post-receive hook should be executable by git. If its not executable then git doesn't inform you.
Also, make sure the first line is #!/bin/sh
Hope this helps


Q: ¿Cómo puedo obtener el nombre del servidor de mi base de datos MongoDB? tengo que conectar mi base de datos MongoDB a Tableau, para realizar un cuadro de mando.
Para ello me he descargado el Conector BI de MongoDB para Tableau. Una vez instalado, este conector me pide el nombre del servidor, usuario y contraseña.
El problema es que no encuentro el nombre del servidor ni en MongoDB Atlas ni en MongoDB Compass. Adjunto una captura de lo que me piden. Si aalguienme puede echar una mano sería genial :)
Muchas gracias!


Q: Build vim with --remote-tab on OSX I built vim using:
./configure --with-x --enable-pythoninterp --with-features=huge
but don't have access to vim --remote-tab. I'm using OSX version 10.11.2. I'm hoping to use Vim and not MacVim since I'm using tmux too.
Here's the output of vim --version if it's helpful:
vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Apr  5 2016 09:24:37)
MacOS X (unix) version
Included patches: 1-658
Compiled by *******
Huge version without GUI.  Features included (+) or not (-):
+acl             +farsi           +mouse_netterm   +syntax
+arabic          +file_in_path    +mouse_sgr       +tag_binary
+autocmd         +find_in_path    -mouse_sysmouse  +tag_old_static
-balloon_eval    +float           +mouse_urxvt     -tag_any_white
-browse          +folding         +mouse_xterm     -tcl
++builtin_terms  -footer          +multi_byte      +terminfo
+byte_offset     +fork()          +multi_lang      +termresponse
+cindent         -gettext         -mzscheme        +textobjects
-clientserver    -hangul_input    +netbeans_intg   +title
+clipboard       +iconv           +path_extra      -toolbar
+cmdline_compl   +insert_expand   -perl            +user_commands
+cmdline_hist    +jumplist        +persistent_undo +vertsplit
+cmdline_info    +keymap          +postscript      +virtualedit
+comments        +langmap         +printer         +visual
+conceal         +libcall         +profile         +visualextra
+cryptv          +linebreak       +python          +viminfo
-cscope          +lispindent      -python3         +vreplace
+cursorbind      +listcmds        +quickfix        +wildignore
+cursorshape     +localmap        +reltime         +wildmenu
+dialog_con      -lua             +rightleft       +windows
+diff            +menu            -ruby            +writebackup
+digraphs        +mksession       +scrollbind      -X11
-dnd             +modify_fname    +signs           -xfontset
-ebcdic          +mouse           +smartindent     -xim
+emacs_tags      -mouseshape      -sniff           -xsmp
+eval            +mouse_dec       +startuptime     -xterm_clipboard
+ex_extra        -mouse_gpm       +statusline      -xterm_save
+extra_search    -mouse_jsbterm   -sun_workshop    -xpm
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/usr/local/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H   -DMACOS_X_UNIX  -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc   -L/usr/local/lib -o vim        -lm -lncurses  -liconv -framework Cocoa    -framework Python


Q: awesomewm remap tag display I'm trying to remap my the tag display feature thats traditionally mapped to modkey, "Control", "#" .. i + 9. I have removed any other instance of {modkey, "Tab"} mappings in my rc.lua, and attempted to replace the word Control with the word Tab. However, despite the rc compiling it the command doesn't run. I have no idea why this might be hopefully one of you more experienced users will be able to see my issue.
awful.key({ modkey, "Tab" }, "#" .. i + 9,
                  function ()
                      local screen = awful.screen.focused()
                      local tag = screen.tags[i]
                      if tag then
                         awful.tag.viewtoggle(tag)
                      end
                  end,
                  {description = "toggle tag #" .. i, group = "tag}),

A: As Uli says in the comment, what can and cannot be a modified is a constraint coming from Xorg. It cannot be Tab.
But. With awful.keygrabber, you can create a keybinding on modkey+Tab, then from that callback, start the keygrabber and intercept the number keys from there. When the keygrabber detect Tab is released, then stop it. There is multiple built-in methods and property to make this rather easy.
See https://awesomewm.org/apidoc/core_components/awful.keygrabber.html for more details.
Just take the Alt+Tab example (link above) and modify it to fit your use case.


Q: hbase for storing gamers' last 1000 key hits So for my use case, I need to save only the last 1000 key hits of each gamer. and there will be only 2 fields --> gamerId (all numeric) and keyId (also all numeric). so, lets say, gamer 1123 already has 999 keyIds stored, when the 1000th keyId comes in for that gamer, normal insertion. however, once 1001st keyId comes in, we need to remove the earliest recorded keyId for that gamer and persist that 1001st in. so, at all times, there can only be max 1000 keyIds for each gamer in the db. We have +/- 100 million of gamers and very high keyId traffic, and this table will be looked up and written into very frequently.
will HBase be suitable for this? if it's not, what could be the alternative?
Thanks

A: In principle, you can get this done in hbase very easily thanks to versioning. I've never tried something as extreme at 1,000 versions per column (normally 5-10) but I don't think there is any specific restriction as to how many versions you can have. You should just see if it creates any performance implications. Also check out this discussion: https://www.quora.com/Is-there-a-limit-to-the-number-of-versions-for-an-HBase-cell
When you define your table and your column family, you can specify the max versions parameter. This way, when you simply keep doing the Puts with the same row value, the key for that row will keep generating new versions (they will all be time-stamped as well. Once you do your 1,001th Put, the 1st put will automatically be deleted, and so on on the FIFO basis. Similarly, when you do a Get on that row-key, you can use various methods to retrieve a range of versions. In that case it depends on what API you will be using to get the values (this is easy to do with native Java API, but not sure about other access methods).
100mln rows is quite small for HBase, so generally it shouldn't be a problem. But of course if each of your rows really has 1,000 versions, then you are looking at 100bln key-values. Again, I'd say it's doable for HBase, but you should see imperially whether this causes any performance problems and you should size your cluster appropriately.


Q: Measure associated to a top-degree differential form (not necessarily a volume form) on a K-analytic manifold (K a local field) Suppose $K$ is a non-Archimedian local field and suppose $\omega$ is a top-degree differential form on a compact $K$-analytic manifold $M$ of dimension $n$. It is possible to construct a Borel measure on $M$, denoted $\mu_{\omega}$, essentially by writing
$$\mu_{\omega}(A) = \int_A|f|d\mu $$
locally. That is, on a coordinate patch $U$ on which $\omega = fdx_1\wedge...\wedge x_n$ we define it as such (we can make sense of this by integrating on polydisks and applying Caratheodory's extension theorem) with respect to the Haar measure $\mu$ on $K^n$. This doesn't depend on the choice of coordinates because of the standard change of variables formula.
One element of this construction is that an arbitrary Borel set $A$ can be written as a disjoint union of Borel sets which are contained in a coordinate patch on which we know how to integrate Borel sets. This leads me to some questions:

*

*Does this extend to $K$-analytic manifolds which are not compact? I explicitly used compactness to show that I can cover $M$ with disjoint coordinate patches. (I did the obvious and used clopenness of the basis to iteratively transform a finite clopen cover into a finite disjoint clopen cover. This does not work if $M$ is not compact.) I do not believe it should, but I cannot come up with a counterexample.

*I do not see why this construction fails for real manifolds. I have a (very strong) suspicion that this is defining a density on a manifold. In fact, I am nearly certain that this is simply integrating the density $|\omega|$. Can anyone confirm this? The only fact specific to $K$-analytic manifolds that I used is this ability to write a Borel set as a disjoint union of Borel sets in coordinate patches. That being said:

*I believe this requirement that Borel sets are disjoint unions of Borel sets in coordinate patches is actually a red herring. Is it simply true that one can do this? (I don't see how to do this if the patches are not disjoint.) Otherwise, is there a work-around?


Q: i am not able to remove grayscale via jquery my css code
.content-img  {
    -webkit-transition: all 1s ease;
     -moz-transition: all 1s ease;
       -o-transition: all 1s ease;
      -ms-transition: all 1s ease;
          transition: all 1s ease;
         -webkit-filter:grayscale(100%);
}

my jquery
 $('.content-img').hover(function () {
        $(this).css('-webkit-filter', 'grayscale(0)');
    });

I just wanted to write jQuery. it doesnt work.

A: Why do you need to use jQuery at all?
You can use this:
.content-img:hover {
    -webkit-filter: grayscale(0%);
            filter: grayscale(0%);
}

Here, I made you this fiddle using css only, with :hover selector.
But be careful, filter has limited support, look at filter article on MDN.


Q: How to work around Mathematica hanging when showing a large SparseArray? Bug introduced in 9.0 and fixed in 9.0.1

In Mathematica 9, if I display any large SparseArray object in the default way (which looks something like SparseArray[<97293>, {25000, 25000}]), the MathKernel process will keep using 100% CPU, the Front End will hang and eventually display the "Kernel is not responding to a dynamic evaluation; Abort or Continue waiting?" dialog.  Pressing Abort will kill the kernel process.
I am looking for a way to avoid / work around this.
Reproducing the problem
Try
g = RandomGraph[{25000, 50000}];
AdjacencyMatrix[g]  (* note missing semicolon *)

In a few seconds after the result is displayed Mathematica 9 will hang in the sense that:

*

*the beachball cursor shows intermittently (on OS X)

*the kernel uses 100% CPU (one core)

*subsequent evaluations will be impossible until the kernel is killed

Mathematica 8 will not hang.
Observations

*

*Not displaying the SparseArray (putting a semicolon after AdjacencyMatrix[g];) avoid the problem.

*The displayed form of the SparseArray is very short.  This is true even for the cell expression.  The problem is not caused by an overwhelming amount of data being sent to the front end.

*I still want to keep track of how many non-zero elements there are in the SparseArray so I would like to display it

*Disabling Dynamic updating from the Evaluation menu does not change anything.  That would have been a usable temporary workaround.

*The problem does not appear when using the command line version (kernel only) of Mathematica

*Killing the kernel manually (not using the front end) causes INTERNAL SELF-TEST ERROR: Kernels|c|6568
I believe this to be a bug and I'll contact support, but some analysis of why the problem happens would be useful to work around it.  Or perhaps just a way to find the number of non-zero elements quickly.  Then maybe I could write an alternate Format for SparseArray objects.
Version & system info
This happens with Mathematica 9.0.0.0 on OS X 10.8.2, 16 GB RAM.  Can someone on OS X try to reproduce the problem?

A: As Silvia notes in the comments, this behaviour is because of the predictive interface that is new in version 9. Mathematica tries to inspect the contents of the output to determine which contextual menu options to show in the suggestions bar depending on whether it is an array of integers/reals/mixed or if it is square/rectangular, etc. My guess is that somewhere along the line in the implementation, they must be inadvertently converting the sparse matrix to a full one.
One obvious solution then, is to simply disable the suggestive interface. This however disables it for all notebooks and all operations. An alternative to this would be to disable it only if the output contains a SparseArray object. This can be done using the $Pre and $Post commands:
$Pre = (SetOptions[EvaluationNotebook[], ShowPredictiveInterface -> True]; #) &
$Post = Function[expr,
    If[
        FreeQ[expr, SparseArray],
        expr,
        SetOptions[EvaluationNotebook[], ShowPredictiveInterface -> False];expr
    ],
    HoldAll
]

The $Pre setting is necessary to turn it back on for the next evaluation after $Post turns it off (or might have turned it off).


Q: Can I use spring boot datasource to get connection object so as to use it with conn.executeQuery() manually? I am working on spring boot application with Mysql backend and trying to use springboots datasource Bean to get connection object so as to use it with the following stmts:
stmt =conn.createStatement()
stmt.executeQuery("show tables");

which is expected to return the table list. Below is the code of connection class:
public class Test {

@Autowired
DataSource datasource;

public void test1(){
      System.out.println("Inside Test Method");
    try {
         Connection conn = datasource.getConnection();
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("show tables");
         while (rs.next()) {
             System.out.println(rs.getString("TableNames"));
         }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch(NullPointerException e){
        System.out.println("Null Pointer exception");
    }

  }

}
But the datasource object is throwing null value and hence it doesnt return any connection object.
Following is the application.yml
spring:
 datasource:
 url: jdbc:mysql://localhost:3306/test
 driver-class-name: com.mysql.jdbc.Driver
 username: ****
 password: ****
 initial-size: 1
 max-idle: 2
 max-active: 3

Ideally the datasource object should read these properties and be able to return connection object. Not sure if my understanding is correct.
Can anyone help me out in figuring the issue pls ?

A: I think spring boot automated this process completely. One doesn't have to inject the data source manually & connection pool mechanism is also automated. Just adding the connection properties and pool properties in yaml file or properties file under src/main/resources. It will inject the data source for you.


Q: Do channel ids for guide categories (like music) change in the YouTube Data API? After fetching the list of channels from the guide with the guideCategories endpoint, a list of kind youtube#guideCategory is returned.  These IDs can be used to get a list of channels from the channels endpoint for the given category.
My question is do these IDs change?  Can I store this list of guide categories and reuse them for multiple languages/regions?

A: Assuming it works the same way as VideoCategories do, the IDs should work for and remain consistent across any region that supports it.
For example, when I used the API explorer and specified USA, Germany, or Australia for the region, the guideCategory ID for Music (GCTXVzaWM) was available for all three, so that guideCategory is supported in and will work for all three of those regions.


Q: set readonly property to false for an html text input on clicking on Edit I need to set readonly false when i click on Edit and when i click on edit button should change to save button. i made two input box type="submit". i need to make all the fields editable when i click on edit. please help me to find out the answer.
<form role="form" data-toggle="validator" method="post">

      <?php if(isset($account_list)){   print_r($account_list);exit;
}?>

                        <input type="text" name="RMName" value="<?= isset($accountList['name']) ? $accountList['name'] : '' ?>" id="inputName" readonly="readonly" class="readonlyinput"/>

                        <input type="email" id="inputEmail" name="inputEmail" value="<?= isset($accountList['email']) ? $accountList['email'] : '' ?>"  readonly="readonly" class="readonlyinput" />

                        <input type="text" name="dob" value="<?= isset($accountList['dob']) ? $accountList['dob'] : ''  ?>" id="InputDob" readonly="readonly" class="readonlyinput"/>

                        <input name="Phone" type="text"  id="InputNumber" value="<?= isset($accountList['phone_number']) ? $accountList['phone_number'] : '' ?>" readonly="readonly" class="readonlyinput"/>

                        <input type="text" name="OrgName" value="<?= isset($accountList['organisation']) ? $accountList['organisation'] : ''  ?>" id="InputOrgName" readonly="readonly" class="readonlyinput"/>

                        <input type="text" name="OrgId" value="<?= isset($accountList['organisation_id']) ? $accountList['organisation_id'] : '' ?>" id="InputOrgId" readonly="readonly" class="readonlyinput"/>

                        <input type="text" name="City" value="<?= isset($accountList['city']) ? $accountList['city'] : ''  ?>" id="InputCity" readonly="readonly" class="readonlyinput" />

                        <input type="text" name="State" value="<?= isset($accountList['state']) ? $accountList['state'] : '' ?>" id="InputState" readonly="readonly" class="readonlyinput" />

                        <input type="text" name="Country" value="<?= isset($accountList['country']) ? $accountList['country'] : '' ?>" id="InputCountry" readonly="readonly" class="readonlyinput" />

                  <input type="submit" class="button" title="Edit" value="EDIT" onclick="inputToggle()"/>
                  <input type="submit" class="button" title="Save" value="SAVE"  hidden="hidden"/>

    </form>

A: Use this function. Suppoesing .edit class of edit button
$('.edit').on('click', function(){
  $('input').prop('readonly',true);
});

But don't set this property initially

A: Use .prop to toggle readonly property of the :input elements.
Also note, e.preventDefault() as submit button will submit and relaod the form.

var edit = true;

function inputToggle(e) {
  e.preventDefault();
  $(':input').prop('readonly', edit = !edit);
}

<form role="form" data-toggle="validator" method="post">

            <input type="text" name="RMName" value="" id="inputName" readonly="readonly" class="readonlyinput" />

            <input type="email" id="inputEmail" name="inputEmail" value="" readonly="readonly" class="readonlyinput" />

            <input type="text" name="dob" value="" id="InputDob" readonly="readonly" class="readonlyinput" />

            <input name="Phone" type="text" id="InputNumber" value="" readonly="readonly" class="readonlyinput" />

            <input type="text" name="OrgName" value="" id="InputOrgName" readonly="readonly" class="readonlyinput" />

            <input type="text" name="OrgId" value="" id="InputOrgId" readonly="readonly" class="readonlyinput" />

            <input type="text" name="City" value="" id="InputCity" readonly="readonly" class="readonlyinput" />

            <input type="text" name="State" value="" id="InputState" readonly="readonly" class="readonlyinput" />

            <input type="text" name="Country" value="" id="InputCountry" readonly="readonly" class="readonlyinput" />

          <input type="submit" class="button" title="Edit" value="EDIT" onclick="inputToggle(event)" />

            <input type="submit" class="button" title="Save" value="SAVE" hidden="hidden" />

</form>

Fiddle demo


Q: Bitnami GitLab 5.2.0: gitlab_sidekiq not running and could not be started We are using Bitnami GitLab 5.2.0.
We stumbled upon that we can't push into new repository, like
git@192.168.133.10:sandbox/testgit2.git,
but we can work with old ones. Closer investigation showed that gitlab_sidekiq is not running.
/opt/bitnami/ctlscript.sh restart gitlab_sidekiq
gitlab_sidekiq could not be started
Where to look? Should I update first?
UPDATE: Bitnami GitLab 5.2 server is broken down: can't push code into new repositories.
(While old repositories are unaffected)
TestProject4>git remote add origin git
@192.168.133.10:sandbox/testproject4.git

TestProject4>git push -u origin master

fatal: '/opt/bitnami/apps/gitlab/repositories/sandbox/testproject4.git' does not  appear to be a git repository
fatal: The remote end hung up unexpectedly

UPDATE WITH ANSWERS:
I am using virtual machine in VirtualBox on my PC (in 1 team as pilot moving the VM to some VM host)
Yes, I modified gitlab.yml
/opt/bitnami/apps/gitlab/htdocs/log/sidekiq.log has this lines in repetition, so they should give clue (look like some thing wrong when reading some file)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /opt/bitnami/apps/gitlab/htdocs/config/environment.rb:5)
/opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse': (<unknown>): found character that cannot start any token while scanning for the next token at line 73 column 1 (Psych::SyntaxError)
    from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse_stream'
    from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:151:in `parse'
    from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:127:in `load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:113:in `initialize'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:71:in `new'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:71:in `instance'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:48:in `[]'
    from /opt/bitnami/apps/gitlab/htdocs/config/initializers/1_settings.rb:38:in `<top (required)>'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `block in load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:588:in `block (2 levels) in <class:Engine>'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:587:in `each'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:587:in `block in <class:Engine>'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `instance_exec'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `run'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `each'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `run_initializers'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/application.rb:136:in `initialize!'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/railtie/configurable.rb:30:in `method_missing'
    from /opt/bitnami/apps/gitlab/htdocs/config/environment.rb:5:in `<top (required)>'
    from /opt/bitnami/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /opt/bitnami/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/lib/sidekiq/cli.rb:199:in `boot_system'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/lib/sidekiq/cli.rb:47:in `parse'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/bin/sidekiq:7:in `<top (required)>'
    from /opt/bitnami/ruby/bin/sidekiq:23:in `load'
    from /opt/bitnami/ruby/bin/sidekiq:23:in `<main>'

GitLab says it requires ruby 1.9.3, but here I see 1.9.1. Can that be problem?

A: It is strange. What are you using, the installer, the virtual machine or the cloud image? If the sidekiq server is not running it is possible that the repository was not created properly. Could you check if there is any error in the sidekiq log file?
/opt/bitnami/apps/gitlab/htdocs/logs/sidekiq.log
Did you modify any configuration file for GitLab?
EDITED:
The problem seems a wrong configuration in the gitlab.yml. It is also important the white spaces. Could you check your change in that file?
/opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse': (): found character that cannot start any token while scanning for the next token at line 73 column 1 (Psych::SyntaxError)
GitLab CI ships Ruby 1.9.3 latest stable version. The folder name uses 1.9.1 for backguard compatibility Why is my gem "INSTALLATION DIRECTORY:" ...1.9.1 when the "RUBY VERSION:" is 1.9.3
Please post the gitlab.yml file if you do not find the exact error.

A: In my case I had <tab> in my yml file.
It's quite strange error though!


Q: Group by and foreach I want to print only once the title and all related images id_post
table IMAGES
id_images | dir_image | post_id
     1      image1.jpg   1
     2      image2.jpg   1
     3      image3.jpg   1
     4      image4.jpg   1
     5      image5.jpg   2
     6      image6.jpg   2
     7      image7.jpg   2
     8      image8.jpg   2

table POSTS
id_post   |          slug        |   title
 1           title_post            Title Post
 2           title_post_2          Title Post 2

PHP code:
$slug = $_GET['slug'];
 $stmt = $DB_con->prepare("SELECT * FROM posts, images
                      WHERE posts.id_post = images.post_id
                      AND slug=:slug");
 $stmt->execute(array(":slug"=>$_GET['slug']));

 while($row=$stmt->fetch(PDO::FETCH_BOTH))
 {
 ?>

<?php print utf8_encode($row['title']);?>

<?php
}
?>

Accessing the page "Title post 2", the result is:
Title post 2
image5.jpg

Title post 2
image6.jpg

Title post 2
image7.jpg

Title post 2
image8.jpg

How to get the result:
Title post 2
image5.jpg
image6.jpg
image7.jpg
image8.jpg

How I enter the SQL statement the "group by" to group images:
SELECT * FROM posts, images
                     WHERE posts.id_post = images.post_id
                     AND slug=:slug

And then inside the while inserting a foreach with the images of the group by?
while($row=$stmt->fetch(PDO::FETCH_BOTH))
     {
     ?>

<?php print utf8_encode($row['title']);?>

    <?php
    }
    ?>

Inserting if not solve for me, it will be necessary to create several ifs

A: If you just want to do it in procedural PHP, you could do something like this:
$runningTitle = '';

while($row=$stmt->fetch(PDO::FETCH_BOTH)) {

    if ($row['title'] != $runningTitle) {
        $runningTitle = $row['title'];
        print "
";
        print utf8_encode($row['title']);
        print "
";
    }

    // now render images.

}

However I would recommend using a more object orientated approach to build the html string and then return it as a single string, to echo at the end, rather than rendering everything out procedurally. It's often tidier to complete all your program logic before rendering a page, rather than rendering while you are still asking the code to make decisions.
You are using PHP in it's traditional form - as a templating language. It has come a long way since then.

A: It's some easy and fast and if your "join" images are few, not many.
Your group by, use a GROUP BY and get all images concatenated by SEPARATOR with GROUP_CONCAT
SELECT
  posts.*,
  COUNT(0) total,
  GROUP_CONCAT(dir_image SEPARATOR '|') images
FROM
  posts
  INNER JOIN images ON (posts.id_post = images.post_id )
WHERE
  slug=:slug
GROUP BY
  id_post

This is your loop, create an array exploding the SEPARATOR over field "images" and do the loop
while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
    $aImages = explode('|', $row['images']);
    ?>

<?php print utf8_encode($row['title']); ?>

        <?php
            echo '
' . implode('

', $aImages) . '
'
        ?>

    <?php
}
?>

Or
while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
    $aImages = explode('|', $row['images']);
    ?>

<?php print utf8_encode($row['title']); ?>

        <?php
        foreach ($aImages as $sImage) {
        ?>
            <a href="<?php echo $sImage;?>"><?php echo $sImage; ?>
        <?php
        }
        ?>

    <?php
}
?>


Q: threading: function seems to run as a blocking loop although i am using threading I am trying to speed up web scraping by running my http requests in a ThreadPoolExecutor from the concurrent.futures library.
Here is the code:
import concurrent.futures
import requests
from bs4 import BeautifulSoup

urls = [
        'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=ibfxcfd&showcategories=CFD',
        'https://www.interactivebrokers.eu/en/index.php?f=41634&exch=chix_ca',
        'https://www.interactivebrokers.eu/en/index.php?f=41634&exch=tase',
        'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=chixen-be&showcategories=STK',
        'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=bvme&showcategories=STK'
        ]

def get_url(url):
    print(url)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'lxml')
    a = soup.select_one('a')
    print(a)

with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:
    results = {executor.submit( get_url(url)) : url for url in urls}

    for future in concurrent.futures.as_completed(results):
        try:
            pass
        except Exception as exc:
            print('ERROR for symbol:', results[future])
            print(exc)

However when looking at how the scripts print in the CLI, it seems that the requests are sent in a blocking loop.
Additionaly if i run the code by using the below, i an see that it is taking roughly the same time.
for u in urls:
    get_url(u)

I have add some success in implementing concurrency using that library before, and i am at loss regarding what is going wrong here.
I am aware of the existence of the asyncio library as an alternative, but I would be keen on using threading instead.

A: You're not actually running your get_url calls as tasks; you call them in the main thread, and pass the result to executor.submit, experiencing the concurrent.futures analog to this problem with raw threading.Thread usage. Change:
results = {executor.submit( get_url(url)) : url for url in urls}

to:
results = {executor.submit(get_url, url) : url for url in urls}

so you pass the function to call and its arguments to the submit call (which then runs them in threads for you) and it should parallelize your code.


Q: Hamiltonian system with double integration I have an Hamiltonian system with double integrals so, it is not possible to solve this kind of system with standard optimal control approach.
I suppose that it is necessary to focus on calculus of variation.
I would really appreciate if you have any suggestions (textbook, paper etc.) in order to solve this kind of system.


Q: mysql query show only 1 result i want to output the result based on todays date.
the problem is, the output only show 1 result?
database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'
';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'
';
endwhile;

A: If the date field is of type datetime, you'll have to do something like
SELECT ... WHERE DATE(date)=CURDATE()
Notice that I'm using curdate() in the query. There's no need to generate the date value in PHP. MySQL is perfectly capable of doing that itself.

A: Try adding a GROUP BY statement to the second SQL statement.

*

*you should group by the key of the elemnts you want to be shown in the end result

A: The use of the aggregate function SUM will result in a single result. You are asking the database to get all the rows then sum up a value and give you the value.
To see the result for many groups of values you have to add a group by clause.


Q: UISearchBar stays when seguing to another view controller via push I followed this guide: http://www.jhof.me/simple-uisearchcontroller-implementation/
The only difference in my code is
instead of self.tableView.tableHeaderView = self.searchController.searchBar;
I have self.navigationItem.titleView = self.searchController.searchBar;
When I segue from the results table view controller, the uisearchbar stays in the navigation bar.

A: I rewrite the sample from Apple, you can see I comment self.tableView.tableHeaderView = self.searchController.searchBar; then set it to navigation bar's title view, just like you. You can find search bar is here in snapshot.
- (void)viewDidLoad {
    [super viewDidLoad];

    APLResultsTableController *qresultsTableController = [[APLResultsTableController alloc] init];
    self.resultsTableController = qresultsTableController;
    _searchController = [[UISearchController alloc] initWithSearchResultsController:qresultsTableController];
    self.searchController.searchResultsUpdater = self;
    [self.searchController.searchBar sizeToFit];
//    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.navigationItem.titleView = self.searchController.searchBar;
    self.searchController.hidesNavigationBarDuringPresentation = NO;

    // we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
    self.resultsTableController.tableView.delegate = self;
    self.searchController.delegate = self;
    self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
    self.searchController.searchBar.delegate = self; // so we can monitor text changes + others

    // Search is now just presenting a view controller. As such, normal view controller
    // presentation semantics apply. Namely that presentation will walk up the view controller
    // hierarchy until it finds the root view controller or one that defines a presentation context.
    //
    self.definesPresentationContext = YES;  // know where you want UISearchController to be displayed
}

snapshot is here,

UISearchBarController has a property named hidesNavigationBarDuringPresentation default is YES, set it to NO if you want to use it as navigation item's title view
self.searchController.hidesNavigationBarDuringPresentation = NO;

I have tested, it works. hope it helpful.


Q: how to fix "Error Connection Timed Out Error" of a codeigniter website on a godaddy server? I have uploaded a basic codeigniter website on godaddy server without any database connection. In the config file base url is set to the domain name, index_page is blank & uri_protocol is set to request_uri. I also have the .htaccess file with the code but not sure what to do in it. Here what should i do to remove this error?
I have tried playing with the base url and uri_protocol and also made changes to the .htaccess file but no help either.
My .htaccess code -

Options +FollowSymLinks
RewriteEngine on

# Send request via index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

A: Have your /folder/app/.htaccess like this:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /folder/app/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

then in /folder/app/application/config/config.php you need to have this config:
$config['base_url']  = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';


Q: grub rescue on Ubuntu 18.04 with btrfs partition I have a small server (HP ProLiant MicroServer Gen8) running Ubuntu 18.04 64 bit with the latest HWE generic kernel (5.4.0.74.83~18.04.67); it has two SATA drives, GPT partitioned but booting in legacy BIOS mode. Both drives are partitioned as follows:

*

*partition 1 (1 MB): "shadow" boot partition, for GRUB code;

*partition 2 (several TBs): BtrFS, containing @ subvolume for / and @home subvolume for /home; /boot is indeed under /@/boot

*partition 3 (4 GB): swap

The BtrFS partitions of the two drives are tied together in a BtrFS mirror configuration.
A few days a go power went out, and the NAS didn't ever recover. At boot, I just got the dreaded "grub rescue", saying it couldn't find the target partition (specified with the BtrFS volume GUID, I think). Trying to do ls (hd0,gpt2) (or really, any other partition) told me "unknown filesystem" (even though insmod btrfs seems to work correctly).
Thinking something was fried with the GRUB stuff, I booted with an Ubuntu 18.04 server installation key, and tried to reparir GRUB, as follows:

*

*mount /dev/sda2 /mnt (/dev/sda2 is the BtrFS partition); I can see that all data is still there;

*mount --bind /dev /mnt/@/dev; same for /dev/pts, /proc, /sys, /run (otherwise DNS, managed by resolvconf in both the live system and the "broken" system wouldn't run)

*chroot /mnt/@

*inside the chroot, I did mount /dev/sda2 / -o subvol=@ otherwise grub-probe/grub-install would get confused; outside the chroot, redid the bind thing as that was shadowed by the remount;

*mount -a
Then (across multiple tries) I tried several things:

*

*reinstalled GRUB to /dev/sda (grub-install /dev/sda); tried with --recheck and without, tried grub-mkdevicemap (removing manually the USB key device from the generated device.map file);

*recreated the GRUB configuration (update-grub);

*upgraded the kernel, not really thinking it's much of a kernel version problem, but to make sure (1) I'm trying to boot something that is surely not corrupted and (2) to have freshly made initrd

*checked if the kernel/initrd files were all readable (e.g. with sha1sum /boot/*), as the GRUB messages about that were scary - see later;

*downgraded GRUB (which is at the latest 2.02 revision available in the repos) to a few patch revisions earlier, as I suspected the power loss hadn't much to do about it, but it was instead some upgrade that broke it

*run btrfs check /dev/sda2 and btrfs check /dev/sdb2; both ran without errors, the only problem (reported for both) was in the free space cache of a single block (I later mounted /dev/sda2/ with clear_cache option just to be sure)

The results from all this stuff were far from encouraging: when done correctly, this stuff always leads me again to grub rescue, but this time with a more interesting twist:

*

*it can read somewhat the BtrFS volume, but, so to say, barely; doing ls (hd0,gpt2)/ shows the subvolumes, but both ls (hd0,gpt2)/@ and ls (hd0,gpt2)/@home show empty directories (which is why it cannot find (hd0,gpt2)/@/boot/ and then all the stuff it needs to go into normal mode);

*the most interesting thing is that there's other subvolumes, namely three snapshots done by the Ubuntu version upgrade script; those subvolumes instead can be read by GRUB; not only that: if I adjust prefix, root & co. to point inside the snapshot subvolumes, I can manage to go into "normal" GRUB mode and, again adjusting the paths in the menu entries, boot the older kernel that was in the snapshot (the only problem is that it cannot find the modules, as I'm loading an older kernel version that is no longer installed in the current root filesystem, but given they aren't really used it boots just fine).

Once (when I probably botched something in the aforementioned mount dance in the chroot) I managed to reboot and get directly normal mode, but GRUB was always finding something bad for all entries in the boot menu: in particular, for each and every entry it couldn't either load the kernel or initrd, giving a scary "inode not found" error message (or, in another case, "couldn't find the chunk descriptor"; both of these have no matches in Google besides the GRUB sources themselves, which is always a bad sign); notice that, as I said above, inside the live USB session they were all readable.
Extra thoughts:

*

*the server motherboard has a bit of a weird problem with the SATA controller - disk enumeration seems to take a lot, which lead to this bug when I upgraded to 18.04 https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1752961; the only (sad) fix was to add a sleep 5 in the initrd before btrfs scan; this also lead to having the second disk as /dev/sdc in some of the live USB runs, but it didn't seem to matter (when it happened I also adjusted the file name in /dev, which didn't seem to be particularly relevant for the result though);

*I thought about bad RAM, although it felt unlikely because (1) once booted the system runs normally and (2) it's ECC RAM and I'd expect at least some kind of error message in case; anyhow, I started a MemTest and it's several hours it's running without errors;

*iLO reports a self-test error at boot, that however seems to be unrelated. the error was later solved upgrading to the latest firmware version and clearing its NVRAM; as expected, this made no difference at all, but at least the POST screen is a bit cleaner

My current guess is something like this: the HWE kernel is using a BtrFS version with some feature incompatible with the "regular" Ubuntu 18.04 GRUB version, so all files/directories that are written "now" are potentially problematic for GRUB to read; indeed, I saw that between GRUB 2.02 and the current version (2.06) there has been some work on BtrFS stuff, although for zstd compression, that isn't enabled on my disks. Maybe trying a more recent GRUB could fix the issue? But is there some packaged GRUB 2.06 build that works for 18.04?
Long story short: any idea about what the problem might be and how to fix it?

A:
any idea about what the problem might be

Not really, though I share your suspicion that grub and btrfs may not play along well.

and how to fix it?

Have you considered saving yourself this headache and moving the /boot outside of btrfs?
You could carve out a bit of space (shrink down the swap partition by 1G - swap is overrated anyway) and get yourself a new /boot partition of this extra 1G.
For disk redundancy you can use software raid1 - grub supports it quite well.
You would lose the snapshot capability for /boot, though /boot is small enough to have some other way to recover it.


Q: How can i format a string as currency in a data bound DataGrid in WPF C#? I have some data being shown in a DataGrid.  The data comes from SQL, where a "money" type can be null.  When i display this data, all is OK when i format the data in a double column format as currency.  ie:
internal void FillGrid()
        {
        bD = new DataTable();
        DataTable dt = EmployerQuery();  //queries the SQL DB

        bD.Columns.Add(new DataColumn("ID", typeof(int)));
        bD.Columns.Add(new DataColumn("EmployerName", typeof(string)));
        bD.Columns.Add(new DataColumn("FlatMinAmount", typeof(double)));
        bD.Columns.Add(new DataColumn("DistrictRate", typeof(double)));
        bD.Columns.Add(new DataColumn("VendorRate", typeof(double)));
        bD.Columns.Add(new DataColumn("Description", typeof(string)));
        bD.Columns.Add(new DataColumn("EmployeeCount", typeof(int)));

        foreach (DataRow sqlRow in dt.Rows)
        {
            var row = bD.NewRow();
            row["ID"] = sqlRow["ClientID"];
            row["EmployerName"] = sqlRow["OfficialName"];
            row["FlatMinAmount"] = sqlRow["FlatMinAmount"];
            row["DistrictRate"] = sqlRow["DistrictRate"];
            row["VendorRate"] = sqlRow["VendorRate"];
            row["Description"] = sqlRow["Description"];
            row["EmployeeCount"] = sqlRow["EmployeeCount"];

            bD.Rows.Add(row);

        }

However, I then save the data as a .csv file.  When i read that file back, the values for "FlatMinAmount" that were null are not allowed to be inserted into a column type double, so I cannot format the data columns as type double, since many are null.
<dg:DataGrid Name="newGrid" ItemsSource="{Binding ElementName=readGrid, Path=readGrid}" AutoGenerateColumns="False"
                 Margin="5" Height="175" Width="Auto" ColumnWidth="Auto">
        <dg:DataGrid.Columns>
            <dg:DataGridTextColumn Binding="{Binding ID}" Header="Employer ID" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding EmployerName}" Header="Employer Name" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding FlatMinAmount, StringFormat=C}" Header="FlatMinAmount" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding DistrictRate, StringFormat=C}" Header="District Rate" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding VendorRate, StringFormat=C}" Header="Vendor Rate" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding Description}" Header="Description" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding EmployeeCount}" Header="EmployeeCount" Width="*" IsReadOnly="True"/>
        </dg:DataGrid.Columns>
    </dg:DataGrid>

DataTable r = new DataTable();

        try
        {
            //string csv = string.Empty;

            //r.Columns.Add("ID", typeof(int));
            //r.Columns.Add("EmployerName", typeof(string));
            //r.Columns.Add("FlatMinAmount",typeof(double));
            //r.Columns.Add("DistrictRate", typeof(double));
            //r.Columns.Add("VendorRate", typeof(double));
            //r.Columns.Add("Description", typeof(string));
            //r.Columns.Add("EmployeeCount", typeof(int));

            r.Columns.Add("ID");
            r.Columns.Add("EmployerName");
            r.Columns.Add("FlatMinAmount");
            r.Columns.Add("DistrictRate");
            r.Columns.Add("VendorRate");
            r.Columns.Add("Description");
            r.Columns.Add("EmployeeCount");

            // Read sample data from CSV file
            using (CsvFileReader reader = new CsvFileReader(filename))
            {
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row))
                {
                    //foreach (string s in row)
                    {
                        r.Rows.Add(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);

                    }

                }
            }

(readGrid is then set to r in code-behind)
If they are string, then i cannot use the StringFormat=C in the binding to show $ etc.  Also, it seems I cannot style a DataGridTextColumn.  So, how can i display the values I read in from .csv as $xx.xx?

A: use Double.Parse() - http://msdn.microsoft.com/en-us/library/system.double.parse.aspx to format the value when you read it in.  This will allow you to use double and you can then apply the appropriate formatting for output.
Updated:
The issue you seem to be having that when reading from file the value is null and when reading from database it is DBNull.  By default DataTable allows for DBNull values.  If you want to mimic this for read, try the following
    DataTable r = new DataTable();
    try
    {
        r.Columns.Add("ID");
        r.Columns.Add("EmployerName");
        r.Columns.Add("FlatMinAmount");
        r.Columns.Add("DistrictRate");
        r.Columns.Add("VendorRate");
        r.Columns.Add("Description");
        r.Columns.Add("EmployeeCount");

        // Read sample data from CSV file
        using (CsvFileReader reader = new CsvFileReader(filename))
        {
            CsvRow row = new CsvRow();
            while (reader.ReadRow(row))
            {
                //foreach (string s in row)
                {
                    double d;
                    double? val2 = null;
                    double? val3 = null;
                    double? val4 = null;
                    if (Double.TryParse(row[2], out d)) val2 = d;
                    if (Double.TryParse(row[3], out d)) val3 = d;
                    if (Double.TryParse(row[4], out d)) val4 = d;

                    r.Rows.Add(row[0], row[1], val2, val3, val4, row[5], row[6]);
                }

            }
        }

A: Use the TargetNullValue attribute:
<dg:DataGridTextColumn Binding=""{Binding FlatMinAmount,TargetNullValue='Not Specified',StringFormat=C}" Header="FlatMinAmount" Width="Auto" IsReadOnly="True"/>

A: If you know the number is null, can't you just set the value of the column to DBNull?
row["FlatMinAmount"] = DBNull.Value;

Here's a little console app I ran to show this working:

class Program
    {
        static void Main(string[] args) {
            DataTable tbl = new DataTable();
            DataColumn col = new DataColumn("Blah", typeof(double));
            tbl.Columns.Add(col);

            DataRow row = tbl.NewRow();
            row["Blah"] = DBNull.Value;

            Console.WriteLine("Result: " + row["Blah"].ToString());
            Console.ReadKey();

        }
    }


Q: Can I extend to a continuous function?
Suppose that $f: \mathbb{R}^n\setminus\{0\} \to \mathbb{R}$ is differentiable. Assume $\lim\limits_{x \to 0}\frac{\partial f}{\partial x_j}$ exists for each $j \in \{1,2,\dots,n\}$.

Can $f$ be extended to a continuous function on $\mathbb{R}^n$? Furthermore, if we assume continuity at the origin, is $f$ differentiable on $\mathbb{R}^n$?
I can't really come up with counter examples or a proof for either questions. For the second question, I know that if $n =1$, $f$ can be extended to a differentiable function (a L'Hopitals argument), but is this true in general?

A: Yes.
Assume the partial derivatives have a finite limit towards 0. Then, in some neighborhood of 0, their absolute value is bounded by some constant $M$. By breaking it up into segments along each coordinate separately, you can show for any points $x_1$,$x_2$ in this neighborhood, that $|f(x_1)-f(x_2)|\leq M |x_1-x_2|$. You can use this to show that any sequence approaching 0 is Cauchy, so the limit exists.

A: I think that I can answer your second question with yes. Let $i \in \lbrace 1, ..., n \rbrace$ be a coordinate direction and for some given $t \in \mathbb{R} \setminus \lbrace 0 \rbrace$ let $g_t:[0, 1] \rightarrow \mathbb{R}$
$$
g_t(s) := f(tse_i),
$$
where $e_i$ is the $i$-th unit vector. Then, because of differentiability, we have $g_t'(s) = t\partial_i f(tse_i)$ according to the chain rule. The mean value theorem gives us some $\xi_t \in [0, 1]$ such that ($t \in \mathbb{R} \setminus \lbrace 0 \rbrace$)
$$
\frac{f(te_i) - f(0)}{t} = \frac{g_t(1) - g_t(0)}{t} = \frac{g_t'(\xi_t)}{t} = \partial_i f(\xi_t t e_i)
$$
whereas the last expression converges to $\lim_{x \rightarrow 0} \partial_i f(x)$ whose existence we assumed. So the partial derivatives $\partial_i f(0)$ exist and are by assumption continuous. So $f$ is differentiable in $0$.
The first question I can not quite answer (yet). But if you wanted to construct a counterexample, you must have strong oscillation near the origin.


Q: I can't enqueue my scripts - They literally aren't being added to my site Ok, I've literally copy-pasted different enqueueing code from about 5 different sources (Including wordpress), and not a single one works.
Here's the code I'm using in functions.php:
<?php

function my_theme_scripts() {
    wp_register_script(
        'main',
        get_stylesheet_directory_uri() . '/js/main.js',
        array( 'jquery' ), '1.0.0', true
    );
    wp_enqueue_script('main');
}

add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

?>

and it literally does nothing. No scripts added into my HTML. nothing.
This is my first time using wordpress, and nobody has explained the functions file to me completely right, but from my understanding, i don't do anything like  do I?
I've also put <?php wp_footer(); ?> right before </body> if that means anything.
EDIT:
I've solved the problem
Stupidly, I'd forgotten to add <?php wp_head(); ?> right before </head>, this screwed it all up. I also changed the 'main' identifier to something more unique, which didn't change anything but might be a better practice anyway.

A: The codex suggests using the function get_stylesheet_directory() in this instance as the get_template_directory_uri() can get overriden by child themes.

*

*get_template_directory_uri()

*get_stylesheet_directory()
In my experience WordPress can sometimes provide 2 or 3 similar functions.

A: You should register js file. Please read WordPress codex
https://codex.wordpress.org/Function_Reference/wp_enqueue_script


Q: Can you edit a workout? I mistakenly selected an outdoor walk instead of an outdoor run in the Workout app for Apple Watch. I realised after my run and wondered if there was a way to edit the type of workout on the iPhone?
Looking back at my workout history, it looks a little ridiculous.


Q: ag grid not retrieving data when mounted with vue using axios I have this strange case when trying to retrieve data from mongoDB using axios not showing on grid. It should be already successful given the data can already loaded into the view (already tested it), but it's nowhere inside beforeMount, mounted, or ready hook.
I already tried with
this.gridOptions.onGridReady = () => {
      this.gridOptions.api.setRowData(this.ticketData)
    }

but only yields partial success (unreliable),
here's a code snippet to show what I mean,
<template>
  <div class="ticketing">
    <ag-grid-vue  style="width: 100%; height: 350px;"
                  class="ag-fresh"
                  :gridOptions="gridOptions"
                  >
    </ag-grid-vue>
    {{testData}} <!--testData can be loaded-->
    <input type="button" @click.prevent="showData" value="test">  </div>
</template>

<script>
//import stuff

//header and url stuff

export default {
//component stuff

  data () {
    return {
      gridOptions: null,
      ticketData: [],
      testData: [] // only for testing purpose
    }
  },
  methods: {
     showData () {
      console.log('data shown')
      this.testData = this.ticketData // this is working
    }
  },
  beforeMount () {
    var vm = this
    axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}})
      .then(function (response) {
        vm.ticketData = response.data
      }) // this is working
      .catch(function (error) {
        console.log(error)
      })
    this.gridOptions = {}
    this.gridOptions.rowData = this.ticketData // this is not working
    this.gridOptions.columnDefs = DummyData.columnDefs
  }
 // mount, ready also not working
}
</script>

To be more specific, I still can't determine what really triggers onGridReady of ag-grid in conjunction with Vue component lifecycle, or in other words, how can I replace button to show testData above with reliable onGridReady/Vue component lifecycle event?

A: You define vm.ticketData and after you call it like this.ticketData
You can change it by: this.rowData = vm.ticketData

A: You are setting this.gridOptions.rowData outside of the axios callback, so this.ticketData is still empty.
Set it inside the callback:
mounted() {
  var vm = this
  axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}})
    .then(function (response) {
      vm.ticketData = response.data
      vm.gridOptions = {}
      vm.gridOptions.rowData = vm.ticketData
      vm.gridOptions.columnDefs = DummyData.columnDefs
    })
    .catch(function (error) {
      console.log(error)
    })
}

A: it is due to overlapped intialization between axios, ag-grid, and vue.
after much tinkering, I am able to solve it with using Vue's watch function:
  watch: {
    isAxiosReady(val) {
      if (val) {
        this.mountGrid() // initiate gridOptions.api functions
      }
    }
  }


Q: unexpected character '?' express When I run my server.js file I get a syntax error with something along the lines like the following:

Unexpected character ?  in the file @babel\core\lib\transformation\normalize-file.js:209

When I try to execute my server.js with following code:
import path from 'path';
import express from 'express';

var app = express();
var port = 3000;

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

But its fine if I run it with following code:
import http from 'http';

http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

There seems to be an issue with express and babel maybe?
I'll add the package.json and the .babelrc below:
package.json:
{
  "name": "counter",
  "version": "0.0.1",
  "private": true,
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/core": "^7.0.1",
    "@babel/node": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "babel-plugin-dynamic-import-node": "^2.1.0",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "express": "^4.16.3",
    "nodemon": "^1.18.4",
    "path": "^0.12.7",
    "react": "^16.5.1",
    "react-dom": "^16.5.1",
    "react-scripts": "^1.1.4"
  },
  "dependencies": {
    "prop-types": "^15.6.1",
    "react-redux": "^5.0.7",
    "redux": "^3.5.2"
  },
  "scripts": {
    "start": "nodemon --exec babel-node server\\server.js ",
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "test": "react-scripts test"
  }
}

.babelrc:
{
  "presets": ["@babel/preset-react","env"],
  "plugins": ["@babel/plugin-syntax-dynamic-import","dynamic-import-node"]
}


Q: Nested ALOGD statement I have situation where:
#define DBG_ALOGD(a)   ALOGD("%s:%d: ", __FUNCTION__, __LINE__); ALOGD a
#define DBG_MSG(a)    do { if (debuggable) {DBG_ALOGD(a);} } while (0)

DBG_MSG(a) used by the applications to print the logs.
DBG_MSG("Hi %d", 2);
will  print as
LOG_TAG: function_name:121
LOG_TAG: Hi 2

I wanted combine FUNCTION:LINE along with the "Hi 2" in single line.
I tried
#define DBG_ALOGD(a)   ALOGD("%s:%d:%s", __FUNCTION__, __LINE__, a)
#define DBG_MSG(a)    do { if (debuggable) {DBG_ALOGD(a);} } while (0)

It didn't worked as a is not a plain string it also have %d
Please suggest how can I change the #define to have a combination of these.

A: I think you can use the macro variable parameters (variadics) :
#include <stdio.h>

#define DBG_ALOGD(fmt, ...)   ALOGD("%s:%d: " fmt, __FUNCTION__, __LINE__, __VA_ARGS__ );
#define DBG_MSG(fmt, ...)    do { if (debuggable ) {DBG_ALOGD(fmt, __VA_ARGS__ );} } while (0)

int main(void)
{
    int debuggable = 1;
    DBG_MSG("%s(%d)\n", "test", 0);
    DBG_MSG("%s", "hello");

    return 0;
}

I tested it with printf function instead of ALOGD, but I think that the result will be the same.
Warning, you will not be able to call directly DBG_MSG("simple string") since the compiler will wait for something not empty in ...