text:
Q: Reliable Way to Add Sound to UIButton I am trying to add a tap-sound to a UIButton to play when it is pushed. So far, I've tried two methods, but none worked out quite as well as I hoped.

*

*I have tried using simple SystemSounds, but they are an ugly solution, as the user have no (or rather very limited) control over the audio volume.

*I also tried AVAudioPlayer in the following form (called in the ViewController's init method):
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient
                                       error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[AVAudioSession sharedInstance] setDelegate:self];

NSString *filePath = [[NSBundle mainBundle]
                     pathForResource: @"button_pushed"
                              ofType: @"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: filePath];
self.buttonPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                           error: nil];
[buttonPlayer prepareToPlay];
[buttonPlayer setDelegate: self];

This second method seemed to work a lot better than the first one; especially when I called sound with the following statement:
    if (self.clickPlayer.playing) {
        [self.clickPlayer stop];
        self.clickPlayer.currentTime = 0;
        [self.clickPlayer play];
    }
    else {
        [self.clickPlayer play];
    }

The above ensured that I got a very fast response when I pushed the button repeatedly. Fast response time, by the way, is essential in my app, and unfortunately, this is where this second methods fails.
If I let the application idle for about 10 seconds, loading the first sound takes a noticeable delay (then, it becomes fast and responsive again). Not only that, it also delays the button from being pushed with it. While this delay is very tiny (probably the fraction of a second), unfortunately it does effect the usability of my application. It is as if the sound was becoming deallocated automatically and needed to be initialized or put into the memory every time I did not use it for a while.
Is there a workaround to always keep the sound available and avoid the delay or another, possibly simple, method to implement button sounds?
A few more info:
1. I use ARC
2. I do not use IB
3. Currently, there are no audio delegate methods implemented
4. The ability to play audio in the background from other applications is kind of important
5. The delay occurred on an iPhone 5; so, I can only imagine how long it would take on less powerful devices...

A: I managed to solve this problem by creating a "blank" player that continuously fires off a tiny .wav file with no sound, therefore keeping the AVPlayer alive. This is probably not the most elegant solution, but it does work, while it does not seem to affect the performance of the program. Here's what you need to do:

*

*Create a silent .wav file of 0.1 seconds long (the smaller the better).

*Initialize a player for it:
NSString *filePath = [[NSBundle mainBundle] pathForResource: @"silence"
                                                     ofType: @"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: filePath];
silencePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                       error: nil];
[silencePlayer prepareToPlay];
[silencePlayer setDelegate: self];

*Then make it fire every second or so:
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                         target:self
                                       selector:@selector(repeatSilence)
                                       userInfo:nil
                                        repeats:YES];

*Finally, create the called method (- (void) repeatSilence { } ) to play the sound:
if (self.silencePlayer.playing) {
    [self.silencePlayer stop];
    self.silencePlayer.currentTime = 0;
    [self.silencePlayer play];
}
else {
    [self.silencePlayer play];
}

A: Not entirely sure, but wouldn't it go faster if you make an NSData of the path and change [[AVAudioPlayer alloc] initWithContentsOfURL to [[AVAudioPlayer alloc] initWithData?


text:
Q: How to select a particular USB port on raspberry pi 3B+ to program two arduino boards with arduino-mk? I have a python program on my Raspberry pi 3B+ witch updates an Arduino mega2560 and an Arduino Uno by using Arduino-mk through bash commands. Each Arduino has its own code folder with its code (.ino) and a Makefile which looks like:
ARDUINO_DIR = /usr/share/arduino
ARDUINO_PORT = /dev/ttyUSB0 (here is the problem)

USER_LIB_PATH = /home/pi/sketchbook/libraries
BOARD_TAG = mega2560 (Uno for the uno one)

include /usr/share/arduino/Arduino.mk

When I call the following command:
os.system("(cd ~/sketchbook/mega; make upload clean)")

with only the mega connected on the USB port everything works and the mega gets programed (same with Uno only). but when I try to get both done:
os.system("(cd ~/sketchbook/mega; make upload clean)")
os.system("(cd ~/sketchbook/uno; make upload clean)")

arduino-mk can't program the Uno (multiple timeouts).
At first the second line in Makefile was:
ARDUINO_PORT = /dev/ttyAMC0

but it was not working so I checked on the web and found that some Arduino copies worked better with:
ARDUINO_PORT = /dev/ttyUSB0

Then it worked but I couldn't get any result with ttyUSB1 up to ttyUSB3 (I hoped it would work like COM ports on windows).
I also noticed that if I keep testing with ttyUSB0 and try with each physical USB port and worked so ttyUSB0 refers to the four physical ports right?
Please how can I get one particular port name?
Or is there an other way to make Arduino-mk work?

A: Plug in one device at a time and look at the output of ls -l /dev/serial/by-id/, you should see a symlink to the actual device node, but uniquely named for your specific device.
You can then set ARDUINO_PORT=/dev/serial/by-id/unique_name in the respective makefiles.

redpajama_set_name: RedPajamaStackExchange


text:
Q: dd copy from an OS HDD to PCIe NVME SSD, SSD can't boot Test 1:
dd if=/dev/sdb of=/dev/sdc

/dev/sdb is a bootable OS HDD, /dev/sdc is another HDD, after executed the above dd command, the /dev/sdc become bootable.
Test 2:
dd if=/dev/sdb of=/dev/sdc

/dev/sdb is a bootable OS HDD, /dev/sdc is a PCIe NVME SSD, after excuted the above command, the /dev/sdc can not boot.
Similar issue:
dd copy a HDD to USB but fail to boot?
In the above case, the OS needs to install usb-storage driver to initramfs; is there any driver needed to install for a NVME SSD?

A: The PCIe NVMe SSDs I've seen are either not bootable at all, or only bootable using UEFI.
If you're using legacy BIOS-style boot, and a PCIe SSD does not appear as a bootable device, it's a pretty good clue that the PCIe SSD does not support legacy-style booting.
If you can get to the bootloader, but fail to start the OS, then the problem is a missing driver; but if you cannot even get to the bootloader, the problem is that the system firmware (BIOS or UEFI) does not support that device as a bootable disk.
UEFI-style boot requires a GPT partition table and an EFI System Partition (ESP), so a straight clone of partitions from a MBR-partitioned disk to a GPT-partitioned one isn't enough. But if you can add the ESP and then replace the bootloader, e.g. from a traditional BIOS-based GRUB to an UEFI version of GRUB, that might be enough to get an existing Linux/Unix installation cloned & converted from legacy to UEFI boot.


text:
Q: How do I save iBooks pdf on iPhone to computer so I can delete them from iPhone? My iPhone 6s+ is running out of memory. I have so many crochet patterns on my iBooks. How do I transfer those patterns to computer so i can delete them from my iPhone? When I first bought the computer I synced my phone then started deleting them from my phone, then they started deleting from the computer.
What did I do wrong?

A: To delete them only from your phone, follow these steps:

In the upper-right corner of the iBooks window, tap Select.
Scroll to find the item that you want to delete, then tap it.
In the upper-left corner of the iBooks window, tap Delete.
Tap Delete This Copy.

If you tap Delete from All Devices, it will remove it from iCloud, which will cause it to be deleted from all devices (including your computer).


text:
Q: Objective-C: Objects are passed by value? I know this has been asked before from different angles.
However, I did not yet see a straight answer how are explicit objects passed in objective-c.  After a month of experience coding in objective c (coming from Java), I see that objects are passed by value.
Is that true?
In my code, I had a NSArray of objects of type Person.  I took one of the objects from the NSArray, edited it and saw the values of any of the objects in NSArray not affected until I called replaceObjectAtIndex: method.  To my surprise, this scenario showed me that explicit objects in Objective C are passed by value.

A: Objects in Objective-C are always passed by reference. In terms of how it interfaces with C, you're actually pointers to object by value but it's not worth splitting hairs.
Although there are two types of object literal in Objective-C, strings and blocks, and the latter of those is permitted to live on the stack rather than the heap, it is still handled by reference.
The test you performed must have been flawed in some way.

A: Everything is passed by value in C, it's just that some of these values are pointers. Passing a pointer allows you to just pass a "signpost" to the target object, rather than the entire object itself. You manipulate the object through by following the pointers; anyone holding a  pointer to the same object will see the changes made to it by any other code.
All Objective C objects are handled via pointers, so you should have seen the changes in your array example. For example,
NSArray *myArray = ...;
id element = [myArray objectAtIndex:n];
element.foo = @"Bar";

// [[myArray objectAtIndex:n] foo] is now "Bar";

What was your test code?

A: There was some kind of error in your test.
NSMutableString *string = [@"foo" mutableCopy];
NSArray *array = [NSArray arrayWithObject:string];
[string appendString:@"bar"];
NSLog(@"%@", array);

> [...] (
>     foobar
> )

In Objective-C all objects are always referenced by a pointer.


text:
Q: Additional text found in json string after finishing deserializing object This question have been asked a few times here but still there are some situations where it doesn't work.
I am working on reading json data using JSON.net and want to read the json data into dataset. I have following json data string ( It can be more complicated and can be nested to multiple levels)
[{"timestamp": 1383033661,
  "base": "USD",
  "rates" : {
  "AED": 3.673136,
  "AFN": 56.962675,
  "ALL": 101.792499,
  "AMD": 409.561999,
  "YER": 215.109837,
  "ZAR": 9.851868,
  "ZMK": 5230.441665,
  "ZMW": 5.395017,
  "ZWL": 322.355006}}]

I am trying to read it into a data set using:
DataSet currency = (DataSet)JsonConvert.DeserializeObject(json, (typeof(DataSet)));

but it throws the exception:
"Additional text found in json string after finishing deserializing object"

Note:I tried converting single level json data into data table and it was successfully converted but again when I tried to convert it into dataset it failed with same above given exception.
Could anyone please give an insight of above exception and resolution for it ?

A: You need a structure similar to
public class Rate
{
    public string TimeSpan { get; set; }
    public string Base { get; set; }
    Dictionary<string, string> Rates { get; set; }
}

rates is another json object inside the json array.
const string json = @"{
  ""timestamp"": 1383033661,
  ""base"": ""USD"",
  ""rates"" : {
      ""AED"": 3.673136,
      ""AFN"": 56.962675,
      ""ALL"": 101.792499,
      ""AMD"": 409.561999,
      ""YER"": 215.109837,
      ""ZAR"": 9.851868,
      ""ZMK"": 5230.441665,
      ""ZMW"": 5.395017,
      ""ZWL"": 322.355006
   }
}";

Rate currency = (Rate)JsonConvert.DeserializeObject(json, (typeof(Rate)));


text:
Q: Is there a good role based workflow engine in PHP? I am looking for role based access and work flow engine that allows for simple configuration.

A: i use the Zend Framework, so i guess to create auth/roles/resources/acl, i will use the respective classes

*

*Zend_Auth

*Zend_Acl_Role

*Zend_Acl_Resource

*Zend_Acl
to determine if a user (role) is allowed access to a resource, do something like

// setup variables
$acl = new Zend_Acl();
$adminRole = new Zend_Acl_Role("admin");
$adminResource = new Zend_Acl_Resource("adminResource");

// add roles, resources to acl
$acl->addRole($adminRole);
$acl->addResource($adminResource);

// add rules
$acl->allow($adminRole, $adminResource);

// query acl
echo $acl->isAllowed($adminRole, $adminResource) ? "allowed" : "denied"; // allowed

something like above

A: I would recommend ezComponents workflow. We built an intranet application using it and it was quite easy to use. The documentation is awesome and it has very active community.
Update: ezComponents now lives on as Zeta Components

A: Do you mean a php framework that'll make roles easy ? I'd suggest Symfony. A sample security.yml file looks like
all:
  is_secure:  on
  credentials: Admin

The security files  also cascade, so you can put this on the highest level (App level) and override it on a module or page level.
Or am I totally off ?

A: PHP acl worked really well for me. several open source projects are using it like joomla, in the other hand cakephp take the code model to make it own acl system

A: Tony Marston has one, maybe you could contact him:
http://www.tonymarston.net/php-mysql/workflow.html


text:
Q: FakerLibrary: Adding a custom provider fails When I run the following code, I'm facing some difficulty. Calling the Robot Framework FakerLibrary Add Provider keyword requires two arguments, instead of the expected 1: name of the module. This seems to me to be correct.
As the Robot Framework Library is a Dynamic Hybrid library, the actual keywords come from the Faker Python module. In the Generator class the actual Add Provider method can be found. However, it only takes 2 arguments; one being self: def add_provider(self, provider). So, it should only require 1 argument when called from Robot.
Using the normal Faker keywords works as expected and I'm not having any issues. I'm suspecting that the import through the Dynamic Library doesn't support the Faker module setup as I'm seeing a few Keywords in the Keyword Documentation that require self as an input argument.
For now I've resorted in creating a wrapper around Faker for custom keywords but like the generic approach better. So that is why I would like to solve this issue.
The Robot Script for this example.
*** Settings ***
Library    FakerLibrary
*** Test Cases ***
Faker Custom Provider Generate Data

    ${fakerLib}    Get Library Instance    FakerLibrary
    Add Provider    ${fakerLib}    OceanProvider

The custom provider Python code. When using it with regular Python programming this works as expected but not when adding it through Robot Keywords:
from faker.providers import BaseProvider

class OceanProvider(BaseProvider):

    __provider__ = "ocean"
    __lang__     = "en_US"

    oceans = [
        u'Atlantic', u'Pacific', u'Indian', u'Arctic', u'Southern',
    ]

    @classmethod
    def ocean(cls):
        return cls.random_element(cls.oceans)


text:
Q: pytest.ini doesn't take effect when calling pytest vs. pytest  I am working creating some testing infrastructure and struggling with taking care of all the dependencies correctly.
The directory structure I have looks like:
conftest.py
kernels/
|-kernel_1/
|---<kernel_src1>
|---__init__.py
|---options.json
|---test/
|-----test_func1.py
|-kernel_2/
|---<kernel_src2>
|---__init__.py
|---pytest.ini
|---options.json
|---scripts/
|-----__init__.py
|-----some_module.py
|---test/
|-----test_func2.py

When I call pytest on any of these tests, the test first compiles and simulates the kernel source code (C++) and compares the output against golden that is generated in python. Since all the kernels will be compiled individually, I create an output directory to store compile/simulation logs along with some header files that we generated in the kernel_1 directory.
For example, pytest kernel_1/test/test_func1.py will create a directory in kernel_1/build_test_func1/<compile/sim logs>.
I use the conftest.py which updates cwd to the test directory based on the accepted answer here:
Change pytest working directory to test case directory
I also added pytest.ini to add kernel_2 to the pythonpath when running test_func2 so we can find modules in scripts folder:
[pytest]
pythonpath=.

Tests run correctly when calling it from:
cd kernel_2/; pytest
cd kernel_2/test; pytest
cd kernel_2; pytest test/test_func1.py
cd kernel_2/test; pytest test_func1.py

The test also runs correctly when calling it like this: pytest kernel_2/test/test_func2.py
But I start seeing ModuleImportError when calling it from top-level without specifying the test
pytest
    ImportError while importing test module '<FULL_PATH>/kernel_2/test/test_func2.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    <FULL_PATH>miniconda3/envs/pytest/lib/python3.7/importlib/__init__.py:127: in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    kernel_2/test/test_func2.py:8: in <module>
        from scripts.some_module import some_func
    E   ModuleNotFoundError: No module named 'scripts'

The issue looks when collecting pytest.ini in a specific kernel doesn't take effect when calling pytest, but I haven't been able to find a way to fix this issue. Any comments, concerns are appreciated!


text:
Q: How to filter data on a monthly basis and form the appropriate arrays? I have collections that come from the server after a client request (date range).
For example, incoming data, after which I form the length of the array:

*

*2018/04/12 and 2018/10/12 => array.length = 7 (months)

*2018/05/12 and 2018/10/12 => array.length = 6 (months)

*2018/09/12 and 2018/10/12 => array.length = 2 (months)

A response comes from the server in the form of collections that correspond to the requested date range by the date_call parameter
For example:
Requested data: 2018/10/01 and 2018/10/12
if the document on the date_call parameter corresponds to the requested range (for example, date_call = 2018/10 /01..12) - send the response in the following form
{
    "_id" : ObjectId("5bbb299f06229dddbaab553b"),
    "phone" : "+38 (031) 231-23-21",
    "date_call" : "2018-10-08",
    "adress_delivery" : "1",
    "quantity_concrete" : "1",
    "state" : "200",
    "comments" : "1",
    "is_order" : "n",
    "date_delivery" : "",
    "quantity_orders" : "",
    "summ_order" : "",
    "profit" : "",
    "id" : "0"
}

There may be many such collections.

In data.labels, I have an array with the names of the months that was requested (which I formed in array - Months).
In datasets.data there will be 3 arrays - DataCalls, DataOrders, DataProfit

*

*In DataCalls, the amount of call documents (date_call) monthly

*In DataOrders - the amount of the number of orders (is_order)
monthly

*In DataProfit - the amount of profit (profit) monthly

QUESTION(s):

*

*What is the best way to create arrays of Data Calls, Data Orders,
Data Profit?

*Or is it perhaps better to form approximately such an
object in JSON right away?

    {
        "Month": "April",
        "Calls": 75,
        "Orders": "20",
        "Profit": "1500"
    }

Here is screenshot desirable result with right data

A: JSON is definitely the way to go here, but I'd advise adding the "year" property to your JSON object as well so that you can then execute date calculations if needed on the front end. You could go even deeper and send the actual transactions and do the calculation on the front end.


text:
Q: Natural Deduction (FeedBack) I am looking for feedback to three proofs (alternatively derivations) that I have constructed. The first is:

Theorem. Injectivity does not imply surjectivity.

Proof: Suppose $\{\phi\} \vdash \theta$. Then according to the soundness theorem we have $\{\phi\} \models \theta$, which is to say that for every valuation $v$, $[[\phi]]_{v}=1 \implies [[\theta]]_{v}=1$. However, consider the following structure $\langle \mathbb{N};; +, \cdot, 1 \rangle$ which gives rise to the following formula $\exists x_{1}(x_{0} \dot{=} f_{2}(f_{1}(\overline{c}_{0},\overline{c}_{0}),x_{1}))$.Now, from this formula we define a function as follows:
$$f:\mathbb{N} \to \mathbb{N}, $$
$$f(x)=2x$$
This function is clearly injective. However it is equally clear that it is not surjective, as  there are elements in the range that the function does not map to, more specifically all odd numbers. Thus, we have a case where $[[\{\phi\}]]_{v}=1$ while $[[\{\theta\}]]_{v}=0$, which shows $\{\theta \}$ is not a logical consequence of $\{\phi\}$ ($\{\phi\} \not \models \{\theta\}$). Hence, by the completeness theorem we have $\{\phi\} \not \vdash \theta$, or in more informal terms, the injective property does not imply the surjective property. $\square$
The two other proofs are a bit more complicated to present. As far as I can tell (and believe me I have tried), Math Stack Exchange does not support bussproof, which is a LateX package that enables users to construct proof trees. Furthermore, I haven't been able to simply attach a PDF file of the derivations (again Math Stack Exchange does not support it). As a result, I have decided to post my codes, hoping you (the community) still are willing to provide some feedback.

A: *

*The counterexample to injectivity implying surjectivity is presented in a quite unnecessary laborious way. You will be marked down for obfuscation.

*The universally quantified wffs at the top of both branches of the first displayed proof shouldn't be at the same level as the existential. Move the existentials down five lines, and then you need to repeat the conclusion of the sub proof. Thus ...
$\quad\quad\quad\quad\quad\quad\varphi\\
\quad\quad\quad\quad\quad\quad\ldots\\
\quad\quad\quad\quad\quad\quad\ldots\\
\quad\quad\exists x\varphi\quad\quad C\\
\quad\quad -----\\
\quad\quad\quad\quad C$
See van Dalen section 2.9, or other texts.
Here's the proof done Fitch-style:  Natural Deduction and Identity .
[Yes, it would be good if we could use bussproofs here!]

A: I have made changes to the derivations - does this look better? Moreover, is the second derivation convincing (or rightly performed)?

A: I have a new suggestion as to how to correct my mistake in 0.2; namely I introduce an assumption $f(f(x)) \dot{=} f(a)$ as the minor premise while I at the same time derive $f(f(x)) \dot{=} f(a) \to f(x) \dot{=}a$ as the major premise (from injectivity). Then, I use $\exists E$ at the next step to conclude $f(x) \dot{=} a$. From thereon, I use the Idempotence property to arrive at my desired conclusion. Does this sound more reasonable?


text:
Q: Why cat command redirect a new file get executed right away? I want to generate a bash file that could be called later, like this
cat <<-SCRIPT >test-$$
        #!/bin/bash
        osType=$(grep -Po '^NAME="\K[^"]*' /etc/os-release)
        if [ "$osType" = ...]
        then
            ...
        fi
        exit
    SCRIPT

while I am dubugging, the grep command always get execute right way, why? also try with awk same error
but if I do this
cat <<-SCRIPT >test-$$
        #!/bin/bash
        rpm -q somepackage > test-$$
        rm test-$$-lock
        exit
    SCRIPT

I don't see the rpm command get executed right way?
Also does test-$$ and test-$$-lock will have the same $$?

A: A here-doc like <<-SCRIPT acts like a double-quoted string in that expansions are processed within it. To prevent that, quote the delimiter:
$ cat <<EOF
1+1 = $((1+1))
EOF

1+1 = 2

vs.
$ cat <<'EOF'
1+1 = $((1+1))
EOF

1+1 = $((1+1))

So, here:
cat <<-SCRIPT >test-$$
        ...
        osType=$(grep -Po '^NAME="\K[^"]*' /etc/os-release)

The grep command is within a command substitution which gets processed because SCRIPT is not quoted, so it is executed when the here-doc is used.
Here, on the other hand:
cat <<-SCRIPT >test-$$
        #!/bin/bash
        rpm -q somepackage > test-$$
        rm test-$$-lock
        exit
    SCRIPT

there's no command substitution, so no commands run. The rpm -q somepackage part is just text. However, with an unquoted delimiter, $$ inside the here-doc would be expanded immediately, to the same value used in the name of the output file. That is, if the current shell's PID is 1234, the cat command would create test-1234 containing the line rpm -q somepackage > test-1234.
With a quoted delimiter, the $$ would be left as-is, and the result would be file called test-1234 containing rpm -q somepackage > test-$$. If you now ran test-1234 as a script, the $$ would be expanded then, and that shell's PID would be used. It would probably be different from the value used when creating the file.
In any case, the $$ in rpm .. > test-$$ and rm test-$$-lock would get expanded to the same value.


text:
Q: Is the following a vector space? : The set of all solutions of the differential equation $y''+y=\cos t$ I understand I can show something is a vector space by showing it is a subspace using the three known axioms. I know I can find the general solution of the DE and seeing if it is a vector space. But can I re-write the equation into a system of first order equations, like so?
$x_1'=  x_2$
$x_2'= -x_1 + \cos t$
But then how do I show it now? Does it even contain the $\vec 0$ vector?

A: A set $V $ is only a vector space if it complies with some axioms, one of which is the existance of the null vector, $0$. Now just note that $y=0$ does not solve your equation, meaning that the set of all its solutions is not a vector space.

A: No. Let $y_1$ and $y_2$ be solutions. Then $L[y_1 + y_2] = \cos t + \cos t = 2\cos t \neq \cos t$ so it is not closed under addition.

A: However, it is an affine space, i.e. it is a vector space translated by a particular solution, since the set of differences of any two solutions is a vector space.


text:
Q: How to convert a date to different format in Python to calculate age I have a dataframe df with a DOB (date of birth) that is in the format of "Year-Month-Day (1994-01-01)" and the DOB variable is an object.
I need to assign age to each person using this DOB variable. I noticed I need to use datetime to find age, and I need to convert the format to "Year/Month/Day (1994/01/01)" first.
I wonder if someone can help.
Thanks!

A: now = pd.Timestamp('now')
df['dob'] = pd.to_datetime(df['dob'])
df['age'] = (now - df['dob']).astype('<m8[Y]')
print(df)

covert your str into datetime objects
You can subtract dob from now to obtain timedelta64[ns]. To convert that to years, use astype('

for your last formatting
df['dob'].apply(lambda x: x.strftime('%Y/%m/%d'))


text:
Q: How can I shrink a 4-column flexbox layout to 2 columns in Polymer? I have a dashboard I made with Polymer and the flex layout, however there's some issues. Basically I need it to be 4 columns long, but when the screen shrinks I need it to go to 2 columns, and then finally to 1 column. (basically laptop - 4, tablet - 2, phone - 1). Right now it goes 4 to 3 to 2 to 1. How can I achieve the 4 to 2 to 1?
Here's what I currently have:

and

        <paper-card heading="ep-gw-ops-node1">

            <paper-card heading="Temperature" id="temperature" class="blue" style="width: 275px; margin: 2px">

 0

            </paper-card>

    ...

    ...

    ...

</paper-card>

I've attached a basic wireframe of what I am trying to accomplish.
If there is a better way to do it without paper-cards I'm more than open to suggestions.
Note* the last column will be lowered so the 'node 1' header will stretch all the way across and the columns will be the same size.

A: I do something like this
<dom-module id="my-element">
  <template>

    <iron-media-query query="(min-width: 600px)" query-matches="{{wide}}"></iron-media-query>

        <paper-card>...</paper-card>
        <paper-card>...</paper-card>

  </template>


text:
Q: Cannot get proper div with jquery plugin I have this codepen with a basic jquery plugin.
https://codepen.io/stephendesjardins/pen/jZZozK
When I click on the div box. I want it to find his .dot div and add class "haya".
For some odd reason it add it to the second box instead of the first one.
They wanted me to add more details to post this post. So I guess, I can say that I found the plugin template on github.
 /*!
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;(function ( $, window, document, undefined ) {

    // undefined is used here as the undefined global
    // variable in ECMAScript 3 and is mutable (i.e. it can
    // be changed by someone else). undefined isn't really
    // being passed in so we can ensure that its value is
    // truly undefined. In ES5, undefined can no longer be
    // modified.

    // window and document are passed through as local
    // variables rather than as globals, because this (slightly)
    // quickens the resolution process and can be more
    // efficiently minified (especially when both are
    // regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = "defaultPluginName",
        defaults = {
            propertyName: "value"
        };

    // The actual plugin constructor
    function Plugin( element, options ) {
      console.log(element);
        that = this;
        this.element = element;

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype = {

        init: function() {
            // Place initialization logic here
            // You already have access to the DOM element and
            // the options via the instance, e.g. this.element
            // and this.options
            // you can add more functions like the one below and
            // call them like so: this.yourOtherFunction(this.element, this.options).

          $(this.element).on('click', function(){
            $(this).addClass('bleh');
            $(that.element).find('.dot').addClass('haya')
          })
        },

        yourOtherFunction: function(el, options) {
            // some logic
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin( this, options ));
            }
        });
    };

  })( jQuery, window, document );

  $('.box').defaultPluginName();

  $('.box2').defaultPluginName();

A: $(that.element) is targeting the second parent div. Change $(that.element).find('.dot').addClass('haya') to $(this).find('.dot').addClass('haya')


text:
Q: MVC 3 Custom ValidationAttribute for CheckBoxFor firing twice on client-side  I'm going to lay out the code to explain the whole situation then pose the description of the problem:
In my View Model I have a boolean property to track whether the user has accepted terms:
 [MustBeTrue(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "MustAccept")]
 public bool HasAuthorizedBanking { get; set; }

As you can see I've created a custom validation attribute to handle this called MustBeTrue to handle the Checkbox, since [Required] is currently not working for client-side validation on Checkboxes in MVC 3
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if ((bool)value)
            return ValidationResult.Success;

        return new ValidationResult(String.Format(ErrorMessageString,validationContext.DisplayName));
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "truerequired"
        };

        yield return rule;
    }
}

Then I add a CheckBoxFor with a ValidationMessage to my View:
@Html.CheckBoxFor(model => model.HasAuthorizedBanking)
@Html.ValidationMessageFor(model => model.HasAuthorizedBanking, "", new { @class = "validationtext" })

In order to implement this client-side I created a jQuery validator method, and added an unobtrusive adapter:
// Checkbox Validation
jQuery.validator.addMethod("checkrequired", function (value, element) {
    var checked = false;
    checked = $(element).is(':checked');
    return checked;
}, '');

jQuery.validator.unobtrusive.adapters.addBool("truerequired", "checkrequired");

In my view all the steps in the signup process are on one page, the elements are hidden and shown via jQuery and validated using jQuery Validation. When the 'Next' button is clicked each input element on the page is triggered for validation:
 var validator = $("#WizardForm").validate(); // obtain validator
    var anyError = false;
    $step.find("input").each(function () {
        if (!validator.element(this)) { // validate every input element inside this step
            anyError = true;
        }

    });

    if (anyError)
        return false;

Notes:

*

*There is only one property in my model with the MustBeTrue attribute, and there is only one CheckBoxFor & matching ValidationMessageFor on the entire page.

*In order to track when this method is being called I simply put an alert(checked); inside the jQuery Validator method 'checkrequired'.

The problem: When the checkbox is checked/unchecked the 'checkrequired' method is fired once. However, when the 'Next' button is clicked and we set off to validate all the input elements, it is fired twice whether or not the checkbox is checked. Interestingly, if it is checked, the first validation returns true and the second returns false (this second false return is my main problem - the page will not validate and it will not allow you to continue to the next step). Additionally, when it is checked and Next is clicked - the ValidationMessageFor message disappears as though it is valid.
Edit:  I have another Custom Attribute for validating Age in a jQuery DatePicker textbox, and while it is implemented this exact same way - it only fires once under the same conditions.

A: It turns out the issue is that a second input element with the same name as the checkbox was being generated by Html.CheckBoxFor, as described here: http://forums.asp.net/t/1314753.aspx
<input data-val="true" data-val-required="The HasAuthorizedBanking field is required." data-val-truerequired="You must accept to continue." id="bankingtermscheckbox" name="HasAuthorizedBanking" type="checkbox" value="true" />
<input name="HasAuthorizedBanking" type="hidden" value="false" />

The fix was to change the jQuery selector to only look at input elements whose type is not hidden:
$step.find(':input:not(:hidden)').each(function () { // Select all input elements except those that are hidden
        if (!validator.element(this)) { // validate every input element inside this step
            anyError = true;
        }

    });

    if (anyError)
        return false; // exit if any error found


text:
Q: It is ok to handle soft 404 errors with noindex, nofollow tag? Recently my site has experiencing lot of soft 404 errors from auto-generated menu links returning not found pages. But it will eventually filled with contents overtime, so I want to temporarily disable to search engines from crawling these pages.
(e.g. PSP > Kingdom Hearts > Cheats. It will return page with "sorry no cheats are available yet" message.)
Do you guys think this will work?
Edit: I have removed these links already from the site, but the search engines are already crawled and returning soft 404 errors.

A:
...from auto-generated menu links returning not found pages. But it will eventually filled with contents overtime

I would not display links which lead to non-existent pages. That these pages will "eventually filled with contents overtime" does not matter.
Apart from SEO this is also horrible user-experience: Imaging browsing a webpage, and every third link you click on returns a 404 page saying that "content will eventually filled in later". If you do not have content, don't display links to it.

A: it is not the best practice but you might want to use redirection to 302 redirection:
The HTTP response status code 302 Found is a common way of performing a redirection. An HTTP response with this status code will additionally provide a URL in the Location header field
if it is permanent and you don't need dynamic solution use this:
you can use robots.txt and to Disallow search engine from getting into those urls until you will add a content to them, then open it when the pages are ready.
create robots.txt in your root directory /robots.text
and fill it with the follwing
User-agent: *
Disallow: /cgi-bin/
Disallow: /tmp/
Disallow: /~joe/


text:
Q: How to join a query result with a value, received from another query? I want to calculate transaction costs in USD
for a number of most recent transactions
on the Rootstock blockchain.
I have a PostgreSQL database table with token
prices reports.token_prices
from which I select the value
of the latest available RBTC price in USD:
select tp.price_in_usd
from reports.token_prices tp
where tp.chain_id = 30
and tp.coingecko_token_id = 'rootstock'
order by tp.dt desc
limit 1

(note that tp.dt is a timestamp)
Result of the query:
16995.771

Then I have a table with all transactions,
chain_rsk_mainnet.block_transactions,
from which I select the gas fees
for the 5 most recent ones:
select
bt.fees_paid
from chain_rsk_mainnet.block_transactions bt
order by bt.block_id desc, bt.tx_offset
limit 5

(note that instead of using a timestamp, I'm using bt.block_id and bt.tx_offset for transaction order)
Result:
0
4469416300800
4469416300800
16450260000000
0

Now I want to multiply each of these numbers
by the result of the first query.
How can I do this in SQL?

A: Without further information your simplest option would be just convert the first query into a CTE then Join that result in the second query.
with  price_cte(price_in_usd) as
      (select tp.price_in_usd
         from reports.token_prices tp
        where tp.chain_id = 30
          and tp.coingecko_token_id = 'rootstock'
        order by tp.dt desc
        limit 1
      )
select bt.fees_paid * p.price_in_usd)  "Fees Paid in USD"
  from chain_rsk_mainnet.block_transactions bt
  cross join price_cte p
 order by bt.block_id desc, bt.tx_offset
 limit 5;

NOTE: Not tested, no sample data nor results.


text:
Q: I'm not able to install opencv in pycharm? I have downloaded opencv through cmd using pip install opencv-python. But when I run simple read write program in pycharm it couldn't load import cv2 command when I search then, I came to know that pycharm have some other way to install opencv. I did it setting->project->project interperter then I search for
opencv-python but it gives me this error during installation:
Collecting opencv-python
  Could not fetch URL https://pypi.org/simple/opencv-python/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/opencv-python/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/opencv-python/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/opencv-python/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/opencv-python/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/opencv-python/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/opencv-python/
  Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

I have the latest version of python and pip but though I am getting this error could anyone help me, please.

A: It's most likely that you installed opencv in the base conda environment and not the environment you activated as interpreter or that you installed it in the environment you created and have the base env activated:
Try the following set of steps:
conda create -n envname python
conda activate envname
pip install opencv-python
Go to pycharm and add the envname environment to pycharm interpreters, activate it and then run the code.

A: Your initial error is:
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available."))

If you are Windows user, set following paths to System's PATH environment variable:
If using Anaconda:
<system_path>\Anaconda3
<system_path>\Anaconda3\scripts
<system_path>\Anaconda3\Library\bin

If only Python is installed on your system then(I am assuming Python 3.6 is installed in your system):
<system_path_where_python_is_installed>\Python36
<system_path_where_python_is_installed>\Python36\Scripts
<system_path_where_python_is_installed>\Python36\Library\bin

And then try to install opencv via PyCharm.
Hope this solves your problem.


text:
Q: Database structure for 2000 data per second and real-time shown? I am working on a monitoring project based on Web. There are nearly 50 sensors with the sample frequency 50Hz. All the raw data of sensor must be stored into the database. That means that nearly 2500 data per second will be deal and 200 million per day. And the data must be saved for at least three years. My job is making a webserver to show the real-time and historical sensor data through the database. The time-delay displaying is allowed.

*

*Which database should we choose for this application?  SQL server or Oracle?  Is it possible for these databases to stand so huge I/O transactions per second?

*How to design the database structure for real-time data and historical data? My opinions are that there are two databases, one store real-time data, another store historical data. First the coming data was stored in real-time database, and at the some time(eg. 23:59:59 every day ), I write a sql transaction to transfer the real-time data to the historical database. So for the real-time displaying, it read the real-time database.  And for historical data shown, it read historical database. Is it feasible? And how to determine the time to transfer the data? I think on day is too long for some huge data.

*How to store the time information? It comes a data per 20 million seconds. For one data + one time information, the database will expand so huge. For that the datetime type of sql server 2008 take 8 byte space. For 50 data+ one time information , the volume of database will reduce ,but for the data shown , it will cost time to get ervery data from the 50 data. How to balance the database size and the efficient of data reading?


text:
Q: Vim formatted print date to current file I am trying to print the current formatted as Mon, 1 Jan 2022 into my current file in vim. So far I've tried the following command, but the % sign gets put into the command as the current file.
:0r !date '+%a, %d %b %Y'

This ends up giving me  an output similar to seen below.
/home/user/file.txta, /home/user/file.txtd /home/user/fileb /home/user/fileY

The issue is that the path to the current file is put in place for % as vim does, but that is causing issues for the current use case.
Any help is appreciated

A: The immediate solution is obviously to escape the %:
:0r !date '+\%a, \%d \%b \%Y'

But you might be interested by the built-in :help strftime(), which doesn't require escaping:
:0put=strftime('%a, %d %b %Y')


text:
Q: How do I resolve conflicts with Git? I have a pull request for which GitHub tells me "This branch has conflicts that must be resolved." I tried:
~/src/networkx: git rebase origin/master
Current branch topo is up to date.
~/src/networkx: git merge origin/master
Already up-to-date.

A: First you need to make sure you have the upstream remote repository set:
git remote add upstream git@github.com:networkx/networkx.git

Then You need to fetch upstream/master and then rebase on that. It's something along the lines of:
git fetch upstream
git checkout <feature-branch>
git rebase upstream/master

As git replays your work on top of upstream/master, conflicts will be raised and you'll have to dive into the files to resolve them. Then you:
git add <files that you fixed>
git rebase --continue

A: Actually... you don't have anymore to pull and rebase locally.
You can resolve (simple) merge conflicts right form GitHub, since Dec. 2016.
See "Resolve simple merge conflicts on GitHub "

You can now resolve simple merge conflicts on GitHub right from your pull requests, saving you a trip to the command line and helping your team merge pull requests faster.

The new feature helps you resolve conflicts caused by competing line changes, like when people make different changes to the same line of the same file on different branches in your Git repository.
You'll still have to resolve other, more complicated conflicts locally on the command line.

A: Try running this to see what remotes you have set up:
git remote -v

If you don't already have a remote for the original repository you forked from in Github, you can add it as follows:
git remote add upstream https://github.com/networkx/networkx.git

This will name the remote upstream. After this, you can merge in the latest upstream into your branch and resolve your conflicts:
git fetch upstream
git merge upstream/master

If the first git remote -v command already showed a remote with that name, just use that instead of adding a new remote. Hope that helps.


text:
Q: javax.naming.NameNotFoundException: Resource /WEB-INF/classes not found with maven tomcat plugin i am running on maven 2 and i am using the Apache Tomcat Maven Plugin for tomcat 7
with the following configuration:
<plugin>
  <groupId>org.apache.tomcat.maven</groupId>
  <artifactId>tomcat7-maven-plugin</artifactId>
  <version>2.0-beta-1</version>
    <configuration>
      <path>/${project.build.finalName}</path>
    </configuration>
</plugin>

but when trying to run the application with mvn tomcat7:run
i am getting the following exception:
SEVERE: Unable to determine URL for WEB-INF/classes
javax.naming.NameNotFoundException: Resource /WEB-INF/classes not found
        at org.apache.naming.resources.BaseDirContext.listBindings(BaseDirContext.java:733)
        at org.apache.naming.resources.ProxyDirContext.listBindings(ProxyDirContext.java:546)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1197)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:825)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:300)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1568)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1558)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
        at java.util.concurrent.FutureTask.run(FutureTask.java:138)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:662)

please advise how to fix this exception.

A: It seems that is a problem in the tomcat version bundled with the tomcat7-maven-plugin (which is fixed to 7.0.25). See this answer on a similar question.


text:
Q: Variation of paramters in DE I need to solve this equatiom using variation or parameter
$x^2y''-xy'+y=4x+3\ln x$
By making the change of variables $x=e^t$
I understand plugging in the variable and dividing by $e^{2t}$
But how do I get 2 linear independent solutions or a $y_c$ so I can set up a wronskian and then determine $y_p$ then add it to $y_c$ to solve for $y$.

A: Making the substitution $x=e^t$ results in an auxiliary equation
\begin{equation}
m(m-1)-m+1=0
\end{equation}
or
\begin{equation}
m^2-2m+1=0
\end{equation}
So in terms of $t$ the equation becomes
\begin{equation}
\dfrac{d^2y}{dt^2}-2\dfrac{dy}{dt}+y=4e^t+3t
\end{equation}
Since the solution to the auxiliary equation is $m=1,1$ the solution to the homogeneous equation is
\begin{equation}
y_c=c_1e^t+c_2te^t
\end{equation}
So the two linearly independent functions you need for the Wronskian are $y_1(t)=e^t$ and $y_2(t)=te^t$.
From there you should be able to find the variable parameters $u_1,u_2$ satisfying
\begin{equation}
y_p=u_1e^t+u_2te^t
\end{equation}
which satisfies the non-homogeneous equation.


text:
Q: webusercontrol problem I have one webusercontrol for Datepicker. When I am using this control in content pages it works fine. I have many controls in content page (textbox, label, etc.). All controls are inside a table. I have placed usercontrol inside <td>. When I click on an image, the calendar control is showing. But that time this calender control pushes all other controls (textbox, label, etc.). I have set the z-index at a higher value, but still it's not working.
alt text http://www.shareimages.com/images/thumbs/0/0/1/39586-qJyWopyZlqGlk6CVmw-datepicker.jpg

A: Z-index will not work for you becuase it is made for absolute,fixed and relative positioned elements.
in your case what happened is when the calendar was not loaded the cell was empty but when you opened the calenday it filled the cell and expanded the row which it expanded the table. which causes the elements who are inside the tabe to change their position.
try not to put the calendar over the other rows. create new column. set rowspan and put the calendar inside that cell which it will expand in its cell with out affecting the other rows since it is in different column (this will change the desiegn but it is the easy way)


text:
Q: Does automatic updates reboots Windows Server 2008? Does automatic updates reboots Windows Server 2008 ?

A: By default, yes! It depends on the specific updates though. Some don't require a reboot, but many do.

A: This behavior is entirely configurable. You can change the Windows Updates settings through the control panel. If you're working with a Server Core installation, you'll have to do it from the command line. Server 2008 R2 Core has a sconfig utility that provides a series of menus to make this (and other basic configuration tasks) very easy, but Server 2008 RTM Core has a script that accepts parameters to make it...um...possible.
In NT 6.0, there are five possible values for the registry key HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\AUOptions: 1 = disabled; 2 = notify before
   download, notify before install; 3 =
   download updates automatically,
   notify when they're ready to install
   (default on a full install of Windows
   Server 2008); 4 = automatic download,
   automatic install at 3 AM; 5 = allow
   local admin to select configuration
   mode
To use the scregedit script for this or other configuration tasks, you must CD to the directory where it is located:
cd c:\windows\system32

To view the currently configured option:
cscript scregedit.wsf /au /v

To set an option:
cscript scregedit.wsf /au 4

...where "4" could be whichever option-value you choose to set.
Stop and restart the Windows Update service to put this change in effect:
net stop wuauserv
net start wuauserv

At this point, you can just leave the machine to update itself on schedule, or you can force update detection like so:
wuauclt /detectnow

I hope this helps!

A: Yes, unless you choose an option other than automatic.


text:
Q: Can my team members use a specific runner in GitLab registered for a project by me (maintainer) in my laptop even when I shut down my laptop? We as a team are working in a branch in GitLab. I (maintainer) registered a specific runner for this project in my laptop to execute the pipeline. Can my team members use this runner registered by me even when I shut down my system? What happens in case of I registered my runner within docker ?

A: If a machine is turned off it cannot execute a pipeline.


text:
Q: Edittext - Mask with date format
I use redMadRobot/input-mask library to mask edittext. But I need space between DD / MM  / YYYY like in example image and / symbol must be always visible. But I can't do it with this library as I see.
Code :
const val DATE_MASK = "[00]{/}[00]{/}[9900]"

MaskedTextChangedListener.Companion.installOn(
            editText, DATE_MASK, object : MaskedTextChangedListener.ValueListener {
                override fun onTextChanged(
                    maskFilled: Boolean,
                    extractedValue: String,
                    formattedValue: String
                ) {
                    //transactions
                }
            }
        )

Is there any native edittext property to make this desgin or can you suggest another library?

A: Library author here.
input-mask-android is about text formatting, but your question looks more layout-related.
Three EditText components plus two / labels between them might do the trick. setOnEditorActionListener and TextWatcher listeners will help with cursor movement.
Or you could just put a couple of spaces within curly brackets and call it a day:  [00]{ / }[00]{ / }[9900]
I'd also suggest reading more about our affine masks, and then use a couple of patterns for the sake of year correctness:

*

*[00]{ / }[00]{ / }[00]

*[00]{ / }[00]{ / }[0000]


text:
Q: Add a model transformer that transforms multiple fields in embedded form I am trying to read a \DateInterval from 2 input fields, as follows :
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, ['label' => "Name"])
        ->add('duration', DateIntervalType::class, ['label' => false])
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(['data_class' => NamedInterval::class]);
}

Here's my DateIntervalType::buildForm :
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('amount', IntegerType::class)
        ->add('kind', ChoiceType::class, ['choices' => ['Year' => 'Y', 'Month' => 'M', 'Week' => 'W']])
    ;
}

And here is the transformer I attempted :
$builder->get('duration')->addModelTransformer(new CallbackTransformer(
    function ($property) {
        return new \DateInterval('P' . $property['amount'] . $property['kind']);
    },
    function ($property) {
        /* compute $specString from $property assuming it's a \DateInterval */
        /* ... */
        return ['amount' => 1, 'kind' => 'W'];
    }
));

Hence this is not working, my $property is always null after validating the form when transforming from form data to \DateInterval and I'm not even sure that I ever used the transformer from \DateInterval to form data, what I am doing wrong?

A: It appears that the CallbackTransformer is inversed :
$builder->get('duration')->addModelTransformer(new CallbackTransformer(
    function ($property) {
        /* compute specString from $property assuming it's a \DateInterval */
        /* ... */
        return ['amount' => 1, 'kind' => 'W'];
    },
    function ($property) {
        if (!$property) return null;
        return new \DateInterval('P' . $property['amount'] . $property['kind']);
    }
));

Now it works like a charm !
EDIT: as \DateInterval converts weeks to days, there also should be an option 'Day' => 'D' in the options list.


text:
Q: Why do "Joining, by =" messages bleed through in Rmarkdown code blocks despite using warning=FALSE? Should I report as a bug? A helpful sequence here (suppress comment "joining by..." when running dplyr::left_join) shows that you can suppress the message by explicitly stipulating the joining variable or by wrapping the whole dplyr block in suppressWarnings to get rid of this bleed through.
This is useful but I don't understand why neither "message=FALSE" nor "warning=FALSE" in an Rmarkdown code block header suppresses this message?  The message seems somewhere between a message and a warning to judge by comments on it elsewhere but I would have thought we should be able to suppress the message with one of those block options.
I do understand the logic behind having the message when "by = " is not specified and I do know about suppressWarnings but wrapping dplyr blocks in anything seems a poor fit with the useful tidyverse syntax.
Is this worth a bug report or feature request?  And if so, to whom: is the issue with how dplyr emits the message or with knit or somewhere else?

A: For me, the best option is to set your by argument explicitly:
tib1 %>%
    left_join(tib2, by = "lwr") %>%
    pander()

Alternately, use suppessMesseages:
suppressMessages(tib1 %>%
                   left_join(tib2) %>%
                   pander())


text:
Q: How can I restore my Unity? I can't restore my Unity using reset
root@vitor:~# unity --reset
WARNING: Unity currently default profile, so switching to metacity while resetting the values
unity-panel-service: nenhum processo localizado
Checking if settings need to be migrated ...no
Checking if internal files need to be migrated ...no
Backend     : gconf
Integration : true
Profile     : unity
Adding plugins
Initializing core options...done
compiz (core) - Warn: failed to receive ConfigureNotify event on 0x2e000b8

Initializing composite options...done
Initializing opengl options...done
Initializing decor options...done
Initializing vpswitch options...done
Initializing snap options...done
Initializing mousepoll options...done
Initializing resize options...done
Initializing place options...done
Initializing move options...done
Initializing wall options...done
Initializing grid options...done
Initializing session options...done
Initializing gnomecompat options...done
Initializing animation options...done
Initializing fade options...done
Initializing unitymtgrabhandles options...done
Initializing workarounds options...done
Initializing scale options...done
compiz (expo) - Warn: failed to bind image to texture
Initializing expo options...done
Initializing ezoom options...done

(compiz:2174): GConf-CRITICAL **: gconf_client_add_dir: assertion `gconf_valid_key (dirname, NULL)' failed
WARN  2013-10-01 23:14:25 unity.favorites FavoriteStoreGSettings.cpp:139 Unable to load GDesktopAppInfo for 'ubiquity-gtkui.desktop'
ERROR 2013-10-01 23:14:26 unity.launcher.trashlaunchericon TrashLauncherIcon.cpp:62 Could not create file monitor for trash uri: Operação sem suporte
Initializing unityshell options...done
compiz (core) - Warn: unhandled ConfigureNotify on 0xe000a7!
compiz (core) - Warn: this should never happen. you should probably file a bug about this.
WARN  2013-10-01 23:14:28 unity.libindicator <unknown>:0 Desktop file '/usr/share/applications/libreoffice-writer.desktop' is using a deprecated format for its actions that will be dropped soon.
WARN  2013-10-01 23:14:28 unity.libindicator <unknown>:0 Desktop file '/usr/share/applications/libreoffice-calc.desktop' is using a deprecated format for its actions that will be dropped soon.
WARN  2013-10-01 23:14:28 unity.libindicator <unknown>:0 Desktop file '/usr/share/applications/libreoffice-impress.desktop' is using a deprecated format for its actions that will be dropped soon.
WARN  2013-10-01 23:14:28 unity <unknown>:0 Unable to fetch children: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000

WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch path: Nenhuma interface "org.ayatana.bamf.application" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Unable to fetch children: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000

WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch icon: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch name: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch boolean: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch boolean: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch boolean: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Unable to fetch children: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000

WARN  2013-10-01 23:14:28 unity <unknown>:0 Unable to fetch children: Nenhuma interface "org.ayatana.bamf.view" no objeto no caminho /org/ayatana/bamf/application0x1fbe000

WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch path: Nenhuma interface "org.ayatana.bamf.application" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch path: Nenhuma interface "org.ayatana.bamf.application" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch path: Nenhuma interface "org.ayatana.bamf.application" no objeto no caminho /org/ayatana/bamf/application0x1fbe000
WARN  2013-10-01 23:14:28 unity <unknown>:0 Failed to fetch type: Nenhuma interface "org.ayatana.bamf.window" no objeto no caminho /org/ayatana/bamf/window48234680
Initializing staticswitcher options...done
Setting Update "main_menu_key"
Setting Update "run_key"
WARN  2013-10-01 23:15:28 unity.glib.dbusproxy GLibDBusProxy.cpp:283 Calling method "InfoRequest" on object path: "/net/launchpad/lens/video" failed: GDBus.Error:org.freedesktop.DBus.Error.UnknownMethod: No such interface `com.canonical.Unity.Lens' on object at path /net/launchpad/lens/video
WARN  2013-10-01 23:15:28 unity.glib.dbusproxy GLibDBusProxy.cpp:283 Calling method "SetViewType" on object path: "/net/launchpad/lens/video" failed: GDBus.Error:org.freedesktop.DBus.Error.UnknownMethod: No such interface `com.canonical.Unity.Lens' on object at path /net/launchpad/lens/video

(firefox:2380): Gtk-CRITICAL **: IA__gtk_clipboard_set_with_data: assertion `targets != NULL' failed

(firefox:2380): Gtk-CRITICAL **: IA__gtk_clipboard_set_with_data: assertion `targets != NULL' failed

I use Ubuntu 12 for 64 bits.

A: try to download something like xfce and login as that (pretty easy to do from ubuntu's login screen, just click the little circle to the right of your name) and then run that command from in there. Another suggestion is to use ctrl + alt + F1 and run that from a terminal when no one is logged into unity. Might work, might not.


text:
Q: Are extensions of regular vertex operator algebras also regular? Let $U$ be a simple VOA which is  self-dual and of CFT type (i.e., $U\simeq U'$, and $U$ has grading $U=\bigoplus_{n\in\mathbb N}U(n)$ with $U(0)$ spanned by the vacuum vector $\Omega$).  Let $V$ be a (conformal) extension of $U$ which is also simple, self-dual, and of CFT type.
Now suppose that $U$ is regular, which means that any weak $U$-module is completely reducible (see Regularity of rational vertex operator algebras ). Can we show that $V$ is also regular?
This result is imporant as it shows as that the ribbon tensor category of $V$ is modular by Rigidity and modularity of vertex tensor categories. Showing regularity is equivalent to showing that $V$ is rational and $C_2$-cofinite (cf. Rationality, regularity, and $C_2$-cofiniteness). In our case, one suffices to show that $V$ is rational, as rational extensions of regular VOAs are always regular by Prop. 3.4 of Regularity of Rational Vertex Operator Algebras. So can we show that $V$ is rational, i.e., show that any admissible $V$-module (also called $\mathbb N$-gradable weak $V$-module) is completely reducible?

A: Update: I think it will be useful to have a more coherently written answer, since I have learned more since my original response. Under the assumptions of the question, the answer is yes, the vertex operator algebra $V$ will be regular, provided that the categorical dimension $\mathrm{dim}_{\mathcal{C}}\,V\neq 0$, where $\mathcal{C}$ is the modular tensor category of $U$-modules. So for instance if $U$ is a unitary regular VOA and $V$ is a unitary $U$-module, then the categorical dimension of $V$ will be a positive real number and $V$ will be regular. I'm not aware of any pathological extensions of non-unitary regular VOAs that have categorical dimension $0$, but I also don't know that these can be ruled out.
As noted in the question, to show that $V$ is regular, it is enough to show that $V$ is rational, i.e., show that if $W=\bigoplus_{n\geq 0} W(n)$ is an $\mathbb{N}$-gradable weak $V$-module, then $W$ is the direct sum of irreducible ordinary $V$-modules (modules $W$ for which the $W(n)$ are finite dimensional). The rationality of $V$ follows from three facts:

*

*$V$ is $C_2$-cofinite. This holds because $U$, as a regular VOA of CFT type, is $C_2$-cofinite, and therefore all ordinary $U$-modules, including $V$, are $C_2$-cofinite.

*The category of ordinary $V$-modules is semisimple. To prove this, one uses the results from https://arxiv.org/abs/1406.3420 that $V$ is a commutative associative algebra in the modular tensor category $\mathcal{C}$ and that the category of ordinary $V$-modules is the category of "dyslectic" modules $\mathrm{Rep}^0\,V$ for the algebra object $V$. Then Kirillov and Ostrik showed in https://arxiv.org/abs/math/0101219 that $\mathrm{Rep}^0\,V$ is semisimple under the assumption $\mathrm{dim}_{\mathcal{C}}\,V\neq 0$. (I am not sure how necessary the assumption on non-vanishing of the dimension is in the VOA context, but it is certainly necessary in other contexts: recall the converse to Maschke's Theorem.)

*If the ordinary module category of a $C_2$-cofinite VOA $V$ is semisimple, then $V$ is rational. This was proved by Carnahan and Miyamoto in Lemma 3.6 and Proposition 3.7 of https://arxiv.org/abs/1603.05645.

Another proof of 3. goes as follows. Let $W=\bigoplus_{n\geq 0} W(n)$ be an $\mathbb{N}$-gradable weak $V$-module; we need to show that $W$ is a direct sum of irreducible ordinary $V$-modules.
First assume that $W$ is generated by a homogeneous vector $w\in W(N)$ for some $N\geq 0$. Then by standard vertex algebra theory,
$$ W = \mathrm{span}\lbrace v_n w\,\vert\,v\in V, n\in\mathbb{Z}\rbrace, $$
and hence
$$ W(N)=\mathrm{span}\lbrace v_{\mathrm{wt}\,v-1} w\,\vert\,v\,\mathrm{homogeneous}\rbrace. $$
This means that $W(N)$ is singly-generated as a module for the $N$th Zhu's algebra $A_N(V)$ as in https://arxiv.org/abs/q-alg/9612010. But since $V$ is $C_2$-cofinite, $V$ is also $C_{2N+2}$-cofinite and therefore $A_N(V)$ is finite dimensional by Proposition 2.14 in https://arxiv.org/abs/0712.4109 (where the result is attributed to Miyamoto). Hence $W(N)$ is finite dimensional and generates $W$, and then Buhl's results in https://arxiv.org/abs/math/0111296 on spanning sets of weak modules for $C_2$-cofinite VOAs imply that $W$ is an ordinary $V$-module (see his Corollary 5.6). Thus $W$ is semisimple because the category of ordinary $V$-modules is semisimple.
Now take a general $\mathbb{N}$-gradable weak $W$. Then $W=\sum_{n\geq 0}\sum_{w\in W(n)} V\cdot w,$ where $V\cdot w$ is the $\mathbb{N}$-gradable weak $V$-submodule of $W$ generated by homogeneous $w$. By the previous case, each $V\cdot w$ is an ordinary and thus semisimple $V$-module. This means that $W$ is a sum, and therefore also a direct sum, of ordinary simple $V$-modules, completing the proof that $V$ is rational.
Original answer: As far as modularity of the category of $V$-modules is concerned, $V$ will effectively be regular under suitable conditions. The point is that since $V$ will be a commutative associative algebra object in the modular tensor category of $U$-modules, one can study its representations using the techniques developed in, for instance, Kirillov and Ostrik's paper https://arxiv.org/abs/math/0101219. They proved that if the base category $\mathcal{C}$ (in this case of $U$-modules) is modular, then so is the category of "dyslectic" modules for the extension provided that:

*

*$V$ is a simple VOA, and

*$\mathrm{dim}_{\mathcal{C}}\,V\neq 0$.
So for instance if $U$ is a unitary regular VOA, this result will apply because all quantum dimensions will be positive real numbers. I'm not aware of any pathological extensions of non-unitary regular VOAs that have quantum dimension $0$, but I also don't know that these can be ruled out.
I should also mention that to apply the tensor-categorical work of Kirillov and Ostrik to VOAs, one also needs the results in https://arxiv.org/abs/1406.3420 and my paper https://arxiv.org/abs/1705.05017 with Thomas Creutzig and Shashank Kanade showing that the tensor category of dyslectic modules for the extended algebra studied by Kirillov and Ostrik actually agrees with the vertex algebraic tensor category structure on the category of ordinary $V$-modules.
As far as whether the extended algebra $V$ is regular in the original sense of Dong, Li, and Mason, the above results certainly suggest that the answer should be yes, at least as long as $\mathrm{dim}_\mathcal{C}\,V\neq 0$, but I am not aware of whether this is known in general. One case that has been known for some time is the case of framed VOAs, i.e., conformal extensions of a tensor power of $c=\frac{1}{2}$ simple (and unitary!) Virasoro VOAs; the regularity of framed VOAs was proven in Theorem 2.12 and Corollary 2.13 of https://arxiv.org/abs/q-alg/9707008.


text:
Q: how to show a laoding bar with tkinter and tensorflow? I am currently loading a csv file with the help of tensorflow. Everything works without problems. Now I would like to try to create a gui using this method. With the help of a gui, I would like to create a loading bar to reflect the flow of the tensor flow. I came across tkinter because it has a loading bar. Can I integrate this with Tensorflow? If Yes, How do I do that?
import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
from sklearn.metrics import accuracy_score
from tkinter import *
from tkinter import ttk
import time

def load_tf():
    df = pd.read_csv('my_data.csv')
    X = pd.get_dummies(df.drop(['ID'], axis=1))
    y = df['ID']
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

    model = Sequential()
    model.add(Dense(units=32, activation='relu', input_dim=len(X_train.columns), return_sequences=True))
    model.add(Dense(units=64, activation='relu', return_sequences=True))
    model.add(Dense(units=1, activation='sigmoid', return_sequences=True))
    model.compile(loss='binary_crossentropy', optimizer='Adam', metrics='accuracy')
    model.fit(X_train, y_train, epochs=100, batch_size=32)
    model.save('tfmodel')

With my current Tkinter implementation, I can only run the function step(). I would like to do something like that with tensorflow. So when I click on a button, the bar should load.
root = Tk()

def step():
    for x in range(5):
        load_bar['value'] +=20
        root.update_idletasks()
        time.sleep(1)

load_bar = ttk.Progressbar(root, orient=HORIZONTAL, length=200, mode='determinate')
load_bar.pack()
button = Button(root, text="Start", command=step)
button.pack()

root.mainloop()


text:
Q: Function keys not working on Toshiba C-50-B I purchased a Toshiba C-50-B-P-0010 about a week back, it did not come pre-installed with any OS. I have installed Ubuntu 14.04. The function keys are not responding properly. If i press F3 which is for brightness, it put the laptop to sleep! I have tried all the solutions suggested in the following link. One difference i observed after following all the suggestions is that i can change my brightness through my system settings. But the function keys are still not working as they should be. Touch pad on/off is also not responding.
Brightness control doesn't seem to work on a Toshiba Satellite M115 laptop
I'm not very good at using the terminal, so please give detailed suggestions.
One of the suggestions is to update my BIOS, but the Toshiba India website drivers page doesn't have any BIOS for this model.

A: I've just got a Toshiba C50-B-14D model. I was able to make most of the function keys working with the following procedure:

*

*Make the /etc/udev/hwdb.d/70-keyboard.hwdb file with the following content (you will need root privileges to make the file):
#Satellite C50-B
keyboard:name:Toshiba input device:dmi:bvn*:bvr*:bd*:svnTOSHIBA*:pnSATELLITE*C50-B:pvr*
 KEYBOARD_KEY_13c=brightnessdown
 KEYBOARD_KEY_13d=brightnessup
 KEYBOARD_KEY_13e=switchvideomode
 KEYBOARD_KEY_13f=f21                                   # Touchpad toggle
 KEYBOARD_KEY_158=wlan

Note that it is important to have exactly one whitespace before the lines starting with KEYBOARD.

*Run sudo udevadm hwdb --update

*Run sudo udevadm trigger (This command would save you from restarting the machine, but if it doesn't work, try restarting the machine.)

After this the only key which do not work for me is the Wifi On/Off key.
To find more information on this process you can look e.g. here or here.


text:
Q: Custom JS selector is not taking effect at ngModel I have created a custom selector system with JS trying to make it look better. It looks perfect and changes the selector when I make it visible, but it doesn't changes my ngModel at my Angular component, keeping it at undefined. Here is my JS and HTML.

<div class="form__select">
  <select id="gender" name="gender" #gender="ngModel" [(ngModel)]="user.occupation">
    <option value="0">Selecciona un género</option>
    <option value="1">Hombre</option>
    <option value="2">Mujer</option>
    <option value="3">Otro</option>
  </select>
</div>

 load_selector() {
    const selectors: HTMLCollectionOf<Element> = document.getElementsByClassName("form__select");
    document.addEventListener("click", MainScript.close_selector);
    [].forEach.call(selectors, (selector) => {
      const select: any = selector.getElementsByTagName("select")[0];
      let replaced: HTMLElement = document.createElement("DIV");
      replaced.setAttribute("class", "form__select-box");
      replaced.innerHTML = select.options[select.selectedIndex].innerHTML;
      selector.appendChild(replaced);
      let option_parent: HTMLElement = document.createElement("DIV");
      option_parent.setAttribute("class", "form__select-items");
      [].forEach.call(select.options, (options) => {
        let option: HTMLElement = document.createElement("DIV");
        option.setAttribute("class", "form__select-item");
        option.innerHTML = options.innerHTML;
        option.addEventListener("click", function () {
          const parent_node: any = (<HTMLElement>(<HTMLElement>(<HTMLElement>this.parentNode)).parentNode).getElementsByTagName("select")[0];
          let previous_sibling: any = this.parentNode.previousSibling;
          for (let i = 0; i < parent_node.length; i++) {
            if (parent_node.options[i].innerHTML == this.innerHTML) {
              parent_node.selectedIndex = i;
              previous_sibling.innerHTML = (<HTMLElement>this).innerHTML;
              let actual_selected = (<HTMLElement>(<HTMLElement>this.parentNode)).getElementsByClassName("form__select-item--selected");
              [].forEach.call(actual_selected, (node) => {
                node.classList.remove("form__select-item--selected");
                node.classList.add("class", "form__select-item");
              });
              this.classList.add("form__select-item--selected");
            }
          }
          previous_sibling.click();
        });
        option_parent.appendChild(option);
      });
      selector.appendChild(option_parent);
      replaced.addEventListener("click", function (e) {
        e.stopPropagation();
        (<any>this).nextSibling.classList.toggle("form__select-items--active");
        (<any>this).classList.toggle("form__select-box--active");
      });
    });
  }


text:
Q: Anonymous web browser? It appears that it's easy to uniquely identify a user through all the infos returned by their browser:
https://panopticlick.eff.org/
Are there ways to "anonymify" a browser like Chrome or Firefox so that only the most basic infos are sent to the server?
What about web proxies like Squid, Privoxy, Proxomitron, etc.? Are they able to strip most of the infos?
Thank you.

A: The kind of information used by Panopticlick isn't the sort of thing that proxies can obscure (only the User Agent string and HTTP_ACCEPT Headers can be influenced by them).
If you're looking for a basic non-unique browser (but don't mind your IP being visible), a basic all-defaults install of Windows plus browser on a VM works reasonably well.
If you need "strong" anonymity, i.e. want to hide even your IP, look into the Tor Project ( http://www.torproject.org/ ).

A: If you want to browse anonymously, you must also refrain from using most browser plug-ins and most scripting.  Proxies, VPNs, and Tor can help but will not be able to protect your anonymity if you do not also follow several other precautions.  Consider using the Tor browser bundle for starters.
The Tor Project has some helpful recommendations on browsing habits that you will need to change in order to truly have any chance at remaining anonymous.
Also keep in mind that blending in with the crowd will work to your advantage.  If, for example, you configure NoScript to disable JavaScript but then allow JavaScript on specific websites, you will, in fact, be less  anonymous (although I've linked to a specific question, be sure to read that entire FAQ).

A: Although there are many sources of information available to a website from which your browser can be identified, the ones listed on the panopticlick experiment provide a good starting point for reducing the size of your browser's fingerprint. Focus on the characterstics that contain the most bits of identifying information.
Many of those characteristics rely on the execution of javascript code, which you can easily disable in most browsers, although that would severely impact your browsing experience. A more subtle approach would be to selectively allow javascript on websites you trust, for instance by using the Firefox plugin NoScript. Alternatively, since these scripts are executed locally, you can allow them to run and merely prevent the results from being sent back to the server by disabling AJAX. Details on how to accomplish this can be found here.
Another large source of entropy could be the user agent. Not using an exotic browser version or operating system would help, but may be inconvenient. You can also set the user agent manually, from the browser settings or through plugins, to gibberish, although you may be uniquely identified by that, or to a more common string. Shortly after the paniopticlick website was launched, the most frequent user agent in the project's dataset was 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7', but that information is both skewed and outdated. Ideally, you'd have to find more recent data elsewhere.
The HTTP_ACCEPT headers are far less customisable, but you may be able to reduce the entropy a little bit by keeping the number of preferred languages to a minimum or by switching away from an uncommon language. These settings are usually accessible from within the browser. Many websites are only available in one language and will ignore these settings anyway.
Note that these measures don't prevent tracking altogether; they merely reduce the size of your browser's fingerprint. IP addresses, cookies etc. can still be used as identifying information.


text:
Q: Definition of set of vectors obtained by a linear combination with bounded coefficients I am not able to find a definition of a set described by
$V = \{~ \boldsymbol{v} = \sum_{i=1}^k \lambda_i \boldsymbol{u}_i,\quad k \lt \infty,\quad 0 \leq \lambda_i \lt +\infty, \quad \lambda_i \in \mathbb{R},\quad \boldsymbol{v}, \boldsymbol{u}_i \in \Bbb R^n ~ \}$
I know it is a polyhedra, more specifically it will be a polytope, but this definition resembles a lot the one of convex hull, just with the different constraints on the coefficients, so I was wandering if it has actually a name.
I need this because I will have to do some calculations on this type of set, and right now i am not able to find anything about it.
Thank you in advance
EDIT: corrected typo in $\lambda_i \leq +\infty$

A: It is called conical hull, as you can see here: https://en.wikipedia.org/wiki/Conical_combination


text:
Q: how to pass int values in mysql query string? here my code-
$sqlpin = "SELECT pinId FROM tblpin WHERE pinId = '$pin_no', status = 0 ";

status is int type.
it is showing parse error.

A: SELECT pinId FROM tblpin WHERE pinId = '$pin_no' AND status = 0

A: Have you tried?
$sqlpin = "SELECT pinId FROM tblpin WHERE pinId = '$pin_no' and status = 0 ";

A: Syntax error is caused by comma in WHERE clause. You should use AND logical operator to connect these two conditions.
btw: If some column has numeric type don't pass values with apostrophes, just: colName = 123. Only text values requires apostrophes/quotes (in MySQL both has exactly the same meaning).


text:
Q: canvas draw bitmap crash on Android 10 but not on Android 8 I used canvas to draw bitmap and I used two version of android 8 and 10 to test. Somehow android 10 crash and I just dont seems to understand this error message:
java.lang.IllegalArgumentException: software rendering doesnot support hardware bitmaps
Below is my code. The crash is on the this line:  canvas.drawBitmap(bitmap1, 0F, 0F, null)
 private fun DrawRectTextAndBitmap()
    {

        val strOwnerName: String = "Owner: " + tvOwnerName.text.toString()
        val strCtcName:String = "Contact : " + tvCtcPersonName.text.toString()
        val strCtcMobileNo:String ="Mobile : " + tvCtcPersonMobile.text.toString()
        val strAddr1 : String ="Drug Allergy : " + tvAddr1.text.toString()
        val strAddr2: String = "Food Allergy : " + tvAddr2.text.toString()

          val bitmap1 = (imgResult.getDrawable() as BitmapDrawable).getBitmap()

          var h = bitmap1.height
          var w = bitmap1.width

          val newbitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)

          val canvas = Canvas(newbitmap)

          //-- draw background color

          canvas.drawColor(Color.GREEN)

          //-- draw bitmap onto Canvas:

          canvas.drawBitmap(bitmap1, 0F, 0F, null)

          //-- create paint-based color

          val paint = Paint()
          paint.isAntiAlias()
          paint.setColor(ContextCompat.getColor(applicationContext, R.color.royalblue))
          paint.alpha = 126

          val strDisplayAllText: String = strOwnerName

          val paintText = Paint(Paint.ANTI_ALIAS_FLAG)
          paintText.setTextSize(rectTextSize)
          paintText.setColor(ContextCompat.getColor(applicationContext, R.color.Lightgray))
          paintText.setStyle(Paint.Style.FILL)

           val color1 = Color.parseColor("#f5f5f5")
            paintText.setColor(color1)
            paintText.setStyle(Paint.Style.FILL)

          //-- Draw the Rectangle

          if (h > w ) {

              val rectangle = Rect(10, rectPortrait_StartPoint, rectPortrait_H, rectPortrait_W)

              canvas.drawRect(rectangle, paint)

          } else {

              val rectangle = Rect(10, rectLandscape_StartPoint, rectLandscape_H, rectLandscape_W)

              canvas.drawRect(rectangle, paint)
          }

          val rectText = Rect()
          paintText.getTextBounds(strOwnerName, 0, strDisplayAllText.length, rectText)

          if( h > w ) {

              canvas.drawText(strOwnerName, 20F, 830F, paintText)
              canvas.drawText(strCtcName, 20F, 890F, paintText)
              canvas.drawText(strCtcMobileNo, 20F, 950F, paintText)
              canvas.drawText(strAddr1, 20F, 1010F, paintText)
              canvas.drawText(strAddr2, 20F, 1110F, paintText)

              val density = Resources.getSystem().displayMetrics.density
              imgResult.layoutParams.height = 240 * density.toInt()
              imgResult.layoutParams.width = 180 * density.toInt()
              imgResult.requestLayout()

          }else{

              //--landscape

              canvas.drawText(strOwnerName, 20F, 560F, paintText)
              canvas.drawText(strCtcName, 20F, 620F, paintText)
              canvas.drawText(strCtcMobileNo, 20F, 680F, paintText)
              canvas.drawText(strAddr1, 20F, 740F, paintText)
              canvas.drawText(strAddr2, 20F, 870F, paintText)

              val density = Resources.getSystem().displayMetrics.density
              imgResult.layoutParams.width = 200 * density.toInt()
              imgResult.layoutParams.height = 200 * density.toInt()
              imgResult.requestLayout()
          }

          runOnUiThread {

              imgResult.setImageBitmap(newbitmap)
          }

      }

Update: I added the following
 1)  in manifest

I added :

 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:hardwareAccelerated="false"

 </application>

2 ) in code , I modified for the ImageView

      imgResult.setImageBitmap(newbitmap)
     imgResult.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

A: from Canvas class:
private void throwIfHwBitmapInSwMode(Bitmap bitmap) {
   if (!isHardwareAccelerated() && bitmap.getConfig() == Bitmap.Config.HARDWARE) {
      onHwBitmapInSwMode();
   }
}

therefore make bitmap with config software, or enable hardware acceleration

A: You should disable hardware acceleration by this tag android:hardwareAccelerated="false", it can be use in Application and Activity;
Or you can use this method for one particular View like
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);


text:
Q: xml2 installed but not found during compilation I'm trying to compile the lib https://github.com/bjz/gl-rs.
I'm getting an error when running make:
error: linking with `cc` failed: exit code: 1
(a long list of linker args follows)
note: /usr/bin/ld: cannot find -lxml2

If I'm reading this right, the linker cannot find the lib xml2. I made sure xml2 and libxml2 are installed (via sudo apt-get install) but that's not enough.
What to do?

A: In the Ubuntu packaging system, the libXXX packages often only contain the runtime libraries necessary for running applications that dynamically link the library.
In order to get the libraries and header files necessary for compiling and building, there is usually a separate libXXX-dev package (-dev indicating that the packages are for development). You can check what development packages are available for a particular library using the apt-cache search engine e.g.
apt-cache search devel | grep libxml2

In your case, you are probably missing the libxml2-dev package.


text:
Q: Can I check the Indy version installed? I need to use the latest Indy component library version.  Can I get the library version by some source code command or any other trick to make sure I'm using the correct lib.
I know I'm using the indy....160.bpl - this is what my Delphi XE2 says while moving the mouse over the component bar.  The latest INDY lib I take from Fulgan Indy

A: If your application already has an instance of an Indy component (which inherits TIdBaseComponent), you can get the version simply by
Version := SomeIndyComponent.Version;

in the current version, this function will return 10.5.9.0

A: How to get version of Indy by using an Indy component at runtime ?
As @Remy pointed out in his comment, you can get the Indy version from any Indy component by using the Version property. Here's a sample using TIdHTTP component:
procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage('Indy version: ' + IdHTTP1.Version);
end;

How to get version of Indy without an Indy component at runtime ?
You can get the whole version string in Indy's versioning format:
<major>.<minor>.<release>.<build>

from the gsIdVersion constant defined in the IdVers.inc file included in the IdGlobal.pas unit in a way like follows:
uses
  IdGlobal;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage('Indy version: ' + gsIdVersion);
end;

or if you have Indy revision at least since 25th October 2012 (4850), you can use the individual version information elements, whose are defined in the same include file as mentioned before e.g. this way:
uses
  IdGlobal;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage('Indy version: ' +
    IntToStr(gsIdVersionMajor) + '.' +
    IntToStr(gsIdVersionMinor) + '.' +
    IntToStr(gsIdVersionRelease) + '.' +
    IntToStr(gsIdVersionBuild)
  );
end;

How to get version of Indy at design time ?
To get Indy version at design time you can simply right click any of the Indy's components dropped on a form and open its About box through the About Internet Direct (Indy)... menu item.
Where are the version information defined ?
As I've mentioned before, it's in the IdVers.inc include file stored in the ..\Lib\System\ folder of the library and it might be the next option of how to get the Indy's version information.
Disclaimer
Some of what was mentioned here applies to the Indy's most recent version at this time, but I'm not sure if it applies also to all older versions (such as Indy 9 for instance).


text:
Q: Changing base::colnames into a generic function called colnames I am developing a package and I want to use colnames() to extract an attribute from a list.
#' @export
colnames <- function(x) {
  UseMethod("colnames")
}

#' @export
colnames.default <- function(x) {
   base::colnames(x)
 }

#' @export
colnames.newclass <- function(x) {
  some_sort_of_subsetting(x)
}

Is this legit? When I will attach the package it will mask base::colnames() but I use it as a default, with the only exception of my own class "newclass".
Also on the same note. I want to use zoo::index() generic as a name, What are your suggestions? To add zoo to Depends or to make a new generic function.
#' @export
index <- function(x, ...) {
   UseMethod("index")
}

And then do I have to make a reference to zoo in case the user loads zoo as well? Can I import just the generic function from zoo?


text:
Q: timevalue("23:50") This is just nuts.
I have a cell (in excel) in which I type "23:50" (without quotes). Next, with this cell selected, I go to the immediate window and type
msgbox activecell = timevalue("23:50")
..and it gives me "FALSE"!
I get TRUE for everything else, for eg with 23:49 or 23:51 (or any other time for that matter) in the cell and correspondingly in the code, but with 23:50 its breaking down for no reason.
This line is part of a bigger code, where this condition needs to be TRUE for the rest of it to execute. Using Excel 2007 on Win 7.

A: Test with this instead:
timevalue(activecell.text) = timevalue("23:50")

Likely your mismatch is due to the numeric equivalents not matching exactly:
      activecell.value = 0.99305555555555_5_

but
cdbl(timevalue("23:50"))=0.99305555555555_6_