text:
Q: Can't update Centos 6 kernel with yum, uname -r is still showing the old version I sended those commands:
# yum install kernel
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * base: centosr3.centos.org
 * extras: centosg4.centos.org
 * updates: centosg4.centos.org
Setting up Install Process
Package kernel-2.6.32-279.2.1.el6.i686 already installed and latest version
Nothing to do

# yum install kernel-devel
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * base: centosr3.centos.org
 * extras: centosg4.centos.org
 * updates: centosg4.centos.org
Setting up Install Process
Package kernel-devel-2.6.32-279.2.1.el6.i686 already installed and latest version
Nothing to do

#uname -r
2.6.32-042stab057.1
#uname -a
Linux asteriskserver 2.6.32-042stab057.1 #1 SMP Fri Jun 22 02:17:07 MSD 2012 i686 i686 i386 GNU/Linux

As you can see is still running an old revision of 2.6.32 kernel, while yum says that i've another version installed.
I rebooted the system, it's a vps.

A: In most VPS environments used in server virtualization, like openvz, the virtual servers have direct access to the host's kernel for performance, so you cannot update your kernel version because you are sharing the host's kernel with all of the other virtual machines on the host.
If this is not true in your case and your Hoster is not doing that, maybe something is wrong with your bootloader. In most cases, the boot loader installed is GRUB. Have a look at the GRUB chapter in the CentOS-guide.


text:
Q: Increase, decrease value in Input and don't show negative number I am trying to make input form and its value can be increased and decreased by click +1 / -1 buttons and I have +5 / -5 button also.
When the value is 3 and click -5 button, the value become -2.
But I don't want to show negative number. I want minimum number is always "0".  Even the result value is negative number.
How do I fix the code?

$(function() {
  $(".plus").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value < 30) {
      value = value + 1;
    } else {
      value = 30;
    }

    $input.val(value);
  });

  $(".plus2").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value < 30) {
      value = value + 5;
    } else {
      value = 30;
    }

    $input.val(value);
  });

  $(".minus").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value > 0) {
      value = value - 1;
    } else {
      value = 0;
    }

    $input.val(value);
  });

  $(".minus2").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value > 0) {
      value = value - 5;
    } else {
      value = 0;
    }

    $input.val(value);
  });

});
.change_qty {
  display: inline-block;
  color: #fff;
  background: #2e748e;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  font-weight: 900;
  line-height: 22px;
}

.cursor_hover {
  cursor: hand;
  cursor: pointer;
}

.change_qty {
  display: inline-block;
  color: #fff;
  background: #2e748e;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  font-weight: 900;
  line-height: 22px;
}

.cursor_hover {
  cursor: hand;
  cursor: pointer;
}

-5

-1

  <input type="numeric" style="height:22px;width:40px;margin:0 .5em;text-align:center;" value="0">

+1

+5

This is what I tried here
http://jsfiddle.net/a5ktensk/63/

A: Just change the if statement should do the trick.
http://jsfiddle.net/a5ktensk/68/
if (value > 5) {
    value = value - 5;
}
else {
    value = 0;
}

Another option would be.
value = value -5;
if(value < 0) {
    value = 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Overriding settings in Django when used by the models We are using Django for Speedy Net and Speedy Match (currently Django 2.1). Some of our settings are used by the models. For example:
class USER_SETTINGS(object):
    MIN_USERNAME_LENGTH = 6
    MAX_USERNAME_LENGTH = 40

    MIN_SLUG_LENGTH = 6
    MAX_SLUG_LENGTH = 200

    # Users can register from age 0 to 180, but can't be kept on the site after age 250.
    MIN_AGE_ALLOWED_IN_MODEL = 0  # In years.
    MAX_AGE_ALLOWED_IN_MODEL = 250  # In years.

    MIN_AGE_ALLOWED_IN_FORMS = 0  # In years.
    MAX_AGE_ALLOWED_IN_FORMS = 180  # In years.

    MIN_PASSWORD_LENGTH = 8
    MAX_PASSWORD_LENGTH = 120

    MAX_NUMBER_OF_FRIENDS_ALLOWED = 800

    PASSWORD_VALIDATORS = [
        {
            'NAME': 'speedy.core.accounts.validators.PasswordMinLengthValidator',
        },
        {
            'NAME': 'speedy.core.accounts.validators.PasswordMaxLengthValidator',
        },
    ]

(which is defined in https://github.com/speedy-net/speedy-net/blob/staging/speedy/net/settings/global_settings.py). And then in the models I use:
from django.conf import settings as django_settings

class User(ValidateUserPasswordMixin, PermissionsMixin, Entity, AbstractBaseUser):
    settings = django_settings.USER_SETTINGS

(and then use attributes of settings, such as settings.MIN_SLUG_LENGTH, in the class).
The problem is, when I try to override such settings in tests (you can see my question & answer on Can I define classes in Django settings, and how can I override such settings in tests?), User.settings remains the same and is not overridden by the settings I tried to override. This is a problem since in the model I passed settings.MIN_SLUG_LENGTH for example to validators, which are also passed other values by other models. Is it possible to define the models and settings in such a way which the correct settings will be used both in production and in tests, including when I want to override them?
I'm aware of this quote from https://docs.djangoproject.com/en/dev/topics/testing/tools/#overriding-settings:

Warning
The settings file contains some settings that are only consulted
  during initialization of Django internals. If you change them with
  override_settings, the setting is changed if you access it via the
  django.conf.settings module, however, Django's internals access it
  differently. Effectively, using override_settings() or
  modify_settings() with these settings is probably not going to do what
  you expect it to do.
We do not recommend altering the DATABASES setting. Altering the
  CACHES setting is possible, but a bit tricky if you are using
  internals that make using of caching, like django.contrib.sessions.
  For example, you will have to reinitialize the session backend in a
  test that uses cached sessions and overrides CACHES.
Finally, avoid aliasing your settings as module-level constants as
  override_settings() won't work on such values since they are only
  evaluated the first time the module is imported.

Which I understand are relevant in this case, but how do I define the settings in such a way that I can override them?
Function _1___set_up in speedy/core/base/test/models.py is a workaround to make the tests work, but this is a hack and I don't think it's a good solution for the long term.

A: The problem, as you quoted:

avoid aliasing your settings as module-level constants as override_settings() won't work on such values since they are only evaluated the first time the module is imported.

There are 3 ways around this, where Way 1 > Way 3 > Way 2.
Way 1: Don't alias with class attribute, but classproperty
Recommended; arguably the correct way.

*

*Pro: Most expressive, easier to debug.

*Con: More code in model.

from django.utils.decorators import classproperty

class User(PermissionsMixin, Entity, AbstractBaseUser):
    # settings = django_settings.USER_SETTINGS
    @classproperty
    def settings(cls):
        return django_settings.USER_SETTINGS

Caveat: Class attributes that depend on the settings class attribute won't work.
Although Way 2 allows the following code to still be valid, these are evaluated at class definition (import) time and cannot reasonably change based on override_settings(), unless they are classproperty too.
AGE_VALID_VALUES_IN_MODEL = range(settings.MIN_AGE_ALLOWED_IN_MODEL, settings.MAX_AGE_ALLOWED_IN_MODEL)
AGE_VALID_VALUES_IN_FORMS = range(settings.MIN_AGE_ALLOWED_IN_FORMS, settings.MAX_AGE_ALLOWED_IN_FORMS)

Way 2: Patch settings class so instances read django_settings
Not recommended; impacts the runtime evaluation of USER_SETTINGS also in production, not only in tests (@hynekcer).

*

*Pro: No code change in model.

*Con: Least expressive, more difficult to debug.

*

*Define a function overridable_settings:

def overridable_settings(settings_class):
    old__getattribute__ = settings_class.__getattribute__
    settings_name = settings_class.__name__

    def patched__getattribute__(_self, item):
        from django.conf import settings as django_settings
        settings = getattr(django_settings, settings_name)
        return old__getattribute__(settings, item)

    settings_class.__getattribute__ = patched__getattribute__
    return settings_class()

*django_settings.USER_SETTINGS is now an instance of the settings class. Instead of get_django_settings_class_with_override_settings, define override_settings:

import copy

def override_settings(settings, **overrides):
    copied_settings = copy.deepcopy(settings)
    for setting, value in overrides.items():
        setattr(copied_settings, setting, value)
    assert copied_settings != settings
    return copied_settings

Usage:
@overridable_settings
class USER_SETTINGS(object):

from speedy.core.base.test import utils

# @override_settings(USER_SETTINGS=get_django_settings_class_with_override_settings(django_settings_class=django_settings.USER_SETTINGS, MIN_SLUG_LENGTH=tests_settings.OVERRIDE_USER_SETTINGS.MIN_SLUG_LENGTH))
@override_settings(USER_SETTINGS=utils.override_settings(django_settings.USER_SETTINGS, MIN_SLUG_LENGTH=tests_settings.OVERRIDE_USER_SETTINGS.MIN_SLUG_LENGTH))
def test_slug_min_length_fail_username_min_length_ok(self):

Way 3: Create receiver of signal setting_changed to update alias

*

*Pro: Minimal code change to model.

*Con: Less expressive than Way 1 with regard to the dependent attributes in the Caveat.

From https://docs.djangoproject.com/en/dev/topics/testing/tools/#overriding-settings:

When overriding settings, make sure to handle the cases in which your app's code uses a cache or similar feature that retains state even if the setting is changed. Django provides the django.test.signals.setting_changed signal that lets you register callbacks to clean up and otherwise reset state when settings are changed.
Django itself uses this signal to reset various data.

from django.core.signals import setting_changed
from django.dispatch.dispatcher import receiver

def register_django_setting_alias(setting_alias, django_setting):
    def decorator(cls):
        @receiver(setting_changed, weak=False)
        def update_setting_alias(setting, value, **_):
            if setting == django_setting:
                setattr(cls, setting_alias, value)
        return cls
    return decorator

Usage:
@register_django_setting_alias('settings', 'USER_SETTINGS')
class User(PermissionsMixin, Entity, AbstractBaseUser):
    settings = django_settings.USER_SETTINGS


text:
Q: c++ converting from char to string? Im having some issues in converting a char value of a vector to a string.
I have a globaly declared vector as such.
std::vector<Musician> aMusician;

that stores values from a file read into a struct
struct Musician {
char code;
int impact;
};

code is a single char of values either A,B,C,D,E,F,G or H
I have a function that takes in a string value and checks if this string value contains any of the possiblle codes(example string x = ABCD, it would contain the codes A B C and D). A standard string target is used to store the char after conversion using a stringstream.
its used like so
std::stringstream ss;
std::string target;

 for (Musician musc : aMusician)
    {
      ss << musc.code;
      ss >> target;

if (target.find(variable1.at(0)) != std::string::npos) {
//code
}

}

However they do not match. Target is only storing A where as the vector contains A,B,C,D,E,F,G,H. Or in other words Target is only storing the first code.
Below is a test output of when i print both target and the vector values
vector: A
target: A
vector: B
target: A(should be B)
vector: C
target: A (should be C.....etc)
vector: D
target: A
vector: E
target: A
vector: F
target: A
vector: G
target: A
vector: H

Below are example records of the files being and used and how they match
file contains code(in this case A)
A:Lead singer:2:10:3.
B:Backing singer:5:2:2.
C:Guitarist:3:6:2.
D:Singing guitarist:2:8:3.

file containing word to match(for exmaple in this case A matches with A1 and band1)
band1:A1B3C4.
band2:A4B1C5D1E1H5


text:
Q: How can "start" be used in past continuous? Another multiple-choice question:

What were you doing when Lucy phoned you?
I had just finished my work and _____ to read a book.

The answer is "was starting." I think the answer is wrong by itself. Since "start" is a transient verb, it can't be used in past continuous.

I've made a mistake, which is not the focus of the question, by writing present continuous instead of past continuous.

"The action of starting a car continues until the car has started and you release the starter." but I think it happens too fast to be considered a continuous event.

A: Please be aware that the question has been edited and it is significantly different to when I answered it

I had just finished my work and was starting to read a book.
Q. The answer is "was starting." I think the answer is wrong by itself. Since "start" is a transient verb, it can't be used in present continuous.
I would suggest that the answer is correct

transient; adjective; lasting for only a short time; temporary:
Although an action may only last for a short time it may be continuous whilst it is happening. Temporary & Continuous are not mutually exclusive. The action of walking continues until you stop walking. The action of starting a car continues until the car has started and you release the starter.
Starting the car, Starting the race, starting a war

Q. How can "start" used in present continuous? How can "start" be used in the Present Continuous Tense?
Present Continuous: form; We use am, are, is + the -ing form of the verb
I am starting the car.
However in this case I think you are confusing the Present Continuous with the Past Continuous
Past continuous: form; We use was/were + the -ing form of the verb.
"I had just finished my work and was starting to read a book".
Past continuous: uses; Events happening at a particular time in the past
We generally use the past continuous to talk about actions and states in progress (happening) around a particular time in the past. It can emphasise that the action or state continued for a period of time in the past:
Where was Donna last night? I'm not sure. I think she was visiting her family. (action)
or
I remember that night. You were wearing that red dress. (state)
Ref CED Past continuous

Ref CED present participle -ing
-ing: used to form the present participle of regular verbs:
present participle; a form of a verb that in English ends in -ing and comes after another verb to show continuous action. It is used to form the present continuous:
In the sentences "The children are watching television", "The weather is getting colder", and "I heard him singing", "watching", "getting", and "singing" are present participles.


text:
Q: Almost sure convergence to mean with a logarithm Let $(X_n)$ be i.i.d. random variables with mean $\mu$. Show that
$$\lim _{n \rightarrow \infty} \frac{1}{\log n} \sum_{i=1}^{n} \frac{X_{i}}{i}=\mu$$
almost surely.
I am thinking of letting $T_n=\frac{1}{\log n} \sum_{i=1}^{n} \frac{X_{i}}{i}$ then applying Markov's inequality to get
$$\Pr(|T_n - \mu|>\epsilon) \leq \frac{\mathbb{E}|T_n-\mu|}{\epsilon^2}$$
and somehow getting a summable sequence to apply the Borel-Cantelli Lemmas. But I don't really know how.

A: Unfortunately, it seems hard to get a good control on $\mathbb{E}|T_n-\mu|$.
However, we can use the classical strong law of large numbers. First, using the fact that $\sum_{i=1}^ni^{-1}/\log n\to 1$, we can assume that $\mu=0$. Then denote $S_i=\sum_{k=1}^iX_i$, $S_0=0$  and write
$$
\frac 1{\log n}\sum_{i=2}^n \frac{S_i-S_{i-1}}i=\frac 1{\log n}\sum_{i=2}^n \left(\frac{S_i}{i}-\frac{S_{i-1}}{i-1}\right)+\frac 1{\log n}\sum_{i=2}^n S_{i-1}\left( \frac{1}{i-1}-\frac 1i\right).
$$
The first sum telescops, for the second one, use the fact that if $c_i\to 0$, then
$$
\frac 1{\log n}\sum_{i=2}^nc_i/i\to 0.
$$


text:
Q: How to add a footer using AddFooterView with text from a String? I've made an application with a ListView. I'm to trying to add a footer to my ListView (which scrolls along with the ListView), using addFooterView. In this footer I want to add a TextView with some text which is defined in my Activity as a String called notification.
I've tried several things but it wouldn't work.
My ListActivity, RoosterWijzigingen.java:
public class RoosterWijzigingen extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        ArrayList<HashMap<String, String>> roosterwijziginglist = new ArrayList<HashMap<String, String>>();

        String hour = "4";
        String info = "Af 123";
        String notification = "Het is 40min-rooster!";

        // Creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();

        // Adding each child node to HashMap key => value
        map.put("hour", hour);
        map.put("info", info);

        // Adding HashList to ArrayList
        roosterwijziginglist.add(map);}

        ListAdapter adapter = new SimpleAdapter(this, roosterwijziginglist , R.layout.roosterwijzigingen,
                            new String[] {"hour", "info"},
                            new int[] {R.id.hour, R.id.info});
        setListAdapter(adapter);

        setContentView(R.layout.listplaceholder);
   }
}

I get the information for the strings hour, info and notification from a JSON file, but I omited this to shorten the code.
listplaceholder.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

        <ListView
                         android:id="@+id/android:list"
                         android:layout_width="fill_parent"
                         android:layout_height="wrap_content"
                         android:drawSelectorOnTop="true" />

        <TextView
                         android:id="@id/android:empty"
                         android:layout_width="fill_parent"
                         android:layout_height="wrap_content"
                         android:text="No data" />

roosterwijzigingen.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

        <TextView
                         android:id="@+id/hour"
                         android:layout_width="wrap_content"
                         android:layout_height="fill_parent" />

        <TextView
                         android:id="@+id/info"
                         android:layout_width="match_parent"
                         android:layout_height="fill_parent" />
</LinearLayout>

A: You have to put your String in a TextView before adding it to your list, and it will look something like that :
String footerText = "Footer text";
TextView textView = new TextView(this);
textView.setText(footerText);

getListView().addFooterView(textView);

Remember that 99% of the time when you want to display something on the screen, it has to be a View.


text:
Q: Own function for focal statistics (focal, "raster" package, R) gives incorrect output I am a beginner in R and programming. So I think than the question is simple, but I can't to find the answer or solve it solus.
I have the raster (100*100 cells). I need to get the median value of harmonic's magnitudes by 2D DFT at the moving window (for example, size of window = 21).
I finded the focal function in the raster package. For this function I can code own function which take seria of values (raster values in window) and return individual value for the whole window.
r <- raster(matrix(rnorm(10000), nrow = 100, ncol = 100)) # creation of raster
win <- 21 # setting the window size
spectr <- function(d) {
  return(median(abs(spec.fft(x = 1:win, y = 1:win, z = (d - mean(d)))$A)))
} # i think "d" - the matrix of raster values in the window border
focal(x = r, w = matrix(1, win, win), fun = spectr())

The output:  Error in spec.fft(x = 1:win, y = 1:win, z = (d - mean(d))) :
  argument "d" is missing, with no default
I presumed that data from window is transmitted in the function automatically. What the mistake in my code? Thank you!
UPDATE. For testing is need to load the library "spectral":
install.packages("spectral")
library(spectral)

A: First, To use the function you defined previously in focal(), you just need to remove the parentheses () after the function name.
Second, your function using spectral::spec.fft which requires the z argument to be a matrix. However, focal forwards a vector of values, as we learn from ?focal:

The function fun should take multiple numbers, and return a single number.

Therefore, you have to generate the required matrix yourself.
See this example (however, please check for validity of the output):
spectr <- function(d) {
  return(median(abs(spec.fft(x = 1:win, y = 1:win,
                             z = (matrix(d, ncol = win, nrow = win) - mean(d)))$A
                             # eventually you have to reorder or transpose the matrix
                             # if its order has some impact on spec.fft
                    )))
}

Let's use the function in focal()
focal(x = r, w = matrix(1, win, win), fun = spectr)
# class       : RasterLayer
# dimensions  : 100, 100, 10000  (nrow, ncol, ncell)
# resolution  : 0.01, 0.01  (x, y)
# extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
# coord. ref. : NA
# data source : in memory
# names       : layer
# values      : 0.03341064, 0.04557778  (min, max)


text:
Q: Extend object lifetime/scope from a `if constexpr` branch Say we have the following code
struct MyClass
{
    MyClass() = delete;  // or MyClass() { }
    MyClass(int) { }
    void func() { }
};

int main()
{
    if constexpr (std::is_default_constructible_v<MyClass>) {
        MyClass myObj;
    } else {
        MyClass myObj(10);
    }

    myObj.func();  // Error
}

Here I am using if constexpr to determine whether the class is default-constructible (or not), and then create an object accordingly. In a way, I naively thought this would simplify the different branches down to just the one that's true, i.e.
    if constexpr (true) {
        /* instruction branch 1 */
    } else if constexpr (false) {
        /* instruction branch 2 */
    }

simply becomes
    /* instruction branch 1 */

But in reality, it is probably more like this
    {
        /* instruction branch 1 */
    }

But then the question becomes (going to back to the the very first example), how can I can I keep myObj in scope outside the { ... }?

A: You can't extend the lifetime of an object with automatic storage duration beyond the scope in which it's created.
What you can do is create uninitialized storage outside your if block and create an object in that storage within the scope of the if.  The easiest way to do that is probably std::optional:
template <typename T>
void foo() {
    std::optional<T> obj;
    if constexpr (std::is_default_constructible_v<T>) {
        obj.emplace();
    } else {
        obj.emplace(10);
    }

    obj->func();
}

Live Demo
This does result in a small amount of overhead though, since std::optional has to hold an extra flag to determine if it holds an object or not.  If you want to avoid that overhead you could manage the storage yourself:
template <typename T>
void foo() {
    std::aligned_storage_t<sizeof(T), alignof(T)> storage;
    T* ptr;
    if constexpr (std::is_default_constructible_v<T>) {
        ptr = new(&storage) T{};
    } else {
        ptr = new(&storage) T{10};
    }
    struct destroy {
        destroy(T* ptr) : ptr_{ptr} {}
        ~destroy() { ptr_->~T(); }
        T* ptr_;
    } destroy{ptr};

    ptr->func();
}

Live Demo

Note that in both cases I've moved the functionality to a function template.  For if constexpr to discard a branch it must be dependent on a template parameter.  If you try to do this directly in main the false branch will not be discarded and you will get an error complaining about a missing default constructor.

A: First, your code won't work.  if constexpr really needs its condition to be dependent.
I'll fix it.
template<class MyClass>
void func() {
  MyClass myObj = []{
    if constexpr (std::is_default_constructible_v<MyClass>) {
      return MyClass{};
    } else {
      return MyClass(10);
    }
  }();
  myObj.func();
}

now
int main() {
  func<MyClass>();
}

solves your problem.
Note that under c++17 rules, no copies or moves of MyClass occur in the above code.


text:
Q: Getting error 'table' does not contain a defination for 'Add' and no extension method 'Add' using mvc c# with edmx linq? I am going to create a module for the add product to wish list table using MVC C#. For that I have used Entity Framework. I have crated on dbml class in the model folder. I am go for add product in to wish list i am getting error like this :

"'table' does not contain a defination for 'Add' and no
  extension method 'Add' accepting a  first argumnets of type
  'table' could be found. (are you missing a using directive
  or an assembly reference?)"

I have not idea why this error generate here and what is missing here in my code any buddy then please let me know. here below  i have listed my code.
This is my dbml class in to table defintion :
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.WishList")]
public partial class WishList : INotifyPropertyChanging, INotifyPropertyChanged
{

    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);

    private int _Id;

    private string _Laminate_Sheet_Smo;

    private System.Nullable<int> _CustmorId;

    public List<WishList> list { get; set; }

    #region Extensibility Method Definitions
    partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnLaminate_Sheet_SmoChanging(string value);
partial void OnLaminate_Sheet_SmoChanged();
partial void OnCustmorIdChanging(System.Nullable<int> value);
partial void OnCustmorIdChanged();
#endregion

    public WishList()
    {
        OnCreated();
    }

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
    public int Id
    {
        get
        {
            return this._Id;
        }
        set
        {
            if ((this._Id != value))
            {
                this.OnIdChanging(value);
                this.SendPropertyChanging();
                this._Id = value;
                this.SendPropertyChanged("Id");
                this.OnIdChanged();
            }
        }
    }

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Laminate_Sheet_Smo", DbType="NVarChar(50)")]
    public string Laminate_Sheet_Smo
    {
        get
        {
            return this._Laminate_Sheet_Smo;
        }
        set
        {
            if ((this._Laminate_Sheet_Smo != value))
            {
                this.OnLaminate_Sheet_SmoChanging(value);
                this.SendPropertyChanging();
                this._Laminate_Sheet_Smo = value;
                this.SendPropertyChanged("Laminate_Sheet_Smo");
                this.OnLaminate_Sheet_SmoChanged();
            }
        }
    }

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CustmorId", DbType="Int")]
    public System.Nullable<int> CustmorId
    {
        get
        {
            return this._CustmorId;
        }
        set
        {
            if ((this._CustmorId != value))
            {
                this.OnCustmorIdChanging(value);
                this.SendPropertyChanging();
                this._CustmorId = value;
                this.SendPropertyChanged("CustmorId");
                this.OnCustmorIdChanged();
            }
        }
    }

    public event PropertyChangingEventHandler PropertyChanging;

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void SendPropertyChanging()
    {
        if ((this.PropertyChanging != null))
        {
            this.PropertyChanging(this, emptyChangingEventArgs);
        }
    }

    protected virtual void SendPropertyChanged(String propertyName)
    {
        if ((this.PropertyChanged != null))
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

This is class i have make custom in my model folder also :
 public class WishListCs
{
    [Key]
    public int id { get; set; }

    public string Laminate_Sheet_Smo { get; set; }

    public int CustmorId { get; set; }
}

This is my controller code :
    DataClasses1DataContext db = new DataClasses1DataContext();
if (!string.IsNullOrEmpty(CookieHelper.GetCookieValue(CookieKeys.WishLaminateId)))
            {

                string pids = CookieHelper.GetCookieValue(CookieKeys.WishLaminateId);
                var v = pids.Split(',');
                var length = v.Length;

                for (int i = 0; i < length; i++)
                {
                    WishList addtbl = new WishList();
                    addtbl.Laminate_Sheet_Smo = v[i];
                    addtbl.CustmorId = Convert.ToInt32(CookieHelper.GetCookieValue(CookieKeys.CustId));
                    db.WishLists.Add() // here  i am getting error
                    int UserId = Convert.ToInt32(CookieHelper.GetCookieValue(CookieKeys.CustId));
                    var h = db.WishLists.Where(x => x.CustmorId == UserId).Count();
                    CookieHelper.SetCookie(CookieKeys.CountOfCart, h.ToString());
                }
            }

This is my code please any one help me how can fix this error.

A: Try this:
WishList addtbl = new WishList();
addtbl.Laminate_Sheet_Smo = v[i];
addtbl.CustmorId = Convert.ToInt32(CookieHelper.GetCookieValue(CookieKeys.CustId));
db.WishLists.Add(addtbl); //Add the object into the DBSet
db.SaveChanges(); //Save changes to database.


text:
Q: Apply "Maximum Qty Discount is Applied to" to whole order instead of order line What seems to go wrong: It seems in the current situation the "Maximum Qty Discount is Applied to" applies to the order line instead of the total qty in the cart.
What I think that should happen: The "Maximum Qty Discount is Applied to" should use the total qty in the cart and if it is greater than "Maximum Qty Discount is Applied to" it shouldn't apply the rule.
What am I trying to achieve: It happens more than once that a customer buys something and something goes wrong, they want to give them, say 10% discount on the next product (not the whole order, just one product). Giving a fixed amount discount doesn't do it because there are different product prices, etc.
I haven't set up any special rules for the conditions (always applies) I've just created a coupon code to apply the rule.  Also it can match any product in the order, but preferably only the lowest.
Any ideas?

A: This isn't possible out of the box in Magento CE as far as I know so this will require you to extend the SalesRules.
Both Amasty and Fooman offer extended promo extensions. I've used the Fooman extension before and it offers tons of options. Might be worth giving them a try before you write your own code.


text:
Q: How to tag data in toggle buttons and loop through them to fetch the selected button's data I am trying to add toggle buttons dynamically in a linear layout. I have successfully done this- 2 rows with each row having 2 buttons.
Below is the code for it::
public class MainActivity extends Activity
{
LinearLayout VertLayout;
LayoutInflater inflater;

LinearLayout lnrLay_forXaxis;

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

    initialize();
    make_seat();
}

private void initialize()
{
    VertLayout = (LinearLayout) findViewById(R.id.lnrLyMain);
    inflater = (LayoutInflater) this.getLayoutInflater();
}

private void make_seat()
{
    try{
         for(int y=0;y<2;y++)
          {
             lnrLay_forXaxis = new LinearLayout(this);
                lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
                lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);

                LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);

                lnrLay_forXaxis.setLayoutParams(LLParams);
             for(int x=0;x<2;x++)
             {
                 final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
                 final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);

                    btt.setChecked(false);
                     btt.setText("btn-"+x+y);
                      btt.setTextOn("btn-"+ x+y+" -ON");
                     btt.setTextOff("btn-"+x+y);

                 lnrLay_forXaxis.addView(sngl_lnrLay);
             }

      VertLayout.addView(lnrLay_forXaxis);
          }

    }
    catch(Exception ex)
        {Log.d("exp",ex.toString());}

}

}
in activity_main.xml:
          <LinearLayout
                android:id="@+id/lnrLyMain"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#CCFFCC"
                android:orientation="vertical" >
            </LinearLayout>

in lnrly_btn.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >

    <ToggleButton
    android:background="@drawable/btn_toggle_bg"
    style="@style/YourThemeName"
    android:checked="true"
    android:id="@+id/ToggleButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
      android:layout_margin="3dp">
    </ToggleButton>
</LinearLayout>

Now i want to add some data with each toggle button(think it should be tag i should be using) and add another button to the activity(lets say button-x). So, after selecting few toggle buttons and then clicking on button-x; a toast/Log will appear showing the selected toggle buttons added/tagged values.
How can i do this.

A: You can do something like that:
Add field to your Activity:
ArrayList<View> toggles = new ArrayList<>();

Then:
for(int y=0;y<2;y++)
    {
        lnrLay_forXaxis = new LinearLayout(this);
        lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
        lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);

        LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);

        lnrLay_forXaxis.setLayoutParams(LLParams);
        for(int x=0;x<2;x++)
        {
            final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
            final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);

            Object tag; //your object,int, string ,whatever
            //init your tag
            btt.setTag(tag);
            btt.setChecked(false);
            btt.setText("btn-" + x + y);
            btt.setTextOn("btn-" + x + y + " -ON");
            btt.setTextOff("btn-" + x + y);
            toggles.add(btt);
            lnrLay_forXaxis.addView(sngl_lnrLay);
        }

        VertLayout.addView(lnrLay_forXaxis);
    }
    Button add = new Button(this);
    LayoutParams btParams = new LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    btParams.gravity = Gravity.CENTER;
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            for (View toggle: toggles)
                Log.d("TAG", toggle.getTag().toString());
        }
    });
    VertLayout.addView(add, btParams);


text:
Q: Good introductory Measure Theory Books & PhD Level Statistics Materials I am about to complete my master's degree in Statistics at a very well-respected university and one which has a top 5 statistics department in the U.S. (all I have left to do is defend my thesis).  I also have a BS Statistics from a top U.S. University as well.  Even though I'd like to, I'm doubtful I'll go on to complete a PhD given that (a) I'm older and (b) I work full time.
That being said, I'm very much interested in continuing my studies of statistics in my own time.  It seems like one thing I don't have much exposure to formally, but which every PhD statistics student seems to have a good understanding of, is measure theory.  Given my background and my desire to learn this material, could the Cross Validated community recommend some introductory measure theory materials and some additional statistics books that you think might be a must-learn or a great way for me to essentially learn some "PhD-level" statistics on my own time?  If it's helpful for the recommendations, my interests include survey sampling (especially small area estimation) and imputation, causal inference, longitudinal data analysis and analysis of correlated data.

A: My recommendation:
Start here: Measure Theory Made Ridiculously Simple.
Then buy and read Burrill.
I know its old, but its super inexpensive on Amazon and a really good read. It covers basics of Real Analysis and Probability Theory.


text:
Q: Does \s shorthand match newlines in PHP regex? Can \s match newlines or should I use the /s pattern modifier to make the . match newlines?
I don't want the regex to match 'anything'. Instead I want it to match just newlines/spaces.

A: According to regex101.com \s:

Matches any space, tab or newline character.

So yes, but it's not exactly what you are asking for. But it is a lot closer than using ., which has a tendency to cause catastrophic backtracking and general inefficiency.
If you want to just match spaces and new lines, you can use:
[ \n\r]


text:
Q: One MKNetworkEngine object when using MKNetworkKit I just switched over to using MKNetworkKit and I'm confused whether I should create one MKNetworkEngine object at App launch and use that whenever I want a net connection, or if I should be creating a new one each time?
If I needed to create just one and use it throughout the lifetime of the App, I would have assumed MKNetworkKit would create a singleton, but it doesn't seem to (not that I can see).
On the other hand, it seems cumbersome to alloc/init MKNetworkEngine every time I want to do a  simple GET request.
Something seems amiss, so I'm wondering it I'm using it correctly.

A: you create one engine for every webservice you intend to call and keep it as a strong property in the app delegate
(facebook = one engine / twitter = one engine / flickr = one engine)
The creator Mugunth Kuma writes this:

MKNetworkEngine is a pseudo-singleton class that manages the network queue in your application. It's a pseudo-singleton, in the sense, for simple requests, you should use MKNetworkEngine methods directly. For more powerful customization, you should subclass it. Every MKNetworkEngine subclass has its own Reachability object that notifies it of server reachability notifications. You should consider creating a subclass of MKNetworkEngine for every unique REST server you use. It's pseudo-singleton in the sense, every single request in any of it's subclass goes through one and only one single queue.

see this blog article

A: Etienne678 is right. You should create an engine for every webserver and set the global headers (like gzip) and others required by that server on the engine.
When you queue an operation, to an engine these headers are automatically appended.


text:
Q: missing drive after installation of Ubuntu I had widows before and I installed Ubuntu on it during installation I replace windows with Ubuntu right now I cannot see my D drive. And all the files which exited in D drive.
what is the way to access this?

A: Go to Terminal and run
lsblk

the result would be something like below:
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 531.5G  0 disk
├─sda1   8:1    0   350M  0 part
├─sda2   8:2    0 117.2G  0 part
├─sda3   8:3    0   466M  0 part
├─sda4   8:4    0     1K  0 part
├─sda5   8:5    0 384.4G  0 part
├─sda6   8:6    0  21.2G  0 part /
└─sda7   8:7    0   7.9G  0 part [SWAP]
sr0     11:0    1  1024M  0 rom

(If you see only sda1, that means your partition is formatted which means the chance for recovery is very low)
Based on the size of your D drive, you can find it here. I assume it is called sda5. Now we need to mount it for which we need a mount point. Make the mount point by running this command:
sudo mkdir /media/d

Now you have mount point. Mount your partition to it by running:
mount /dev/sda5 /media/d

If you get any error in any step, let me know.


text:
Q: How to run coverage.py in json mode on a module? I find coverage.py's CLI syntax to be overengineered: it would all be simpler if options on the format such as json or xml were specified as options instead of separate commands (which often have analogous options with completely different names compared to coverage run).
In particular, when I run coverage normally I do coverage run -m pytest to run pytest. If I want the report to be in JSON format however, the -m option is not available (coverage json -m pytest):

no such option: -m

But of course, coverage json pytest also doesn't work:

No source for code: '[redacted]\venv\Lib\site-packages\pytest': [Errno 13] Permission denied: '[redacted]\venv\Lib\site-packages\pytest'

So how am I supposed to do this?

A:
it would all be simpler if options on the format such as json or xml were specified as options instead of separate commands

You know that there are separate commands, you have to use them as separate commands:
coverage run -m pytest
coverage json

Running code and measuring it is one step, which writes a data file.  Then you generate a report from that file with another command.


text:
Q: Inflate textviews with differents values in a Layout I already looked for some answer on the internet but i didn't find so i'm asking for your help
I want to add a TextView everytime i click on a button but with a different value.
For exemple, first click adds a TextView with the number 1, second click adds a TextView with the number 2.
My app crashs everytime i call the method.
Here the code
public class Activity_Planification_Actu extends AppCompatActivity {

    LinearLayout mparent;
    LayoutInflater layoutInflater;
    int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_planification);
        mparent = findViewById(R.id.Layout1);
        layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    public void boutonTest(View v) {

        View myview = layoutInflater.inflate(R.layout.semaine_planif, null, false);
        TextView tv = (TextView) myview.findViewById(R.id.case_semaine);
        tv.setText(i);
        i++;
        mparent.addView(myview);

    }

}

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/include_entete_accueil"
        layout="@layout/tabdebut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="1647dp"
        android:layout_height="930dp"
        android:orientation="vertical"
        app:layout_constraintStart_toEndOf="@+id/include_entete_accueil"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:id="@+id/Layout1"
            android:layout_width="match_parent"
            android:layout_height="53dp"
            android:orientation="horizontal">

        </LinearLayout>

        <LinearLayout
            android:id="@+id/Layout2"
            android:layout_width="match_parent"
            android:layout_height="82dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout3"
            android:layout_width="match_parent"
            android:layout_height="94dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout4"
            android:layout_width="match_parent"
            android:layout_height="69dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout5"
            android:layout_width="match_parent"
            android:layout_height="87dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout6"
            android:layout_width="match_parent"
            android:layout_height="84dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout7"
            android:layout_width="match_parent"
            android:layout_height="91dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout8"
            android:layout_width="match_parent"
            android:layout_height="81dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout9"
            android:layout_width="match_parent"
            android:layout_height="63dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout10"
            android:layout_width="match_parent"
            android:layout_height="72dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout11"
            android:layout_width="match_parent"
            android:layout_height="82dp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:id="@+id/Layout12"
            android:layout_width="match_parent"
            android:layout_height="71dp"
            android:orientation="horizontal"></LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/boutontest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="35dp"
        android:onClick="boutonTest"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include_entete_accueil" />

</android.support.constraint.ConstraintLayout>

06-17 17:25:10.766 6841-6841/com.imsnancydaunot.imscoaching E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.imsnancydaunot.imscoaching, PID: 6841
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:5198)
        at android.view.View$PerformClick.run(View.java:21147)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:5198)
        at android.view.View$PerformClick.run(View.java:21147)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
        at android.content.res.Resources.getText(Resources.java:312)
        at android.widget.TextView.setText(TextView.java:4417)
        at categ_planification.Activity_Planification_Actu.boutonTest(Activity_Planification_Actu.java:34)
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:5198)
        at android.view.View$PerformClick.run(View.java:21147)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

https://i.stack.imgur.com/02iKs.png
To be more precised i want right to the textview another textview but with a different text

A: Your problem in:
tv.setText(i);

You call to setText with int argument and Android think that you pass String's resource id like tv.setText(R.string.some_text) and
cant find resource which id is equals to i i.e. 0 that's why this crash happend .
You should use:
tv.setText(String.valueOf(i));
//or
tv.setText("" + i);

A: provide Logcat
or
try this
can do with loop
LinearLayout my_ll = (LinearLayout) findViewById(R.id.Layout1);
        for(int i=0;i<your_number_of_textviews;i++)
        {
            TextView text = new TextView(this);
            text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            text.setText("text"+i);
            my_ll.addView(text);
        }

every button click logic
LinearLayout my_ll = (LinearLayout) findViewById(R.id.Layout1);
int clickcount=0; //set as global
yourbutton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        clickcount=clickcount+1;
        if(clickcount==0)
        {
            //check how many times clicked and so on
            //here, you can add textview without loop
            TextView text = new TextView(this);
            text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            text.setText("text"+clickcount);
            my_ll.addView(text);

    }
});


text:
Q: Bulk/ Batch insert in Mongo takes time 15 sec to 10000 documents Bulk insert in Mongo takes time i.e average 15 seconds to insert 10000 documents in a collection.
My System is 8 core and 16 GB RAM.
How can I reduce response time for Mongo Insertion? What mongo configurations can be done to reduce execution time?
db.getCollection('temp').insert([{id:1},{id:10000}])

Each document contain 25-30 properties. I am using jenssegers library.


text:
Q: Using the google vba-api to fetch gmail messages from Access I've been searching for a very long time for a way to fetch gmail messages from my MS Access application. I finally found this post here that includes sample vba code to do that.
I'm having 2 issues implementing it.
1) How do I "Use the pre-made GoogleAuthenticator found in authenticators/ folder"?
Is this a vba class module or an existing library that I need to reference? Where do I find the authenticators/ folder?
2) Missing references to WebClient, WebRequest, WebResponse and Dictionary are preventing this code from compiling.
Are these references contained in the GoogleAuthenticator or other libraries that need to be referenced?


text:
Q: DirectShow filter DebugAssert info level I am currently developing DirectShow renderer (audio visualizer), but I am getting ASSERT error when I quit app, telling
szInfo  0x000000e313f8e530 L"Executable: WinDMC.exe  Pid 1fe0  Tid 4768. Module AudioVisualizer.dll, 5 objects left active! \nAt line 350 of C:\Users\Hiroyuki\source\repos\App\baseclasses\dllentry.cpp\nContinue? (Cancel to debug)"
Can anyone tell me how to know the names that are active, not only the number of objects?
MessageBoxOtherThread() doesn't show up to UI(don't know why), so I capture the string to be shown.

A: DirectShow BaseClasses don't track leaked instances, it's just a global counter. You need to guess, or you can edit baseclasses\dllentry.cpp file and add more diagnostic code to identify/log pointers that remain active.


text:
Q: sonar Ant Task can't find findbugs's report(sonar 4.4-RC2 ) I am a beginner to sonar. when i created the sonar env, I just follow the official manual to run samples.  I modified sonar-examples/projects/languages/java/ant/java-ant-simple/build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="Simple Java Project analyzed with the Sonar Ant Task" default="all" basedir="." xmlns:sonar="antlib:org.sonar.ant">

        <!-- ========= Define the main properties of this project ========= -->
        <property name="src.dir" value="src" />
        <property name="build.dir" value="target" />
        <property name="classes.dir" value="${build.dir}/classes" />

        <property name="sonar.host.url" value="http://192.168.3.205:9001" />

        <!-- Define the Sonar properties -->
        <property name="sonar.projectKey" value="org.codehaus.sonar:example-java-ant" />
        <property name="sonar.projectName" value="Simple Java Project analyzed with the Sonar Ant Task" />
        <property name="sonar.projectVersion" value="1.0" />
        <property name="sonar.language" value="java" />
        <property name="sonar.sources" value="src" />
        <property name="sonar.binaries" value="target/classes" />

        <property name="sonar.working.directory" value="sonar" />
        <!--property name="sonar.surefire.reportsPath" value="sonar/build/surefire-reports/findbugs-result.xml" /-->
        <property name="sonar.sourceEncoding" value="UTF-8" />

        <!-- Add your basic Sonar configuration below: sonar.jdbc.url, sonar.jdbc.username, etc. properties -->
        <property name="sonar.jdbc.url" value="jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8" />
        <property name="sonar.jdbc.username" value="sonar" />
        <property name="sonar.jdbc.password" value="sonar" />

        <!-- ========= Define "regular" targets: clean, compile, ... ========= -->
        <target name="clean">
                <delete dir="${build.dir}" />
        </target>
        <target name="init">
                <mkdir dir="${build.dir}" />
                <mkdir dir="${classes.dir}" />
        </target>

        <target name="compile" depends="init">
                <javac srcdir="${src.dir}" destdir="${classes.dir}" fork="true" debug="true" includeAntRuntime="false" />
        </target>

        <!-- ========= Define Sonar target ========= -->
        <target name="sonar" depends="compile">
                <taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml">
                        <!-- Update the following line, or put the "sonar-ant-task-*.jar" file in your "$HOME/.ant/lib" folder -->
                        <classpath path="/root/analyzers/sonar-ant-task-2.2.jar" />
                </taskdef>

                <!-- Execute Sonar -->
                <sonar:sonar />
        </target>

        <!-- ========= The main target "all" ========= -->
        <target name="all" depends="clean,compile,sonar" />

</project>

but when i execute "ant" command, I have a warning info which indict that the output report of findbugs is not at the right place that SurefireSensor expected
[sonar:sonar] 13:29:49.785 INFO  - Findbugs output report: /root/sonar-examples/projects/languages/java/ant/java-ant-simple/sonar/findbugs-result.xml
[sonar:sonar] 13:29:53.552 INFO  - Execute Findbugs 2.0.3 done: 5975 ms
[sonar:sonar] 13:29:53.553 INFO  - Sensor FindbugsSensor done: 5978 ms
[sonar:sonar] 13:29:53.553 INFO  - Sensor SurefireSensor...
[sonar:sonar] 13:29:53.555 INFO  - parsing /root/sonar-examples/projects/languages/java/ant/java-ant-simple/sonar/build/surefire-reports
[sonar:sonar] 13:29:53.556 WARN  - Reports path not found: /root/sonar-examples/projects/languages/java/ant/java-ant-simple/sonar/build/surefire-reports
[sonar:sonar] 13:29:53.556 INFO  - Sensor SurefireSensor done: 3 ms

Are there any other settings I can take to solve the problem?
Thanks!


text:
Q: How to compare two attributes from two different tables in a trigger? So I have two tables:
CREATE TABLE SALE(
OID_PA NUMBER(*,0) PRIMARY KEY,
Amount INTEGER NOT NULL,
Delivery_DATE DATE NOT NULL,
OID_V NUMBER(*,0) NOT NULL,
CONSTRAINT "AMOUNTCHECK" CHECK(Amount >=0),
FOREIGN KEY (OID_V) REFERENCES TICKET(OID_V));

and
CREATE TABLE PRODUCT
(   Code NUMBER(*,0) PRIMARY KEY,
    Stock INTEGER NOT NULL,
    Price NUMBER(4,2) NOT NULL,
    Production_Cost NUMBER NOT NULL,
    Model VARCHAR2(50) NOT NULL,
    TipoMueble VARCHAR2(50) NOT NULL,
    TipoMaterial VARCHAR2(50) NOT NULL,

    OID_PA NUMBER(*,0) NOT NULL,

    CONSTRAINT "TipoMueble" CHECK(TipoMueble IN
    ('Canteado','Complementos','Glaciar',
    'GrupoDiseño','Tiradores','Vitrinas')),
    CONSTRAINT "TipoMaterial" CHECK(TipoMaterial IN ('Aluminio','Lacados',
    'Polilaminado','Madera','Cristal','Chapa','Granito','Formica',
    'Aglomerado','Marmol','Elementos de ferreteria')),
    CONSTRAINT "StockNegativo" CHECK(Stock >=0),
    CONSTRAINT "Precio" CHECK(Price>=0),
    CONSTRAINT "CosteProduccion" CHECK (Production_cost>=0),

    FOREIGN KEY (OID_PA) REFERENCES PAQUETE(OID_PA));

And now I want to create a trigger, the moment I modify the attribute "Amount" in the table "SALE" then it should check the table "PRODUCT".
if "stock" (in PRODUCT) is less than Amount (in SALE) then
RAISE_APPLICATION_ERROR(-20003, 'Not enough stock');

But I don't know how to make the trigger check in both tables at the same time.
right now my code looks likethis right now, it also has some errors that I'm not sure how to fix.
CREATE OR REPLACE TRIGGER TR_ENOUGH_STOCK
AFTER INSERT OR UPDATE OF Amount ON SALE
 BEGIN

    SELECT a.Amount, b.Stock
    FROM ( SALE a inner join PRODUCT b on (a.Code = b.Code))

    IF b.Stock < a.Amount THEN
        RAISE APPLICATION ERROR(-20003, 'Not enough stock');
    END IF;
END;
/

And I'm getting the following errors:
Error(209,5): PL/SQL: SQL Statement ignored
Error(212,5): PL/SQL: ORA-00933: SQL command not properly ended
Error(214,9): PLS-00103: Encountered the symbol "IF" when expecting one of
the following:     ; <an identifier> <a double-quoted delimited-identifier>

A: Here's an example of how you might do that.
Create tables & a trigger:
SQL> create table sale (oid_pa number, amount number);

Table created.

SQL> create table product (code number, stock number, oid_pa number);

Table created.

SQL>
SQL> create or replace trigger trg_biu_stock
  2    before insert or update
  3    on sale
  4    for each row
  5  declare
  6    l_stock product.stock%type;
  7  begin
  8    select stock into l_stock
  9      from product
 10      where oid_pa = :new.oid_pa;
 11
 12    if :new.amount > l_stock then
 13       raise_application_error(-20000, 'Not enough stock');
 14    end if;
 15  end;
 16  /

Trigger created.

SQL>

Insert sample records into the PRODUCT table:
SQL> insert into product values (1, 100, 10);

1 row created.

SQL> insert into product values (2, 50, 20);

1 row created.

SQL> select * From product;

      CODE      STOCK     OID_PA
---------- ---------- ----------
         1        100         10
         2         50         20

SQL>

Let's test it:
SQL> -- 90 is less OID_PA = 10 stock value (which is 100)
SQL> insert into sale values (10, 90);

1 row created.

SQL> -- let's try to update it to a value larger than stock value:
SQL> update sale set amount = 200 where oid_pa = 10;
update sale set amount = 200 where oid_pa = 10
       *
ERROR at line 1:
ORA-20000: Not enough stock
ORA-06512: at "HR.TRG_BIU_STOCK", line 9
ORA-04088: error during execution of trigger 'HR.TRG_BIU_STOCK'

SQL> -- how about a value which doesn't exceed the stock value?
SQL> update sale set amount = 5 where oid_pa = 10;

1 row updated.

SQL> select * From sale;

    OID_PA     AMOUNT
---------- ----------
        10          5

SQL>

As of your attempt: apart from trigger code having wrong syntax, it wouldn't work anyway because you can't reference a table trigger is based on because it is right now being changed, i.e. it is mutating. Oracle raises an error in such cases (see an example below). The correct way is to reference that table's columns using :new or :old, as I did (see an example above).
SQL> create or replace trigger trg_biu_stock
  2    before insert or update
  3    on sale
  4    for each row
  5  declare
  6    l_stock product.stock%type;
  7  begin
  8    select p.stock into l_stock
  9      from product p
 10      join sale s
 11      on s.oid_pa = p.oid_pa
 12      where p.oid_pa = :new.oid_pa;
 13
 14    if :new.amount > l_stock then
 15       raise_application_error(-20000, 'Not enough stock');
 16    end if;
 17  end;
 18  /

Trigger created.

SQL> update sale set amount = 50 where oid_pa = 10;
update sale set amount = 50 where oid_pa = 10
       *
ERROR at line 1:
ORA-04091: table HR.SALE is mutating, trigger/function may not see it
ORA-06512: at "HR.TRG_BIU_STOCK", line 4
ORA-04088: error during execution of trigger 'HR.TRG_BIU_STOCK'

SQL>


text:
Q: PHP - Sum array by defined condition of value Please I need help to summarize a values of array by some conditions
i have this result query :

I want to calcul the Sum of calls for each user, i try with like this, but its show me the sum of all query [Users]
$array_out_ = array();
$usercalls =  $usertalk =  $userpause =  $userwait = $userdispo = $userdead = 0;
    foreach ($queryusers2 as $user) {
            $current_user = $user['user'];
            $usercalls += $user['calls'];
            $usertalk += $user['talk'];
            $userpause += $user['pause'];
            $userwait += $user['wait'];
            $userdispo += $user['dispo'];
            $userdead += $user['dead'];

        $array_out_[$current_user]['calls'] = $usercalls;
        $array_out_[$current_user]['talk'] = $usertalk;
        $array_out_[$current_user]['pause'] = $userpause;
        $array_out_[$current_user]['wait'] = $userwait;
        $array_out_[$current_user]['dispo'] = $userdispo;
        $array_out_[$current_user]['dead'] = $userdead;
    }

This method return me $usercalls (305 for agent29 ) and (436 for agent117)
But i want 305 ofr agent 29 and only 131 for the agent117
Thanks

A: I recommend you change the query SQL to something like this, where you can  group and sum your data.
SELECT
   tn.user,
   SUM(tn.calls) AS usercalls,
   SUM(tn.talk) AS usertalk,
   SUM(tn.pause) AS userpause,
   SUM(tn.wait) AS userwait,
   SUM(tn.dispo) AS userdispo,
   SUM(tn.dead) AS userdead
FROM tablename tn
GROUP BY tn.user

And this will return what you need:
agent29,  305, ...

agent117, 436, ...

A: Your values $usercalls,$usertalk,... are not re-initialized. and are cumulated for all users. Your code works only for the first user and only because your list is ordered by users.
You could initialize an array and sum directly inside it:
$array_out_ = array();

foreach ($queryusers2 as $user)
{
    $current_user = $user['user'];

    if (!isset($array_out_[$current_user])) {
        $array_out_[$current_user] = [
            'calls' => 0, 'talk' => 0, 'pause' => 0, 'wait' => 0,
            'dispo' => 0, 'dead' => 0
        ];
    }

    $array_out_[$current_user]['calls'] += $user['calls'];
    $array_out_[$current_user]['talk'] += $user['talk'];
    $array_out_[$current_user]['pause'] += $user['pause'];
    $array_out_[$current_user]['wait'] += $user['wait'];
    $array_out_[$current_user]['dispo'] += $user['dispo'];
    $array_out_[$current_user]['dead'] += $user['dead'];
}

See also the answer of Enric Borrallo Rodriguez


text: Q: Task Scheduler freezes when Properties is clicked on the Actions pane even after sfc/scannow and reboot; but opening a second Task Scheduler succeeds When I open Task Scheduler on Windows 10, choose a task, and then click on Properties in the Actions pane, the Task Scheduler GUI freezes. I can still work with other things on the desktop. So I run sfc/scannow, reboot gracefully, and try once again. Task Scheduler again freezes when I click on Properties for the chosen task. But if I open a second instance of Task Scheduler leaving the first instance frozen like that, I'm able to click on Properties in the Actions pane for the very same task and make edits to the task.  If this is known behavior and there's a fix, what is it? Thanks


text:
Q: Killing android application on pause I have an application which I would like to be fully disabled/closed when it is paused (IE. When the user presses the Home, End (call) and Back button I would like the application to be closed, instead of being saved in the history stack).
How do I do this....?
Thanks.

A: You know how you have an OnCreate() method in your activity which performs actions when you start. You need to add something like:
@Override

protected void onPause(){
finish();

        super.onPause();

}

in your activity to add actions before it starts
in this case the
finish();

command is what you want to execute before your activity pauses.

A: Implement onPause() in your activity and call finish() on your activity. Bear in mind, though, that this will occur on every pause, including dialogs, incoming calls, users activating a Notification. You might want to consider doing finish() in onStop(), which would at least solve the dialog problem.
Also, bear in mind that users will may get confused when using your app, thinking it has crashed since it is gone when they try to get back to it.

A: you can easily do that by setting true the "noHistory" attribute in to your activity element, in the manifest
http://developer.android.com/guide/topics/manifest/activity-element.html#nohist


text:
Q: Why is JavaScript not used for classical application development (compiled software)? During my years of web development with JavaScript, I come to the conclusion that it's an incredible powerful language, and you can do amazing things with it.
It offers a rich set of features, like:

*

*Dynamic typing

*First-class functions

*Nested functions

*Closures

*Functions as methods

*Functions as Object constructors

*Prototype-based

*Objects-based (almost everything is an object)

*Regex

*Array and Object literals

It seems to me that almost everything can be achieved with this kind of language, you can also emulate OO programming, since it provides great freedom and many different coding styles.
With more software-oriented custom functionalities (I/O, FileSystem, Input devices, etc.) I think it will be great to develop applications with.
Though, as far as I know, it's only used in web development or in existing softwares as a scripting language only.
Only recently, maybe thanks to the V8 Engine, it's been used more for other kind of tasks (see node.js for example).
Why until now it's only be relegated only to web development? What is keeping it away from software development?

A: Most languages in common use are more powerful and better designed than JavaScript. All the features you mention are supported by other dynamic languages like Python or Ruby which are overall better designed. And some of the features you mention are not necessarily desirable anyway - many would consider static typing with type inference preferable to dynamic typing, if you have the choice.
I'm not saying this to diss JavaScript. I quite enjoy working with JS when developing web. But looking at it objectively, JS has a number of drawbacks compared to other languages:

*

*Numerous unfixable flaws. Many mistakes were made when initially developing JS. No need to enumerate them here, they are well documented. All languages have mistakes in the initial design which are later fixed. The difference with JS is that the language was developed and released far to quickly and these mistakes can never be fixed due to the requirement of backwards compatibility in browsers.

*Extremely slow process for introducing improvements and new features. Since all browser vendors have to agree and might even for various political reasons want to slow down the development of the language. Look at C# which is actually a newer language than JS. When C# was introduced it didn't have eg. closures or higher order functions like JS, but after multiple iterations it now has all that and furthermore features like Linq and async syntax which JavaScript developers can only envy.

*Impoverished standard library. Modern languages like Python, Ruby or anything based on Java or .net have extensive standard libraries for almost anything you could need. In JS you can't even read a file without 3rd party libraries. You mention Regex, but all modern languages have that and a thousand things more.

*Other languages have caught up with the few JavaScript advantages. Features like closures and first-class functions were powerful when compared to clunky static languages like Java ten years ago, but dynamic and functional languages have long have had these features, and even Java, a pretty conservative language, has added this in Java 8.

The only feature which really sets JavaScript apart from other modern languages is prototype-based inheritance (as opposed to class-based), and the advantage of this model is dubious since everyone just use it to emulate class based inheritance anyway.
There is simply no reason to choose JavaScript if you have the option of choosing another modern language. Only reason would be if it was the only language you know.

A: From here:

Note that I am basing all my arguments on real-world use cases.
  Counter-arguments that can't be backed up with an example of use in a
  real, complete, interesting, useful applications are invalid. I've
  seen the little "language demos" everyone else has, I've seen the blog
  posts detailing how prototypes and dynamic typing make some trivial
  little example a few lines shorter than it would be in C#, but those
  simply aren't relevant to the problems you run into writing real
  code rather than micro-demos and toys. So here's my gripes with JS:
a) Magic 'this'. This is this, except when this is that. JavaScript
  pushes you to use anonymous functions all over the place, except they
  always end up losing the proper context for the 'this' variable, so
  you end up having goofy code like "var _this = this" all over the
  place and then using that inside your callbacks or other functions.
  Some days I swear that the number of functions I manage to write that
  don't use a renamed 'this' are actually smaller than the number that
  do.
b) 1 + "1" - 1 = 10. Also, "1" + 0 = "10". Yes, this actually has
  caused bugs for our applications, where data that's expected to be a
  number was loaded from a JSON file as a string due to a bug in another
  application, and the result was not good. All our loading code had to
  be updated to add a ton of type conversions all over the place. When I
  need something to be a number I really freaking absolutely want it to
  be a number, not a string or an object or null or anything else. Lua,
  which is very similar to JavaScript in most respects, fixed this
  problem by just not being retarded enough to use the same operator for
  addition and string concatenation.
c) Global by default variables. So even if you take the argument that
  dynamic typing is just "easier" because you don't have to think about
  variable declarations, JavaScript throws that argument out the window
  by making you put 'var' in front of new identifiers all over the
  place. And then it silently screws you if you forget to.
d) Prototypes instead of classes. There are very few large-scale
  real-world JavaScript applications in existence that don't plug in
  their own class system to work around the inherent uselessness of
  prototypes in large application architecture. Those same apps make
  minimal use of prototypes to extend the base JavaScript types, and
  only because JS was so poorly designed that even the two interesting
  built-in types it comes with are lacking half the features you'd
  expect them to have.
e) Inability to create pass-by-value types. This is a frequent problem
  in just about every language aside from C++/D, actually. For those
  using JavaScript to write WebGL apps, take a look at all the linear
  algebra libraries for JavaScript. In 3D apps, you almost use vectors
  more often than you do scalars. Imagine if every integer in your app
  was passed by reference, so that "a = 1; b = a; b++" made both a and b
  equal to 2. Every little three component vector is a complete full
  object. They are passed by reference (the source of almost a half of
  the bugs in our WebGL game so far, in fact). They exist in great
  quantity, are heap-allocated, and are garbage-collected, which puts an
  intense amount of pressure on the GC which can and does result in GC
  pauses in even simple WebGL games, unless the developer jump through
  ridiculously complicated hoops to avoid creating new vectors in all
  the places where it's logical to create new vectors. You can't have
  operator overloading, so you have very large and ugly expressions to
  do basic operations. Accessing individual components is slow. The
  objects aren't natively packed and hence are incredibly slow to push
  into a vertex buffer, unless you implement them as a Float32Array
  instances, which confuses the crap out of the optimizers of both V8
  and SpiderMonkey currently. Did I mention they're passed by reference?
f) No built-in include or require functionality. Seriously, still.
  Third-party libraries exist but almost all of them have some kind of
  bug or another, not least of which is a confusing caching problem in
  at least Chrome making doing actual development a pain in the butt.
g) Dynamic typing. Yes, I'm willing to start that argument. You start
  noticing it the most the second you stop writing little Web apps or
  Web pages and start writing large apps where you actually have data
  that persists for longer than a single mouse click or request/response
  cycle: add the wrong kind of object to an array to process later and
  get a crash later from a missing method or member in a completely
  different bit of code than where the actual mistake was. Fun times.
  Yes, Java makes static typing seem evil. No, Java/C#/C++ are not the
  one and only way to do static typing. Type inference, implicit
  interface binding, etc. give you all the "easy to deal with and not a
  lot of keystrokes" advantages of dynamic typing without all the bugs.
  The second most popular Web language -- ActionScript 3 -- is
  statically typed, in fact, despite otherwise being identical to
  JS/ECMAScript. As an aside, I get more crashes from the Python apps on
  my Fedora desktop than I do from the C/C++ apps (actually, none of the
  C/C++ apps on my desktop crash, now that I think about it). Missing
  member exceptions == so much easier to develop and maintain apps,
  right?
h) Speed. Yes, there has been some ridiculously immense amounts of
  effort by a large number of super bad-ass developers put into the
  language runtimes to make JS almost half as fast as a low-grade C
  compiler that a single college Junior could write in a few months. And
  LuaJIT is in the same boat as JS in terms of fundamental language
  limitations but manages to do better than every JavaScript
  implementation anyway. People who don't understand what all the JS
  optimizations in V8 or such actually do like to claim the JS can do
  amazing things speed-wise, but the reality is that all those
  optimizations are basically just "try very very hard to analyze the
  code to figure out types for variables and then compile it like a
  slightly retarded statically-typed language's compiler would do it."
  Oh, and there's tracing, but then tracing also works on statically
  typed languages (and works better due to a lack of need for type
  guards in the generated machine code). Not a single one of those
  whizbang optimizations was invented by or for JS, in fact; most were
  taken from research JVMs (Java is evil!) or classical OOP languages
  (prototypes are awesome!).
i) No IntelliSense even possible. Want to see what methods exist on
  that variable you've got there on line 187 of foo.js in your text
  editor? Too bad. Go trace through the code until you figure out where
  it was initialized, then go trace through the code to find out what
  its prototype has on it. And then hope there's no code dynamically
  changing the prototype behind your back. In fact, just run it in a
  browser and set breakpoints, because finding out anything useful about
  the value any other way is basically impossible for any codebase
  larger than the toy_web_app.html sites that JavaScript apologists use
  to glorify the ease and simplicity of JavaScript. Some code editors
  try really hard to do better, and almost kinda sorta succeed for the
  really simple cases, sometimes, once.
j) No advantage. JavaScript isn't even special compared to other
  dynamically typed language. It is not capable of doing anything
  interesting at all all that can't also be done by Lua, Python, Ruby,
  etc. None of the JS implementations are any faster than LuaJIT or PyPy
  or various other advanced JIT-ing implementations of other dynamic
  languages. JS has no plus sides to it compared to other commonly
  available languages. Oh, except it runs natively in a Web browser
  without a plugin. Which is the only reason in the world why it's so
  popular. In fact, it's the only reason it event exists. If someone
  10 years ago had just thought, "heck, let's drop an existing
  well-designed and well-established language into our browser and get
  the other guys to do the same instead of making everyone use this
  goofy little hackjob that NetScape came up with," the Web would look a
  lot different (better) today. Just imagine the future if Chrome
  dropped Python into Chrome as a supported language. Or actually,
  imagine this: Google drops C/C++ into Chrome as a supported language
  (http://code.google.com/p/nativeclient/).

A: Recently node.js has brought server-side development forward. So, it's now possible to write JavaScript, for development.
That's true. In history, it hasn't been used as a development language. But, hey, even scripting in client environment (User Agents) is a type of development. Isn't it?
The main reason that I've heard and read in many weblogs, is that, people didn't know about its power and uniqueness till recent years. What made this happen, was maybe that other languages were doing their job just well enough, and nobody ever thought about making something parallel.

A: Why?
JavaScript the most misunderstood language
We were in the dark ages and still are for the general development community to accept that JavaScript is a powerful and versatile language. It's simply not mainstream.
The only recent advance is that node.js has become buzz-wordy and people are starting to accept that javascript has other uses..
I've been keeping an eye on the JS & HTML5 development for windows 8 and the reaction from the .NET community was "dear god why?".
It's simply fact that most non-web developers still see JavaScript as that toy language you use to make those scroll over menus in your browsers.
Admittedly JavaScript doesn't align with "modern development practices". For me JavaScript is still a hacking language I crack out with vim & the internet is my documentation. There is no IDE, there are no development tools, there is no auto-complete or "intellisense", there are no click and drag GUIs.
In the world of Java and .NET developers they are wedded to their GUIs & IDEs and would not be able to program in vim.

A: Your list does not contain anything about writing files to the system, which is a massive part of software development.
People would not think of using JS to build an application because it the de facto scripting language for web, and you would always use the right tool for the job.
Why write acres of JS to write out a file when it is a trivial operation in Java/.NET/C/C++?
With that said, as others have mentioned, node.js and its libraries have made server side operations trivial and with node.js becoming popular, learning it will become a skill for a CV, since you will be able to maintain/extend/build applications with it.


text:
Q: C++ Get country code I'm trying to get the country code (example: "UK" or "SI" or "GER") via GetGeoInfo().
    GEOID GetUserGeoID(GEOCLASS_NATION);

Currently getting the value 16 from the above function ^ but looking in the table there's no number 16.
https://msdn.microsoft.com/en-us/library/windows/desktop/dd374073(v=vs.85).aspx
I know it's only 3-4 lines of code but I can't seem to figure it out on my own. Any help would be appriciated.
EDIT:
GEOID myGEO = GetUserGeoID(GEOCLASS_NATION);
int sizeOfBuffer = GetGeoInfo(myGEO, GEO_ISO2, NULL, 0, 0);
WCHAR *buffer = new WCHAR[sizeOfBuffer];
int result = GetGeoInfo(myGEO, GEO_ISO2, buffer, sizeOfBuffer, 0);

Got it to display my country number but I don't know how I'd transform it into an ISO code.

A: To get the country ISO:
GEOID myGEO = GetUserGeoID(GEOCLASS_NATION);
int sizeOfBuffer = GetGeoInfo(myGEO, GEO_ISO2, NULL, 0, 0);
WCHAR *buffer = new WCHAR[sizeOfBuffer];
int result = GetGeoInfo(myGEO, GEO_ISO2, buffer, sizeOfBuffer, 0);
wcout<<buffer;

Thanks to @Christophe and @Thomas.


text:
Q: How do node.js and libuv use the different threads? While doing some research on Node.js and libuv I started a simple node server with UV_THREADPOOL_SIZE=1 and looked at pstree to see how much threads it really uses.
for Node.js 0.10 pstree -p | grep node produces
node(5157)-+-{node}(5158)
            `-{node}(5162)

To make things a bit more complicated I also tried the same with 0.12 and iojs 3.3. The number of threads differs for every version.
Total number of threads vs thread pool size
0.10: UV_THREADPOOL_SIZE + 1
0.12: UV_THREADPOOL_SIZE + 2
3.3:  UV_THREADPOOL_SIZE + 4
I also tried to set higher numbers for the thread pool size to make sure that I'm not below some minimum value.
My questions are:

*

*What is executed on the main process (5157) and what on the threads below?

*Can we assume that (5158) is the thread id of libuv here and that (5162) is a single "worker" thread?

*What happens in 0.12 and iojs 3.3? Why are there up to 4 threads more than configured?

A: I can't really speak for the Node/V8 part, but in general amy libuv application will use at least 1 + UV_THREADPOOL_SIZE threads.
The first thread is the one which runs the libuv loop by calling uv_run, which is usually the main thread. libuv then has a thread pool of UV_THREADPOLL_SIZE size, where filesystem and DNS operations are run. Network i/o is performed in the loop thread by using epoll / kqueue, etc.


text:
Q: Are thermal fuses polarized? I have a device with a thermal fuse in it. The fuse has failed, and I would like to replace it.
Does thermal fuse have a polarity, similar to an electrolytic capacitor, or is it the same with normal fuse? It has a stripe marking on it.
Is it sensitive to polarization, or will either way work?

A: Short:  No. Thermal fuses are not polarised.

Longer :-) :
No thermal fuse I have ever seen was polarised (based on decades of experience but ...).
I cannot think why a thermal fuse would be polarised.
This seems to be extremely unlikely but I mention it for completeness:
If a device that was called a thermal fuse WAS polarised then it would be more than a fuse - it would be very special in some unusual manner.
 If so then it would need to be replaced by an identical unit if it was going to do the same job.

A photo would be a good idea.
 Does it have a part number on it?


text:
Q: PyAudio.Stream on top of portaudio1.9 hangs when reading audio from microphone I'm working on an application that's continuously reading audio from the microphone, built on top of this SpeechRecognition library.
I am consistently reading a chunk of size 1k from the microphone input stream, but it is sometimes blocking for longer than it should take to record the audio. My chunk size/sample rate put 1k frames at about 60ms of audio, so I'm struggling to figure out why the read call would block for >10s at times. It's possible I just don't understand portaudio/pyaudio/computers, and I'd appreciate any insight available from the community.
Environment: I'm seeing this issue both on ubuntu 14.04 LTS and raspbian wheezy/jessie on a raspi 2.


text:
Q: How to migrate eclipse Juno workspace to Kepler? I have installed Kepler yesterday, but I want to use the old workspace instead of creating from scratch.
Is there any way to migrate eclipse Juno workspace to Kepler ?

A: It basically depends on the plugins used by the projects in your workspace. If you use a standard Eclipse configuration there shouldn't be any problem, just open workspace, close all projects and open them again. If it doesn't work try cleaning them up.


text:
Q: Checkbox state does not change on click In my Model.vue component (in a Nuxt.js and Vuetifyjs application) I have this piece of code:
<v-checkbox v-model="selected"></v-model>

In the script section of this component, I have:
computed: {
    selected: {
        get() {
            return this.$store.state.selected
        },
        set(value) {
            this.$store.commit('UPDATE_SELECTED', value)
        }
    },
},

In the store, I have this:
mutations: {
    UPDATE_SELECTED: (state, value) => {
       state.selected.push(value)
    }
}

And the state of this store contains the selected entry as follows:
state: {
   selected: []
}

AFAIK, I complied to the documentation, but when I click on the v-checkbox component, it does not check/uncheck. What is wrong?

A: The problem occurs because you're using an array for modeling the boolean state property named selected.
So, according to your code, at mutations side, on each mutation you're pushing a new boolean value in the latest position of an array named selected.
Also, at get side, the get() function of your computed property returns the entire array as property to be displayed, resulting in an unchecked checkbox at client side.
So, assuming you need to deal with multiple checkboxes, in order to make the current one working properly you could write it as follows:
Vuex Store
let store = new Vuex.Store({
  state: {
   selected: []
  },
  mutations: {
    UPDATE_SELECTED: (state, value) => {
       //mutating the 0th array position of the selected property
       state.selected[0] = value
    }
  }
})

Computed property
computed: {
    selected: {
        get() {
       //getting the 0-index element of the array, assuming this checkbox is the 0th
            return this.$store.state.selected[0]
        },
        set(value) {
            this.$store.commit('UPDATE_SELECTED', value)
        }
    }
  }

Here you find a working fiddle.
Alternatively, if you need just to deal with a single checkbox in your application state, it'd be enough to model the state.selected property as a boolean. I mean, it would suffice to modify your Vuex state as follows:
state: {
   selected: true //or false if you expect unchecked checkbox as default
  }


text:
Q: Align buttons in Bootstrap Within my current template I am using Bootstrap and it should contain three buttons where each should be positioned respectively. The first one all the way to the left, the second one in the middle and the third (final) one to (all the way to) the right (within a container element).
When I am trying to achieve this with Bootstrap, I happen not to find anything concerning my need. This is because everytime I try to wrap a
 tag around the input elements, the HTML document will show these on seperate rows:

.foo {
  width: 23%;
  /*Should be the width required by the button,
  but I just took a random number that fits
  best. */
  margin: 0 auto;
}
/*This is how it should look like, however
I want to make use of Bootstrap instead of custom positon css if
possible. */

.desired {
  position: absolute;
  left: 10%;
}
.desired div {
  width: 10%;
  text-align: center;
  display: inline-block;
}
.example2 {
  /*Center second element*/
  position: absolute;
  left: 50%;
  margin-left: -5%;
}
.example3 {
  position: absolute;
  right: 0%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />I tried using the following HTML/CSS:

  <input type="submit" class="btn btn-default" value="Foo">
  <input type="submit" class="btn btn-default" value="Test">
  <input type="submit" class="btn btn-default pull-right" value="Bar">

And got to a result that looks something like this:

  <input type="submit" class="btn btn-default" value="Foo">

    <input type="submit" class="btn btn-default" value="Test">

  <input type="submit" class="btn btn-default pull-right" value="Bar">

And this:

  <input type="submit" class="btn btn-default" value="Foo">

    <input type="submit" class="btn btn-default" value="Test">

  <input type="submit" class="btn btn-default pull-right" value="Bar">

I want the elements to look similar to:

    <input type="submit" class="btn btn-default" value="Foo">

    <input type="submit" class="btn btn-default" value="Test">

    <input type="submit" class="btn btn-default" value="Bar">

If this snippet does not show well, this is due to positioning in percentages, so try to view it in full page if necessary.
So my question is: Is it possible to use Bootstrap to align buttons within a document, even when I want these to be placed on the same horizontal line (or row)?
Thanks in advance.

A: very simple just follow below step.
by using bootstrap

*

*put all 3 buttons in same div or container.

*add "text-center" class in parent div or container of all 3 buttons

*add "pull-left" class to first button.

*add "pull-right" class to third button.

by using custom CSS

*

*put all 3 buttons in same parent div.

*give that parent div css- .parent-div { text-align:center;}

*give first button css- .first_btn { display:inline-block; float:left;}

*give third button css- .third_btn { display:inline-block; float:right;}

*give second button css- .second_btn { display:inline-block; float:none;}

A: You can achieve it without using position this way:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

      <button class="btn btn-default">Button</button>

      <button class="btn btn-default">Button</button>

      <button class="btn btn-default">Button</button>


text:
Q: UTF8 characters from database don't show up properly in the browser - MySQL & PHP CodeIgniter My database and tables are set to utf8_general_ci collation and utf8 charset. CodeIgniter is set to utf8. I've added meta tag charset=utf8, and I'm still getting something like: квартиры instead of cyrillic letters...
The same code running on the local machine works fine - Mac OSX. It's only breaking in the production machine, which is Ubuntu 11.10 64bit in AWS EC2. Static content from the .php files show up correctly, only the data coming from the database are messed up. Example page: http://dev.uzlist.com/browse/cat/nkv
Any ideas why?
Thanks.
FYI:
When I do error_log() the data coming from the database, it's the same values I'm seeing on the page. Hence, it's not the browser-server issue. It's something between mysql and php, since when I run SELECT * FROM categories, it shows the data in the right format. I'm using PHP CodeIgniter framework for database connection and query and as mentioned here, I have configured it to use utf8 connection and utf8_general_ci collation.

A: Make sure your my.cnf (likely to be in /etc/) has the following entries :
[mysqld]
default-character-set=utf8
default-collation=utf8_general_ci
character-set-server=utf8
collation-server=utf8_general_ci
init-connect='SET NAMES utf8'

[client]
default-character-set=utf8

You'll need to restart the mysql service once you make your changes.
Adding my comments in here to make this a little clearer.
Make sure the following HTTP header is being set so the browser knows what charset to expect.
Content-type: text/html; charset=UTF-8

Also try adding this tag into the top of your html <head> tag
<meta http-equiv="Content-type" value="text/html; charset=UTF-8" />

A: To make the browser show up correctly.you should check three points:

*

*encoding of your script file.

*encoding of connection.

*encoding of database or table schema.

if all of these are compatible, you'll get the page you want.

A: The original data has been encoded as UTF-8, the result interpreted in Windows-1252 and then UTF-8 encoded again. This is really bad; it isn't about a simple encoding mismatch that a header would fix. Your data is actually broken.
If the data is ok in the database (check with SELECT hex(column) FROM myTable) to see if it was double encoded already in the database), then there must be your code that is converting it to UTF-8 on output.
Search your project for uses of function utf8_encode, convert_to_utf8, or just iconv or mb_convert_encoding. Running
$ grep -rn "\(utf8_\(en\|de\)code\|convert_to_utf8\|iconv\|mb_convert_encoding\)" .

On your application's /application folder should be enough to find something.
Also see config values for these:
<?php
var_dump(
    ini_get( "mbstring.http_output" ),
    ini_get( "mbstring.encoding_translation" )
);

A: Well, if you absolutely and positively sure that your mysql client encoding is set to utf8, there are 2 possible cases. One - double encoding - described by Esailija.
But there is another one: you have your data actually encoded in 1251, not in utf-8.
In this case you have to either recode your data or set proper encoding on the tables. Though it is not one button push task
Here is a manual (in russian) exаctly for that case: http://phpfaq.ru/charset#repair
In short, you have to dump your table, using the same encoding set on the table (to avoid recoding), backup that dump in safe place, then change table definitions to reflect the actual encoding and then load it back.

A: Potentially this may also be caused by the mbstring extension not being installed (which would explain a difference between your dev and production environments)
Check out this post, might give you a few more answers.

A: Try  mysql_set_charset('utf8') after the mysql connect. Then it should works.

A: After 2 days of fighting this bug, finally figured out the issue. Thanks for @yourcommonsense, @robsquires, and a friend of mine from work for good resources that helped to debug the issue.
The issue was that at the time of the sql file dump to the database (import), charset for server, database, client, and connection was set to latin1 (status command helped to figure that out). So the command line was set to latin1 as well, which is why it was showing the right characters, but the connection with the PHP code was UTF8 and it was trying to encode it again. Ended up with double encoding.
Solution:

*

*mysqldump the tables and the data (while in latin1)

*dump the database

*set the default charsets to UTF8 in /etc/my.cnf as Rob Squires mentioned

*restart the mysql

*create the database again with the right charset and collation

*dump the file back into it

And it works fine.
Thanks all for contribution!


text:
Q: How do I change the number of indent guide lines in Sublime Text 2? The current indent guide lines show only on intervals of 12 spaces.
I want them to show on intervals of 4 spaces, so they match my tab width exactly.

A: Use a monospaced font.  Either, comment out the font_face setting in your Settings - User file or change it to a monospaced font available in your os.

A: I had the same issue and found out that the "Tab Width" for my document (2) differed from the setting "tab_size" (4)
What I had to do was to change "Tab Width" in:
View / Indentation / Tab Width


text:
Q: redirect m.php to m.domain.com htaccess Is it possible to redirect
http://www.url.com/m.php?name=Bill

to
http://m.url.com/Bill/

via htaccess?
I have seen some examples but I'm not sure what
they use to accomplish that

A: How about:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?url\.com$ [NC]
RewriteCond %{THE_REQUEST} \ /+m\.php\?name=([^&\ ]+)
RewriteRule ^ http://m.url.com/%1/? [L,R]

RewriteCond %{HTTP_HOST} ^m\.url\.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /m.php?name=$1 [L,QSA]

assuming that both m.url.com and www.url.com point to the same document root.