Q:

How to enable NVIDIA?

Note: Even after I followed the explanation in another question (as my question was identified as a possible duplicate of it) nothing changed of what I am detailing below.

I know there are myriad questions and how-to's about installing and using NVIDIA graphics card on Ubuntu, but my case is a bit different (probably due to using Ubuntu 19.04).
My laptop has a GeForce GTX 1050 NVIDIA graphics card besides the "default" Intel graphics card. (I am using the laptop's own display and nothing is connected to the HDMI port.)
$ lspci -k | grep -A 2 -i "VGA"
00:02.0 VGA compatible controller: Intel Corporation UHD Graphics 630 (Mobile)
    Subsystem: Tongfang Hongkong Limited UHD Graphics 630 (Mobile)
    Kernel driver in use: i915
--
01:00.0 VGA compatible controller: NVIDIA Corporation GP107M [GeForce GTX 1050 Mobile] (rev a1)
    Subsystem: Tongfang Hongkong Limited GP107M [GeForce GTX 1050 Mobile]
    Kernel driver in use: nvidia

I already have installed the latest recommended NVIDIA driver (probably several weeks ago!):
$ sudo ubuntu-drivers devices
== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
modalias : pci:v000010DEd00001C8Dsv00001D05sd00001042bc03sc00i00
vendor   : NVIDIA Corporation
model    : GP107M [GeForce GTX 1050 Mobile]
driver   : nvidia-driver-390 - distro non-free
driver   : nvidia-driver-418 - distro non-free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

$ sudo apt-get install nvidia-driver-418
Reading package lists... Done
Building dependency tree
Reading state information... Done
nvidia-driver-418 is already the newest version (418.56-0ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

$ prime-select query
nvidia

However, system Settings | Details | About displays that the following graphics processor is active:
Intel® UHD Graphics 630 (Coffeelake 3x8 GT2)

I get the following output from nvidia-smi command:
$ nvidia-smi
Wed May 29 19:17:55 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 418.56       Driver Version: 418.56       CUDA Version: 10.1     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1050    Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   33C    P8    N/A /  N/A |      2MiB /  4040MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

The GPU seems idle.
And the nvidia-settings command just displays a simple window like this:

Considering all these, I believe that currently the Intel graphics card, and not the NVIDIA graphics card is active in my system.
Purging and reinstalling the NVIDIA driver does not help.
Certainly I am missing something. But what?

A:

June 3, 2019 Update
Nvidia needs a working Xorg installation to operate within. As your current Xorg Gnome desktop is broken you can try the Unity Desktop to get nVidia drivers working first.
sudo apt-get install unity-session
sudo apt-get install lightdm

And using TAB key select lightdm between "gdm3" and "lightdm" choices there, and press ENTER key to go.

I have a GTX 970M but I know this driver also works with the GTX 1060M which is one step above yours:
$ sudo ubuntu-drivers devices

== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
model    : GM204M [GeForce GTX 970M]
vendor   : NVIDIA Corporation
modalias : pci:v000010DEd000013D8sv00001028sd00000708bc03sc02i00
driver   : nvidia-384 - distro non-free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

$ dmesg | grep -i nvidia

[    1.760813] nvidia: loading out-of-tree module taints kernel.
[    1.760817] nvidia: module license 'NVIDIA' taints kernel.
[    1.763857] nvidia: module verification failed: signature and/or required key missing - tainting kernel
[    1.771538] nvidia-nvlink: Nvlink Core is being initialized, major device number 242
[    1.771720] nvidia 0000:01:00.0: enabling device (0006 -> 0007)
[    1.771858] NVRM: loading NVIDIA UNIX x86_64 Kernel Module  384.130  Wed Mar 21 03:37:26 PDT 2018 (using threaded interrupts)
[    1.778086] nvidia-modeset: Loading NVIDIA Kernel Mode Setting Driver for UNIX platforms  384.130  Wed Mar 21 02:59:49 PDT 2018
[    1.779773] [drm] [nvidia-drm] [GPU ID 0x00000100] Loading driver
[    1.779774] [drm] Initialized nvidia-drm 0.0.0 20160202 for 0000:01:00.0 on minor 1
[    4.866848] nvidia-uvm: Loaded the UVM driver in 8 mode, major device number 240
[    5.248695] input: HDA NVidia HDMI/DP,pcm=3 as /devices/pci0000:00/0000:00:01.0/0000:01:00.1/sound/card1/input9
[    8.877159] nvidia-modeset: Allocated GPU:0 (GPU-30fab9bc-fe6f-ec05-e8e6-c151a1a96121) @ PCI:0000:01:00.0

If you need sound turned on for your nVidia HDMI and most manufacturers these days have it powered off, then you need to use this:

Linux kernel module to toggle Nvidia HDMI audio device on/off on notebooks

Here is someone that has taken the prime-select code and patched it because it wouldn't switch from nvidia to intel. If his patch doesn't help you perhaps he can?

NVIDIA-PRIME: Cant switch to intel


Q:

Geläufige mehrwortige Begriffe mit Adjektiv aus dem Englischen (»Best Practices«, »Daily Soap«, »Open Source«)

Im Deutschen sind einige Begriffe aus dem Englischen geläufig, die aus mehreren Wörtern bestehen, wovon das erste ein Adjektiv ist. Beispiele:

Best Practices

Daily Soap

Open Source

Wie muss mit solchen Begriffen in deutschen Texten verfahren werden?

Müssen sie in Anführungszeichen (bzw. kursiv) gesetzt werden?

»Open Source« ist eine tolle Sache.
  Ich schaue mir gerne eine Daily Soap an.

Meines Wissens nach ist das erforderlich, wenn die Begriffe nicht geläufig sind, wenn der Begriff also als Fremdwort verwendet wird (dann wird der Begriff allerdings auch kleingeschrieben).
Müssen Bindestriche gesetzt werden?

Open-Source ist eine tolle Sache.
  Ich schaue mir gerne eine Daily-Soap an.

Meines Wissens nach ist eine Durchkopplung erforderlich, wenn der Begriff mit einem weiteren Wort verbunden wird: »Open-Source-Enzyklopädie«, »Daily-Soap-Fan«, »Best-Practices-Sammlung«.
Müssen sie zusammengeschrieben werden?

Opensource ist eine tolle Sache.
  Ich schaue mir gerne eine Dailysoap an.

Oder dürfen sie einfach so verwendet werden?

Open Source ist eine tolle Sache.
  Ich schaue mir gerne eine Daily Soap an.

A:

FAQ des Rechtschreibrats:

Wie schreibt man englische Wörter, die nicht im Wörterbuch stehen?
[…]
2. Verbindungen aus Adjektiv + Substantiv
Bei der Schreibung von Verbindungen dieser Art ist die Betonung ausschlaggebend: Liegt die Betonung wie in Hotline hauptsächlich auf dem ersten Bestandteil oder sind beide Bestandteile wie in Daily Soap in etwa gleich stark betont? Im ersten Fall greift das deutsche Betonungsmuster („Erstbetonung“), im zweiten das englische. Da die Betonung wesentlich für die Schreibung des Deutschen ist, folgt die Schreibung ihr auch hier. In den Fällen, in denen beide Betonungsmuster gebräuchlich sind, sind beide Schreibungen zugelassen wie z.B. in Blind Date/Blinddate, Slow Food/Slowfood.
[…]

Demnach kommen nur zwei Optionen in Frage, abhängig von der Betonung:

Zusammenschreibung (Blinddate)
Mit Leerzeichen (Blind Date)

Bei den drei Beispielen aus meiner Frage dürften die Wörter in etwa gleich stark betont werden, also wären diese Schreibweisen korrekt:

Wir diskutieren heute Best Practices.

Open Source ist eine tolle Sache.

Ich schaue mir gerne eine Daily Soap an.


Q:

Sort QGraphicsItems QList based on center point min to max

How can I sort a list of QGraphicsItems based on their boundingRect center point? I would like the list to be sorted from min Y value to max Y value.
thanks
QList<QGraphicsItem*> validItems;

foreach (QGraphicsItem* item, items) {
    if (!item) continue;
    if (item->type() == NexusBlockItem::Type) {
        int nodeCenterY = item->pos().y() + (item->boundingRect().height()/2.0);
    }
}

A:

Qt provides a nice function for this purpose: qSort()
bool itemLess(const QGraphicsItem* item1, const QGraphicsItem* item2)
{
    return item1->sceneBoundingRect().center().y() < item2->sceneBoundingRect().center.y();
}

qSort(validItems.begin(), validItems.end(), itemLess);

Note 1: You can use std::sort() instead of qSort().
Note 2: You can use a functor or lambda to compare the items instead of itemLess() function.
Note 3: Both qSort() and std::sort() use the quicksort algorithm.
EDIT
As vicrucann mentioned, the Qt documentation recommends to use a std::sort() instead of qSort().


Q:

Doubt In A simple integral using complex numbers

Suppose we have $\int_{0}^{\infty}{{e^{-sx}}\sin x} \,dx$
The integral of this is just the imaginary part of $\int_{0}^{\infty}{{e^{-sx}}{e^{ix}}} \,dx$
This can further be written as $\frac{e^{-x(s-i)}}{i-s}$ or $\frac{e^{x(i-s)}}{i-s}$ with the limits from 0 to infinity. In the first case when we substitute the upper limit as infinity we will get $0$ (as $e^{-x}$ will tend to $0$ as $x$ tends to $\infty$) but in the second case we will $\infty$ when we substitute the upper limit.
Can anyone please point out my misunderstanding in this situation?

A:

We always have $$\exp(-x(s-i))=\exp(x(i-s))$$
It value depends on the sign of $s$.
\begin{align}\lim_{x \to \infty} \exp(-x(s-i))&= \lim_{x \to \infty} \exp(ix)\exp(-sx)\\
&=\lim_{x\to \infty} (\cos x+ i \sin x) \exp(-sx)\end{align}
If $s$ is positive, then $\exp(-sx)$ tends to zero and since the norm of $\exp(ix)$ is bounded, we have the whole expression tends to zero.
When it is non-positive, try to take particular subsequence to show that it doesn't converge.


Q:

Repeat each row N times in Google Sheets

I have a column containing 3 rows. I want to be able to repeat those rows 5 times each.
Example
| Name |
|------|
| Dog  |
| Cat  |
| Ball |
|------|

Desired Output
| Output |
|--------|
| Dog    |
| Dog    |
| Dog    |
| Dog    |
| Dog    |
| Cat    |
| Cat    |
| Cat    |
| Cat    |
| Cat    |
| Ball   |
| Ball   |
| Ball   |
| Ball   |
| Ball   |
|--------|

Here's what I have tried:
=TRANSPOSE(split(rept(join(";",A:A)&";",5),";"))

My attempt produces:
| Output |
|--------|
| Dog    |
| Cat    |
| Ball   |
| Dog    |
| Cat    |
| Ball   |
| Dog    |
| Cat    |
| Ball   |
| Dog    |
| Cat    |
| Ball   |
| Dog    |
| Cat    |
| Ball   |
|--------|

A:

=ARRAYFORMULA(TRIM(TRANSPOSE(SPLIT(QUERY(
 REPT(A1:A3&"♠", 5), ,999^99), "♠"))))

=SORT(TRIM(TRANSPOSE(SPLIT(QUERY(ARRAYFORMULA(
 REPT(A1:A3&"♠", 5)), ,999^99), "♠"))), 1, 0)


Q:

Slow MySQL Query - how can it be speed up?

This is edited - I have tried speeding this up but still very slow - can anyone offer anymore help please?
SELECT DISTINCT d.`group_ID`,
  CONCAT(u.fname, ' ', u.lname) AS uname,
  u.corp_id,
  c.`corp_name`,
  u.`user_username`,
  u.location,
  (
    SELECT email
    FROM users
    WHERE role = 'Level 4'
      AND location = d.location
      AND email NOT LIKE '%manager.%'
    LIMIT 1
  ) AS trainer,
  u.`email`,
  GROUP_CONCAT(
    DISTINCT d.title
    ORDER BY d.title SEPARATOR ', '
  ) AS docs
FROM regulatory d
  LEFT JOIN users u
    ON u.user_id = d.`group_ID`
    AND u.`role` = 'Level 6'
  LEFT JOIN corporations c
    ON c.`corp_id` = u.`corp_id`
WHERE d.`spare1` <> 'green.gif'
  AND u.`officialjobtitle` <> 'none'
  AND d.`date_updated` < NOW()
  AND (u.`corp_id` IN (1))
GROUP BY d.`group_ID`
ORDER BY corp_id,
  u.`location`,
  uname ;

A:

You negate the left join from regulatory to users in the where
clause, so use an INNER JOIN for those two tables
use INNER JOIN on corporations if this is possible (I just don't know if it is or not)
remove DISTINCT. You are already performing a GROUP BY and if that is done correctly distinct will be completely redundant (as it doesn't do anything that GROUP BY cannot do)
I would try replacing the correlated subquery for trainer with a "derived table" that is already grouped so you don't multiply the rows
when using GROUP BY in MySQL never rely on the "extension". Always specify all the fields needed to produce unique rows (like you would in almost every other SQL compliant rdbms)

Make sure you have indexes on all fields involved in the joins and if possible those used in the where clause too.
Inspect the explain plan.
Suggested edits:
SELECT
      d.`group_ID`
    , CONCAT ( u.fname , ' ' , u.lname ) AS uname
    , u.corp_id
    , c.`corp_name`
    , u.`user_username`
    , u.location
    , MAX(l4.trainer) as trainer
    , u.`email`
    , GROUP_CONCAT(DISTINCT d.title ORDER BY d.title SEPARATOR ', ') AS docs
FROM regulatory d
INNER JOIN users u ON d.`group_ID` = u.user_id
                   AND u.`role` = 'Level 6'
LEFT JOIN corporations c ON u.`corp_id` = c.`corp_id`
LEFT JOIN (
        SELECT location, MAX(email) AS trainer
        FROM users
        WHERE ROLE = 'Level 4'
            AND email NOT LIKE '%manager.%'
        GROUP BY location
        ) l4 ON d.location = l4.location
WHERE d.`spare1` <> 'green.gif'
    AND u.`officialjobtitle` <> 'none'
    AND d.`date_updated` < NOW()
    AND u.`corp_id` IN (1)
GROUP BY
      d.`group_ID`
    , u.fname
    , u.lname
    , u.corp_id
    , c.`corp_name`
    , u.`user_username`
    , u.location
    , u.`email`
ORDER BY
      corp_id
    , u.`location`
    , uname
;


Q:

PHP SQL concatenation

I have a SQL query in which I want to select records that where paid between two dates.
Here's how I build my query:
$qry = array();
    $qry[] = "SELECT DISTINCT 2 AS Record_Type, wp_woocommerce_order_items.order_id As Order_Id, First_Name;
    $qry[] = "FROM  wp_woocommerce_order_items";
    $qry[] = "LEFT JOIN (SELECT meta_value As First_Name, post_id FROM wp_postmeta WHERE meta_key = '_shipping_first_name') AS a";
    $qry[] = "ON wp_woocommerce_order_items.order_id = a.post_id";
    $qry[] = "RIGHT JOIN (SELECT post_id FROM wp_postmeta WHERE meta_key = '_paid_date' AND meta_value > " .$_POST['debut'] . " AND meta_value < " . $_POST['fin'] . ") AS m";
    $qry[] = "ON wp_woocommerce_order_items.order_id = m.post_id";
    $qry[] = "WHERE wp_woocommerce_order_items.order_item_type = 'line_item'";
    $qry[] = "ORDER BY wp_woocommerce_order_items.order_id";

The problem is with my POST variables in the RIGHT JOIN line. If I hardcode a date instead of $_POST['debut'] and $_POST['fin'] I get the result I'm looking for.
So I guess my problem is with concatenation from my PHP POST variables.
Anyone can help me?

A:

You need to quote your values, e.g. instead of
$qry[] = "RIGHT JOIN (SELECT post_id FROM wp_postmeta WHERE meta_key = '_paid_date' AND meta_value > " .$_POST['debut'] . " AND meta_value < " . $_POST['fin'] . ") AS m";

use
$qry[] = "RIGHT JOIN (SELECT post_id FROM wp_postmeta WHERE meta_key = '_paid_date' AND meta_value > '" .$_POST['debut'] . "' AND meta_value < '" . $_POST['fin'] . "') AS m";

And please look for mysql_real_escape_string or other ways to avoid SQL injection attacks.


Q:

if a public key cannot decrypt the cipher text, then how can a private key?

I understand the "public" part of public key cryptography. Not the "private" part.
For example, let's say our public key is %7 (modulo 7). And the message to be encrypted is 22.
And we know that 22 % 7 = 1
Here, 1 is the encrypted message.
The reason why public keys work is that despite knowing the public key (%7) and the encrypted message (1), I cannot confirm that the original message was 22.
So, this begs the question, how does the private key figure out that the original message was 22?

A:

What you presented is not an encryption scheme, you just took a number and modded it by 7. This can not be an encryption scheme because there is more than one "message" which will produce the same "cipher text", for example:

the message 22 produces the cipher text 22 % 7 = 1
the message 29 produces the same cipher text 29 % 7 = 1
the message 36 produces the same cipher text 36 % 7 = 1
. . .

So your question:

how does the private key figure out that the original message was 22?

It doesn't because for the cipher text "1", there are an infinite number of possible original messages.

What you have looks kinda similar to RSA, so I'm guessing that you read something about RSA and are trying to work through the math. There's a nice easy sample calculation of RSA here that you could try working through.
For a more detailed description of the math of RSA, you can go to the wikipedia page for RSA.

Edit: in comments you said:

if a modulo (public key) produces a result that cannot be reverse engineered, then how is the private key able to do it?

Alright, let's walk through that example of RSA.

You choose two primes, let's take p = 3, and q = 11
You compute n as n = p * q = 3 * 11 = 33
You compute φ(n) = (p-1)*(q-1) = 2 * 10 = 20
You choose a public exponent e such that 1 < e < φ(n), and that e and n are coprime. e = 7 will do.
You choose a private exponent d such that (d * e) % φ(n) = 1. d = 3 will work since (3 * 7) % 20 = (21) % 20 = 1

Now your public key is (7, 33), (e, n), and your private key is (3, 33), (d, n).
Ok, now let's say that you want to encrypt the plaintext message "22", as in your question. The encryption calculation is: m^e % n = c, where m is the original message and c is the ciphertext, so 22^7 % 33 = 22 (heh, that's a coincidence), so the encrypted message is "22".
Now, the person who has the private exponent d can decrypt the ciphertext by calculating c^d % n = m, is our example 22^3 % 33 = 22.


Q:

Spring Boot - MongoDB - Inheritance

I'm running into something odd with inheritance and mongodbrepositories.
I have the following:
`
@Document
public class Base {
    public String fieldA;
}

public class Derived extends Base {
    public String fieldB;
}

public interface DerivedRepository extends MongoRepository<Base, String> {
    List<Derived> findByFieldA(String fieldA);
}

`
When inserting i get

Inserting DBObject containing fields: [_class, _id, fieldA, fieldB ]
  in collection: base

When i do findByFieldA('some value') on the repository i get the following:

find using query: { "fieldA" : "some value" } fields: null for class:
  class Derived in collection: derived

Any idea what is going on here? And how can I fix this, either by saving it to the proper derived collection or by querying from the base collection.
Regards,

A:

First, I would make Derived class as document since the parent is going to be shared among many implementations.
public class Base {
    public String fieldA;
}

@Document
public class Derived extends Base {
    public String fieldB;

    @Override
    public String toString() {
        return "{fieldA: " + getFieldA() + ", fieldB: " + fieldB + "}";
    }
}

Second, change the repository specification with the type of document (class marked as @Document) as:
public interface DerivedRepository extends MongoRepository<Derived, String> {
    List<Derived> findByFieldA(String fieldA);
    List<Derived> findByFieldB(String fieldB);
}

I added extra method findByFieldB(String fieldB) to explain more.
With these changes, you should be able to query either with fieldA or fieldB as below:
public class SpringBootMongoApplication {
    @Autowired
    private DerivedRepository derivedRepository;

    public void testMethod() throws Exception {
        Derived derived1 = new Derived();
        derived1.setFieldB("fieldB1");
        derived1.setFieldA("fieldA1");

        Derived derived2 = new Derived();
        derived2.setFieldB("fieldB2");
        derived2.setFieldA("fieldA2");
        this.derivedRepository.save(Arrays.asList(derived1, derived2));

        List<Derived> deriveds = this.derivedRepository.findByFieldA("fieldA1");
        System.out.println(deriveds);

        List<Derived> deriveds1 = this.derivedRepository.findByFieldB("fieldB2");
        System.out.println(deriveds1);
    }
}

The output should be:
[{fieldA: fieldA1, fieldB: fieldB1}]
[{fieldA: fieldA2, fieldB: fieldB2}]

You can also verify the object persisted and their types with mongo query as below:

I have created an Spring Boot sample app which you can find in Github.


Q:

How to store a Euler graph struct?

I'm working around the Euler Path issue and found a problem:How to define or store a Euler graph struct?
An usual way is using an "Adjoint Matrix",C[i][j] is defined to store the edge between i-j.It's concise and effective！ But this kind of matrix is limited by the situation that the edge between 2 nodes is unique (figure 1).
class EulerPath
{
   int[][] c;//adjoint matrix,c[i][j] means the edge between i and j
}

What if there are several edges (figure 2)?My solution might be using customized class ,like "Graph","Node","Edge" to store a graph,but dividing the graph into some discrete structs ,which means we have to take more class details into consideration,may hurt the efficiency and concision. So I'm very eager to hear your advice!Thanks a lot!
class EulerPath
{
   class Graph
   {
      Node[] Nodes;
      Edge[] Edges;
   }
   class Node{...}
   class Edge{...}
}

A:

You can use an adjacency matrix to store graphs with multi-edges. You just let the value of c[i][j] be the number of times that vertex i is adjacent to vertex j. In your first case, it's 1, in your second case, it's 3. See also Wikipedia -- adjacency matrices aren't defined as being composed of only 1 and 0, that's just the special case of an adjacency matrix for a simple graph.
EDIT: You can represent your second graph in an adjacency matrix like this:
  1 2 3 4
1 0 3 1 1
2 3 0 1 1
3 1 1 0 0
4 1 1 0 0


Q:

Accessing the "statuses/sample" Twitter API in Tweepy

I've been using the Tweepy streaming library to get tweets. It doesn't download very many tweets very quickly. I tried the cURL command for GET statuses/sample, and it gives me a lot more. But I don't see a method to access this anywhere in the Tweepy documentation.
Is there any way to do this with Tweepy? I'd rather not have to deal with the OAuth and everything myself.

A:

Aha. It's not in the documentation, but in the source, I found that I can use Stream.sample instead of Stream.filter like in the docs.


Q:

Not able to open the Jmx file in Jmeter

Error 1Please click here to check the error
Error 2Please click here to check the error
While open the .jmx file in Jmeter we are facing the above issue in Jmeter. Any can able to find the solution for this error?
we are try to open the jmx in 2.12,2.13,3.0 and 3.1 version but we are facing the above issue. But same jmx we can able to open in different system

A:

Basically you have some missing plugins (i.e libraries).
So please double check that you have the same libraries on the different systems
you can check the libraries by going on to the folder
apache-jmeter-3.1\apache-jmeter-3.1\lib
Replace the missing libraries by copy paste then restart jmeter


Q:

Feasibility of nested voxels

Out of curiosity, does anyone know how feasible it would be to have a voxel engine that allowed for voxels within other voxels? For example, you would have the usual chunks filled with voxels, but instead of stopping there each voxel could become a chunk of it's own to store more, smaller voxels. The first use case that comes to mind would be for showing damage to voxels, but there could be others, such as smoother terrain. Thoughts?

A:

It's absolutely feasible. Go and look up octrees and KD-trees. These are just two ways of nesting voxels. These were already used in the 1990s in certain voxel applications. You could also use uniform grids and thus restrict the recursion depth to 1 or 2 levels, which may lead to better cache performance with simpler code. Good luck!


Q:

How do I Change minimum Zoom scale on orientation change?

I am trying to set up an app very similar to the Photos app on the iPhone.  The problem I am running into is that I cannot figure out a good way to set the minimum zoom scale and force the current zoom scale back to the minimum if it is currently smaller than the minimum.
Here is how I am currently setting up my scrollview...
- (void)viewDidLoad{

NSData * imageData = [[[NSData alloc] autorelease] initWithContentsOfURL: [NSURL URLWithString: imageURL]];
UIImage *babe = [UIImage imageWithData:imageData];
babeView = [[UIImageView alloc]
            initWithImage:babe];
[self.view addSubview:babeView];
UIBabeScrollView* myScrollview = (UIBabeScrollView*)self.view;
myScrollview.frame = [UIScreen mainScreen].applicationFrame;
[myScrollview setContentSize:[babe size]];
[myScrollview setMaximumZoomScale:2.0];
// Work out a nice minimum zoom for the image - if it's smaller than the ScrollView then 1.0x zoom otherwise a scaled down zoom so it fits in the ScrollView entirely when zoomed out
CGSize imageSize = babeView.image.size;
CGSize scrollSize = myScrollview.frame.size;
CGFloat widthRatio = scrollSize.width / imageSize.width;
CGFloat heightRatio = scrollSize.height / imageSize.height;
CGFloat minimumZoom = MIN(1.0, (widthRatio > heightRatio) ? heightRatio : widthRatio);

[myScrollview setMinimumZoomScale:minimumZoom];
[myScrollview setZoomScale:minimumZoom];

My UIBabeScrollView is subclassed to overload it's layoutSubviews like so...
- (void)layoutSubviews {
[super layoutSubviews];

// center the image as it becomes smaller than the size of the screen
CGSize boundsSize = self.bounds.size;
CGRect frameToCenter = ((UIImageView*)[self.subviews objectAtIndex:0]).frame;

// center horizontally
if (frameToCenter.size.width < boundsSize.width)
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
    frameToCenter.origin.x = 0;

// center vertically
if (frameToCenter.size.height < boundsSize.height)
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
    frameToCenter.origin.y = 0;

((UIImageView*)[self.subviews objectAtIndex:0]).frame = frameToCenter;

}
The affect I am going for is that the image is always centered, and cannot be zoomed out more than the width or height of the image.
Right now this works fine in portrait mode, but when it is switched to landscape, the zoom scales are incorrect.
Any help would be appreciated, as I am still a fledgling iphone app developer.

A:

In your view controller, implement -willRotateToInterfaceOrientation:duration:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  if (toInterfaceOrientation == UIDeviceOrientationLandscapeLeft ||
      toInterfaceOrientation == UIDeviceOrientationLandscapeRight) {
    [myScrollview setMinimumZoomScale:yourLandscapeMinimumZoomValue];
    [myScrollview setZoomScale:yourLandscapeMinimumZoomValue];
  } else {
    [myScrollview setMinimumZoomScale:yourPortraitMinimumZoomValue];
    [myScrollview setZoomScale:yourPortraitMinimumZoomValue];
  }
}


Q:

Why isn't my .htaccess 301 redirect rule working?

I use URL rewriting on my redesigned website to give my pages tidier URLs.
RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^$ index.php [L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^.+/$ %{REQUEST_URI}index.php [L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+\.php|(.+/)?index)$ - [R=404,L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L]

This .htaccess file allows /filename to actually point to /filename.php. It all works fine.
However, I have now realised that I should set up 301 permanent redirects, so that the pages of the old website (before the redesign) can redirect to pages on the new site (for SEO and linking reasons). The pages have been reorganised, so multiple old pages will redirect to new pages, for example.
The old website did not use URL rewriting. Therefore, I want to create permanent redirects such as /about-page.php to /about, doing them manually with one rule per old page.
I have tried several things, such as...
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^about-page.php$ about [R=301,L]

...or...
Redirect 301 /about-page.php /about

...but it always ends up either not working at all (giving me a 404 error when I attempt to access /old-filename.php, or breaks everything with internal server errors. It seems to work fine if I use Redirect 301 /about-page.html /about instead, but unfortunately the old URLs used .php extensions, not .html extensions.
I believe the problem is related to one of the other rules, which redirect requests for /xyz to /xyz.php, possibly creating some endless loop. But I can't figure out how to fix it.
Any advice? Thank you very much.

Edit: Final, working .htaccess file:
DirectoryIndex index.php #

RewriteEngine On

# -- Use a permanent redirect to point the old page to the new page.
# -- The RewriteCond is needed, or a redirect loop happens in certain cases.
# -- The full URL seems to be needed, or it redirects incorrectly.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^about-page.php$ http://www.mywebsite.com/about [R=301,L]

# -- Redirect most other .php files to a 404 error, to avoid duplicate content.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+\.php|(.+/)?index)$ - [R=404,L]

# -- Redirect requests without an extension, but for a valid file, to that file.
# -- I'm not sure what the RewriteCond lines are for, but they both seem necessary.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L]

A:

DirectoryIndex index.php # -- this sets index.php to be default file for a folder

RewriteEngine On

# -- RewriteRule ^(.+\.php|(.+/)?index)$ - [R=404,L]
# -- dude this above line redirects all php files to 404 error
# -- so delete this, its a problem not solution

RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L]

RewriteRule ^about-page.php$ /about [R=301,L]

This should work, comment if problem occurs


Q:

Using onclick with javascript function, call js var in parameters

Hey guys a bit stuck here. Ill first start with showing you the code.

Thats my javascript and i use a href with onlick which is below;
LinkName

I am trying for the third parameter of the function InfoBoxClick() to be the var named Stanley mentioned in the javascript, but i cant seem to do it, anyone know what i need to do???

A:

You will need to reference Stanley as a variable in the onclick:
InfoBoxClick('StanleyInfo','block',Stanley);

JSFiddle
Just a friendly comment on style, variables should be lowercase, classes and constants should be CapitalCase and UPPERCASE respectively. It's only a convention, but will help other javascript developers understand your code.


Q:

How to extract one line from each of ~1500 identically formatted txt files and save values to csv or xls?

I'm trying to extract one line of text from each of ~1500 identically formatted txt files, then save all the values in these lines--along with a corresponding date (the txt file name)--to a csv file.
The lines in said txt files are thus formatted (there are rows of data above and below):
DAILY AVG:       14.64          9.49          9.46          0.16       243.71

I am hoping to ultimately generate an xls file that looks like this:
Date      AVG1   AVG2  AVG3  AVG4  AVG5
12-13-06  14.64  9.49  9.46  0.16  243.71

I have considered using grep or awk, but frankly have no idea where to start. Is a command-line batch procedure the best line of attack? The desired end result is to have all of these daily averages, along with their corresponding dates, imported to an excel spreadsheet. The import txt option in excel would work on a file-by-file basis, but the problem here is the time it would take to manually import 1500 individual files from txt into xls files would be unfeasible unless I had an army of people.
Any insight or direction would be greatly appreciated.

A:

Assumptions:

All text files are located in the same folder
The text files are tab delimited

Use this Excel VBA code:
Sub tgr()

    Dim oShell As Object
    Dim oFSO As Object
    Dim arrData(1 To 65000) As String
    Dim strFolderPath As String
    Dim strFileName As String
    Dim strText As String
    Dim DataIndex As Long
    Dim lAvgLoc As Long

    Set oShell = CreateObject("Shell.Application")
    On Error Resume Next
    strFolderPath = oShell.BrowseForFolder(0, "Select a Folder", 0).Self.Path & Application.PathSeparator
    Set oShell = Nothing
    On Error GoTo 0
    If Len(strFolderPath) = 0 Then Exit Sub 'Pressed cancel

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    strFileName = Dir(strFolderPath & "*.txt*")
    Do While Len(strFileName) > 0
        strText = oFSO.OpenTextFile(strFolderPath & strFileName).ReadAll
        lAvgLoc = InStr(1, strText, "Daily Avg", vbTextCompare)
        If lAvgLoc > 0 Then
            strText = Mid(strText, lAvgLoc)
            strText = Trim(Mid(Replace(strText, vbCrLf, String(255, " ")), Evaluate("MIN(FIND({1,2,3,4,5,6,7,8,9,0},""" & strText & """&1234567890))"), 240))
            DataIndex = DataIndex + 1
            arrData(DataIndex) = DateValue(Replace(strFileName, ".txt", vbNullString)) & vbTab & strText
        End If
        strFileName = Dir
    Loop

    If DataIndex > 0 Then
        With Sheets.Add
            .Range("A1:F1").Value = Array("DATE", "AVG1", "AVG2", "AVG3", "AVG4", "AVG5")
            With .Range("A2").Resize(DataIndex)
                .Value = Application.Transpose(arrData)
                .TextToColumns .Cells, xlDelimited, xlTextQualifierDoubleQuote, Tab:=True
                .NumberFormat = "mm-dd-yy"
            End With
            Application.DisplayAlerts = False
            .SaveAs strFolderPath & "Daily Averages.csv", xlCSV
            Application.DisplayAlerts = True
        End With
    End If

    Set oFSO = Nothing
    Erase arrData

End Sub

How to use a macro:

Make a copy of the workbook the macro will be run on

Always run new code on a workbook copy, just in case the code doesn't run smoothly
This is especially true of any code that deletes anything

In the copied workbook, press ALT+F11 to open the Visual Basic Editor
Insert | Module Copy the provided code and paste into the module
Close the Visual Basic Editor
In Excel, press ALT+F8 to bring up the list of available macros to run
Double-click the desired macro (I named this one tgr)


Q:

Did Pocahontas quote Greek philosophy?

In the Disney movie Pocahontas, the titular character sings about the river in Just around the River Bend:

[Pocahontas] What I love most about rivers is: You can't step in the
  same river twice The water's always changing, always flowing But
  people, I guess, can't live like that We all must pay a price To be
  safe, we lose our chance of ever knowing

Was this an intentional quotation from the works of the Greek philosopher Heraclitus, or was this merely a coincidence on the part of the Disney songwriters, perhaps sourced from Native American philosophy?

"Everything changes and nothing remains still ... and ... you cannot
  step twice into the same stream"

A:

Disney does have a tendency to use philosophical quotes quite often.  My answer would be yes (more than likely Heraclitus rather than Native American philosophy) to your question.
This answer is based upon the use of other philosophical quotes in Disney films.
Here are just a few examples, including another from Pocahontas:

The only thing I know is that I know nothing.

Quoted by John Smith in Pocahontas
Quote origin: Socrates

The unexamined life is not worth living.

Quoted by Ursula in The Little Mermaid
Quote origin: Socrates

You can discover more about a person in an hour of play than in a year
  of conversation.

Quoted by Zazu in the Lion King
Quote origin: Plato


Q:

Multithreading result into slower

Basically I havn't done multi-threaded programming earlier. Conceptually I am aware of it.
So started with some what coding with random number generation. Code is working but it produce slower result than single thread program. So wanted to know for loopholes in my code and how to improve performance.
so if I tr to generate 1-1500 numbers randomly, using single thread and 10 threads (or 5 threads). single thread execute faster. thread switching or locking seems to be taking time. so how to handle it?
pthread_mutex_t   map_lock;
std::set<int> numSet;
int randcount=0;

static void *thread_fun (void *arg)
{
    int randNum= *(int *)arg;
    int result;
    std::set<int> findItr;

        while (randcount !=  randNum -1 ) {
        result = rand ()%randNum;

        if (result == 0) continue;
             pthread_mutex_lock (&map_lock);
             const bool is_in = (numSet.find (result) != numSet.end ());
             if  (!is_in)
             {
                numSet.insert (result);
                printf (" %d\t", result);
                randcount++;
             }

             pthread_mutex_unlock (&map_lock);
        }

}

A:

Since the majority of your code blocks all parallel threads (because is between a pthread_mutex_lock (&map_lock); and a pthread_mutex_unlock (&map_lock); block), your code works like it was running sequentially only with the overhead of parallelisation.
Tip: try to only collect the results in your thread then pass them back to the main thread which will display them. Also if you don't access your set parallely but pass back partial lists from each thread you don't have to deal with concurrency slowing down your code.


Q:

Daily returns to monthly basic question

I am currently a little bit puzzled. I am trying to compute the monthly returns from a set of data.
30-Sep-18   175.9790658  Performance
29-Sep-18   175.9790658 0.000%
28-Sep-18   175.9790658 0.000%
27-Sep-18   174.9712013 0.576%
26-Sep-18   175.4530194 -0.275%
25-Sep-18   173.5249863 1.111%
24-Sep-18   173.6253172 -0.058%
23-Sep-18   175.9311682 -1.311%
22-Sep-18   175.9311682 0.000%
21-Sep-18   175.9311682 0.000%
20-Sep-18   171.6433724 2.498%
19-Sep-18   170.5624874 0.634%
18-Sep-18   167.1542002 2.039%
17-Sep-18   164.9153843 1.358%
16-Sep-18   168.1403232 -1.918%
15-Sep-18   168.1403232 0.000%
14-Sep-18   168.1403232 0.000%
13-Sep-18   167.0250094 0.668%
12-Sep-18   162.2830264 2.922%
11-Sep-18   163.2663355 -0.602%
10-Sep-18   163.7415407 -0.290%
09-Sep-18   166.8650865 -1.872%
08-Sep-18   166.8650865 0.000%
07-Sep-18   166.8650865 0.000%
06-Sep-18   165.9631283 0.543%
05-Sep-18   168.6782507 -1.610%
04-Sep-18   172.9814277 -2.488%
03-Sep-18   171.6316528 0.786%
02-Sep-18   172.3265548 -0.403%
01-Sep-18   172.3265548 0.000%
31-Aug-18   172.3265548 0.000%

For calculating the monthly performance (X2/X1)-1 has been used giving us a performance of 2.12% but the sum  of individual daily returns is 2.31%
I don't see where discrepancy could come from is it because of the compounding?
Are there perhaps any papers on this subject to read up on since google was to no avail.
Thanks for the help advance and kind regards!

A:

it's the difference between $\sum_{i=1}^n \frac{X_i}{X_{i-1}} -1$ and $\frac{X_n}{X_0}-1$ and has nothing to do with your data integrity


Q:

What are the pro's and con's of a MIDI interface compared to MIDI to USB cable?

Is there a reason why one would choose a MIDI interface instead of a simple MIDI to USB cable?
There's a tenfold price difference between the two and I don't know in what regard the interface would perform better compared to the cable.
My intended usage for the cable or interface is to connect a MIDI keyboard to the computer such that musical notation software can read the played notes.

A:

The cable includes an in-line MIDI adapter.  (MIDI and USB are not compatible signals.)  M-Audio is a respected manufacturer while the other one is a no brand adapter.  It might not work as well or might not support as many channels, but at $5, it's hard to go wrong giving it a try and the reviews seem to indicate it will work for your purposes.
If I had to take a guess, the cable may be doing more in software where the M-Audio is more likely to have a dedicated MIDI processing chip in the unit.  This doesn't practically mean much for most use cases though since computers are plenty powerful now as long as the driver isn't buggy.

A:

As AJ Henderson and Warrior Bob mentioned, those cables are also MIDI interfaces.
I have several of the cable-style MIDI interfaces, as well as an old eMagic AMT8 and a MOTU 828 MK2. A few of my synths with USB interfaces function as USB-MIDI interfaces, but I rarely use them for that purpose. I also have the Elektron TM-1 interface for my MachineDrum.
For typical MIDI music stuff, the cheap cable-style interfaces are perfectly fine. They generally transmit and receive MIDI notes, and can handle a bit of CC data too. They generally fail when you try to do complex SYSEX tasks, like firmware updates. Even my "EMU" branded X-MIDI failed, so don't think that a nice brand name on a cable-style interface will help. They probably all come out of the same factory in Shenzhen. Just buy the cheapest one you can find.
My MOTU is my go-to interface for firmware updates, I've never had trouble with it. I suspect that the AMT8 would be fine too, but I only plug that in when I need to work with a lot of MIDI devices at the same time, which is rare.
I've only ever used the TM-1 to do a firmware update on my MachineDrum. I thought that since the TM-1 is designed for high-speed sample-over-MIDI transfers, it would make for a quick update. Not at all - the update actually took hours. This is probably wise on Elektron's part - you don't want to add any risk to a firmware update procedure. The process probably runs at a low MIDI bitrate and includes a lot of error correction codes.
For your intended use, the cable-style interface should be just fine. If you decide that you need more ports in the future, look at used 4x4 and 8x8 interfaces. As long as they can connect to your computer and drivers are available, an old interface will be just as good as a new one.


Q:

how to make an api call when the form is submitted ? and show message based on the response

i want to send the form data to an url where i can access the form data and send sms using twilio. I know how to configure twilio and send sms using it.
apex class:
public class SMS {
    public Message__c message { get; set; }

    public sms() {
        message = new Message__c();
    }

    public PageReference save() {
        System.debug(System.currentPageReference().getParameters().get('mobile'));
        insert message;
        return null;
    }

}

visual force page:
<apex:page controller="sms">
    <apex:pageBlock title="Sent SMS">
        <apex:pageBlockSection title="List">
            <apex:form>

                <apex:inputField value="{!Message.Mobile__c}" id="mobile" />

                <apex:inputField value="{!Message.Text_Message__c}" id="sms_Text" />

                <apex:commandButton action="{!save}" value="Save"/>
            </apex:form>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

I want to access the form data in apex class and send it into an API call .. How to achieve it ?

A:

For Twilio you don't have to call the API directly. Twilio provides a Helper library to send the SMS. The detailed documentation is available here.
In summary, you have to install their unmanaged package as mentioned here. And then using the helper classes you can send the SMS.
Please note you need the ACCOUNT_SID and AUTH_TOKEN as mentioned here from the Twilio account, and the SMS charges will be billed to this account.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';
String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

List<TwilioNameValuePair> properties = new List<TwilioNameValuePair>();
properties.add(new TwilioNameValuePair('To','+13216851234'));
    properties.add(new TwilioNameValuePair('From','+15555555555'));
    properties.add(new TwilioNameValuePair('MediaUrl','https://www.twilio.com/packages/company/img/logos_downloadable_round.png'));

TwilioMessage message = client.getAccount().getMessages().create(properties);


Q:

Eclipse won't switch workspace

Whenever I switch workspace on eclipse, I get the error:
An internal error occurred during: "Initializing Java Tooling".
Duplicate field name&signature in class file org/eclipse/jdt/internal/compiler/ast/ASTNode
If I restart Eclipse, it then loads the new workspace correctly. Any ideas  how I go about fixing this?
I'm using  Eclipse Kepler on Windows 7

A:

Yup, whoops, lombok bug. Sorry. It's been fixed; the next lombok version (looks like that'll be 1.14) will no longer have this issue. Until then, the edge release can be used if this is really cramping your workspace-switchin' style :)
http://projectlombok.org/download-edge.html


Q:

POST request in Spring MVC not work after migration from 3.2 to 4.1

I send POST request
$.ajax({
            type: "POST",
            url: "/common/ajax/advert/",
            data: data,
            dataType: "json",
            contentType: "application/json",
            success: function(r){}
});

to controller
@Controller
@RequestMapping(value = "/common/ajax/advert")
public class Controller {

    @RequestMapping(value="/", method=RequestMethod.POST)
    @ResponseBody
    public  Map<String,Object> adsSearch(@RequestBody Map<String,Object> data){

        Map<String,Object> result = new HashMap<String,Object>();
        List<Advert> ads =  advSrv.getAds(data);

        result.put("obj", ads);
        return result;
}

and return 404 error, but in spring 3.2 this work fine.
Controllers with RequestMethod.GET work correct in old and new version.
Please help me to fix it.
UPD.1 I tried to create a @RestController class (Spring 4.1) with RequestMethod.POST - and it did not work too.
UPD.2 In log Spring mapped this methods properly, but post request not handled (unlike get requests, they works fine).

A:

Finaly I found a problem - it was a Spring Security after upgrading to 4.0, where csrf protection enabled by default:
DEBUG: org.springframework.security.web.csrf.CsrfFilter - Invalid CSRF token found for post-request

I add support csrf protection and all work properly.


Q:

ajax post with laravel 5.6

I can't figure out how to get this ajax request to post.
     <button class="btn btn-sm btn-primary" id="ajaxSubmit">Submit</button>

      <textarea rows="4" class="form-control resize_vertical" id="application_notes" name="application_notes" placeholder="Notes">{{$application->notes}}</textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  var url = "/instructor-notes-save/{{$application->id}}"
      $(document).ready(function(){
         $('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
            $.ajax({

                  url: url,
                  method: 'post',
                  data: {
                     application_notes: jQuery('#application_notes').val(),
                  },
                  success: function(response){
                     console.log(response);
                  }});
               });
            });
</script>

My controller is this:
public function saveNotes(Request $request, $id)
    {
      $application = Application::findOrFail($id);
      $application->notes = $request->application_notes;
      $application->save();
      return response()->json(['success'=>'Data is successfully added']);
    }

And for what it's worth, here is my route:
Route::post('/instructor-notes-save/{id}', 'InstructorsController@saveNotes')->name('instructor.save.note');

What am i missing to get this ajax request to work? In my console log, i get a 419 unknown status error.

A:

Kindly check that the meta tag _token is present in your layout file inside the <head> tag.
Also please make sure that the AJAX url is present in your routes file.


Q:

Calculate combinations of positioning alphabet in N available positions in order

I have a sorted list of items (e.g. the alphabet). How can I calculate the number of combinations that these items can be placed in a set of N possible positions (where N is more than the items in the first list), while keeping the items in order, but potentially having empty positions.
E.g. A, B could be placed in 3 slots as follows:
A, B, empty;
A, empty, B;
empty, A, B
Regards

A:

Say you have $N$ slots and $M$ letters, with $N\ge M$.  (In your example, $N=3$ and $M=2$.)  Then once you choose the slots that will be filled by the $M$ letters, the positions of the letters themselves are determined (because they must be in order) and the positions of the $N-M$ blank spaces are completely determined (because they go in the remaining slots).  So the answer is therefore  $$\binom NM = \frac{N!}{M!(N-M)!}.$$
(If you are not familiar with the notation, leave a comment.)


Q:

What does the word "Rep." mean?

What's meaning of the 'Rep.'?

A:

Representative, in the U.S. political sense: that is, someone elected to the House of Representatives.  Specifically, this guy.  Not this more famous guy:

Edit: As Justin points out in comments, that’s what Rep. means in this particular example, but in other contexts it can mean many other things too.

A:

It should be pointed out that this is actually ambiguous in this case. It could well stand for Representative, as the gentleman in question was in fact a member of the US House of Representatives at the time.
However, it is also a common abbreviation for Republican, which is the political party he is a member of.
I'd guess the poster was aware of this ambiguity, and was fine with it. Space is so limited in a tweet that doing double-duty with a word like this is often considered a good thing.


Q:

What would be the function to dynamically combine Scala's parser combinators?

I am looking for a function to dynamically combine Scala Parser Combinators. For example, if I want to do it statically I can write:
def aDirective: Parser[String] = "a" ^^ { case _ => "a" }
def bDirective: Parser[String] = "b" ^^ { case _ => "b" }

def combinedDirective: Parser[List[String]] =
  aDirective ~ bDirective ^^ { case a ~ b => List(a, b) }

However rather than coding this statically I want to be able to do this dynamically, for the purposes of generating combinations of parsers.
For example:
def aDirective: Parser[String] = "a" ^^ { case _ => "a" }
def bDirective: Parser[String] = "b" ^^ { case _ => "b" }

def combinedDirective: Parser[List[String]] =
  combine(List(aDirective, bDirective))

def combine(parsers: List[Parser[T]): Parser[List[T]] = ???

I think I need to go from a List of parsers to a Parser of List of Results. So I have attempted to write a signature for a function named combine.
At the moment I cannot figure out how to implement the combine function. Whichever way I attempt it, it seems to be fraught with problems that I cannot think how to solve at the moment. For example how do I construct an initial parser for a fold? I have tried to experiment with various foldLeft and reduceLeft constructs, but cannot seem to quite get there.
I am using Scala 2.11. Any ideas?

A:

This is a sequencing operation, and Scalaz provides a shortcut (normally you wouldn't need the explicit instance definition boilerplate with Scalaz, but this is a special case):
import scala.util.parsing.combinator.RegexParsers
import scalaz._, Scalaz._

object MyParser extends RegexParsers {
  implicit val pm = std.util.parsing.combinator.parser.parserMonad(this)

  def aDirective: Parser[String] = "a" ^^ { case _ => "a" }
  def bDirective: Parser[String] = "b" ^^ { case _ => "b" }

  def combine[T](parsers: List[Parser[T]]): Parser[List[T]] = parsers.sequenceU

  def combinedDirective: Parser[List[String]] =
    combine(List(aDirective, bDirective))
}

And then:
scala> MyParser.parseAll(MyParser.combinedDirective, "ab")
res0: MyParser.ParseResult[List[String]] = [1.3] parsed: List(a, b)

You can also define it yourself with a fold:
import scala.util.parsing.combinator.RegexParsers

object MyParser extends RegexParsers {
  def aDirective: Parser[String] = "a" ^^ { case _ => "a" }
  def bDirective: Parser[String] = "b" ^^ { case _ => "b" }

  def combine[T](parsers: List[Parser[T]]): Parser[List[T]] =
    parsers.foldRight(success(List.empty[T])) {
      case (p, acc) => for {
        pRes   <- p
        accRes <- acc
      } yield pRes :: accRes
    }

  def combinedDirective: Parser[List[String]] =
    combine(List(aDirective, bDirective))
}

And it'll work exactly the same. The trick is just getting the base right—it needs to be a parser that always succeeds with the empty list as its value.

Update: if you're defining a class, not an object, the Scalaz approach above won't work (for a number of weird reasons—in short the this isn't stable enough). You can define your own monad instance pretty easily, though:
class MyParser extends RegexParsers {
  implicit val pm = new Monad[Parser] {
    def point[A](a: => A): Parser[A] = success(a)
    def bind[A, B](fa: Parser[A])(f: A => Parser[B]): Parser[B] = fa flatMap f
  }

  def aDirective: Parser[String] = "a" ^^ { case _ => "a" }
  def bDirective: Parser[String] = "b" ^^ { case _ => "b" }

  def combine[T](parsers: List[Parser[T]]): Parser[List[T]] = parsers.sequenceU

  def combinedDirective: Parser[List[String]] =
    combine(List(aDirective, bDirective))
}

You actually don't need a monad instance here to use sequence, just an applicative functor, but the definition is actually a little more convenient and the monad instance may be useful in other cases.


Q:

OCUnit - Break on test case failure?

When debugging test case failures it would be very useful if the execution would automatically break upon test case failure, so that I could directly investigate the failure. So essentially a break point that triggers when an assertion fails.
Does anyone know if there is an easy way to do that?

A:

There are many solutions how can you achieve that, to list a few:

Add a symbolic breakpoint to [SenTestCase failWithException:]
Overriding failWithException: in a SenTestCase
Use your own testing macros, which you can break after the fail


Q:

acts_as_follower issue with following users

I have a User model created in devise:
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :profile, dependent: :destroy
  after_create :build_profile

  acts_as_follower

end

Which has an associated profile with the user. And I'm using the acts_as_follower gem to give this model the ability to follow another model.
I want the User to follow a Profile, so i have my profile model set up like this:
class Profile < ApplicationRecord
  belongs_to :user

  has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "https://s-media-cache-ak0.pinimg.com/564x/f7/61/b3/f761b3ae57801975e0a605e805626279.jpg"
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/

  acts_as_followable

end

The Profile model should be followable according to the gem, which is how I have it set up.
I ran the migrations as required rails generate acts_as_follower
In my profile_controller iv set up the following methods:
  def follow
    @profile = Profile.find(params[:id])
    current_user.follow(@profile)
    redirect_to :back
  end

  def unfollow
    @profile = Profile.find(params[:id])
    current_user.stop_following(@profile)
    redirect_to :back
  end

And in my route.rb file i have the following:
  resources :profiles do
    member do
      get :follow
      get :unfollow
    end
  end

Now in my profiles show view iv set up the button as so:
  <% if !@profile.followed_by?(current_user) %>
    <%= link_to "Follow", follow_profile_path(@profile), class: "btn btn-success btn-outline btn-sm"%>
  <% end %>

According to my knowledge and documentation this should work, but for some reason it does not follow the user or create the association between the user and the profile to follow.

A:

I figured it out, in my gemfile I installed from the master branch, so change your gemfile to this:
gem "acts_as_follower", github: "tcocca/acts_as_follower"


Q:

Cannot add attributes to validation message

I am trying to add a class to the validation messages added by my HtmlHelper:
@Html.ValidationMessageFor(
    m => m.Status,
    htmlAttributes: new { @class = "validation-summary" })

But I am getting this error:

CS1739: The best overload for 'ValidationMessageFor' does not have a parameter named 'htmlAttributes'

But according to the documentation this is the correct parameter name.  I don't want to pass in a custom message.

A:

There a a couple of ValidationMessageFor overloads and none of them is matching your code. The overload you want to use is this and can be called like this:
public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    string validationMessage,
    Object htmlAttributes
)

so you need to add one parameter more:
@Html.ValidationMessageFor(
    m => m.Status,
    null,
    htmlAttributes: new { @class = "validation-summary" })


Q:

Undefined method error with Rails has_one association (Rails 5)

I am attempting to access the methods of an associated model in the view, but getting an undefined method error

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

.  Thanks for your help!
index view:
<% @actuals.each do |actual| %>
  <% if actual.procedures.present? %>
    <% actual.procedures.each do |procedure| %>

       <%= procedure.cpt_code.id %>
       <%= procedure.description %>

    <% end %>
  <% end %>
<% end %>

Controller:
  def index
    @actuals = Actual.all
  end

Models:
class Actual < ApplicationRecord
  has_many :actual_procedures, :dependent => :destroy
  has_many :procedures, through: :actual_procedures

class ActualProcedure < ApplicationRecord
  belongs_to :procedure
  belongs_to :actual
end

class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
end

class CptCode < ApplicationRecord
  has_one :procedure

Procedures in schema:
  create_table "procedures", force: :cascade do |t|
    t.bigint "cpt_code_id"
    t.string "code"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cpt_code_id"], name: "index_procedures_on_cpt_code_id"
  end

A:

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

You don't have cpt_code in procedures table. Perhaps you meant cpt_code_id.
Update:
Actual reason is you didn't defined association for cpt_code in Procedure model
class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
  belongs_to :cpt_code # you should have this
end


Q:

Slide transition between html files using JQuery and AJAX to navigate

I'd like to know if there's an easy way to implement the slide transition effect between many separate html files in my website.  I've been searching for hours but I can't find an example for what I'm trying to do without having redesign the website.  I'm using JQuery and AJAX to validate the selections on the pages and then move to the selected ones after some server side validation.  Is this possible with my current design? Thanks
//JavaScript function
function getValue(aval) {

    $.ajax({
        url: 'Services.aspx/getSelection',
        type: "POST",
        dataType: "json",
        data: '{"aSelection":"' + aval + '"}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            //alert(data.d);
            if (data.d == 1) {
                window.location.href = "InsuredReason.html";
            }
            if (data.d == 2) {
                window.location.href = "AgentInfo.html";
            }
            if (data.d == 3) {
                window.location.href = "ContratistaInfo.html";
            }
            if (data.d == 4) {
                window.location.href = "VisitorInfo.html";
            }
        },
        error: function (er) {
            //alert(er.d);
        }
    });

  }

A:

You don't need to redirect, better update some area of the page with content of html files.
HTML could be:

And javascript would not redirect, but update the content:
function getValue(aval) {
    if (aval == 1) {
        filename = "InsuredReason.html";
    }
    if (aval == 2) {
        filename  = "AgentInfo.html";
    }
    if (aval == 3) {
        filename  = "ContratistaInfo.html";
    }
    if (aval == 4) {
        filename  = "VisitorInfo.html";
    }
    $.ajax({
        url: 'Services.aspx/'+filename,
        type: "GET",
        success: function (data) {
            //alert(data);
            $('#content').html(data);//where data is content of html file
        },
        error: function (er) {
            //alert(er.d);
        }
   });

}


Q:

how to end a line with with a single linefeed (LF) character ( Unix text file convention ) in Dreamweaver

I am new to Zend Framework.
In zend framework coding standard,It is recommended to terminate the line with a single linefeed (LF) character (Unix text file convention).
I am using Dreamweaver as IDE to develop applications.
Does Dreamweaver automatically converts "Enter" to single linefeed (LF) character or is there any option to achieve this.

A:

Here is a link to the help page that has the answer:
http://help.adobe.com/en_US/dreamweaver/cs/using/WSc78c5058ca073340dcda9110b1f693f21-7bdda.html
Edit -> Preferences -> Code Format (Line Break Type)


Q:

Срочно и быстро начать ExtJavaScript

Здравствуйте. Нужно для проекта изучить ExtJS. ПисАться он будет под фреймворком Yii. Что можете посоветовать? С чего начать?

П.С. Вот нашел ExtJS для Yii (Ссылка), но не знаю стоит ли ее использовать, ибо боюсь, что документации будет маловато для нее.

A:

ExtJs  очень сложный и я бы начинал с него, а потом бы уже изучал бы пхпшные либы. Кстати, "срочно и быстро" -это тонны говнокода, к которому ненависть увеличивается с каждой строкой. Изучите все, а потом уже "срочные и быстрые" проекты делайте или найдите спеца с хорошим скидок по теме.  Удачи.


Q:

Platform-independent directory

Does ASP.NET Core offer any platform-independent way to access standard paths, such as where data or configure files are supposed to be saved?  Modules such as Qt's  QStandardPaths are very helpful to prepare Qt applications to be deployed in a platform-independent way, but unfortunately I haven't found any similar service in ASP.NET Core.  Does anyone know if anything like that exists in the .Net core or ASP.NET Core platforms?

A:

You can use Environment.GetFolderPath.
This blog post provides more info on how the API behaves cross-platform.


Q:

What is the appropriate preposition for spot?

The first member is standing up at the first spot.
The first member is standing up on the first spot.

Which preposition is appropriate?

A:

At is used with places.  If the "spot" can be considered a place, at can be used.
X on Y is used if

Y is a flat surface or object and
The feet or bottom part of X makes contact with the surface, or top surface of that object.

If the "spot" fulfills that criteria, on can be used.
It's possible both on or at will work and in that case it doesn't matter which you use.


Q:

What does GetFunctionPointerForDelegate convert a String^ parameter in a delegate into?

I'm trying to convert a C# delegate to a C++ function pointer, using Managed C++.  Here's the method we were previously using:
// Define a delegate
public delegate void ADelegate(Int32);
ADelegate^ delegateInstance;

// Define a function pointer
typedef void (__stdcall *AFuntionPointer)(int);
AFuntionPointer functionPointerInstance;

// Create an instance of a delegate, using GetFunctionPointerForDelegate
delegateInstance = gcnew ADelegate(this, &AClass::AFunction);

// Convert the delegate to a pointer
IntPtr anIntPtr = Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(delegateInstance);

// Cast the pointer into a function pointer
functionPointerInstance = static_cast<AFuntionPointer>(anIntPtr.ToPointer());

If I turn the ADelegate's parameter from an Int32 to a String^, to what type should I change the AFunctionPointer's parameter to?  In another words, if I changed the first two lines in the above code to:
public delegate void ADelegate(String ^);
ADelegate^ delegateInstance;

How should I change the next two lines?
// To what type does GetFunctionPointerForDelegate translate String^ to?
typedef void (__stdcall *AFuntionPointer)( /* char*?  std::string? */ );
AFuntionPointer functionPointerInstance;

A:

Marshal::GetFunctionPointerForDelegate() on that delegate would generate a function pointer that's compatible with
  typedef void (__stdcall *AFuntionPointer)( const char* );

String^ marshals to const char* unless a [MarshalAs] attribute is applied to the delegate argument.  Marshaling directly to std::string is not possible, the pinvoke marshaller doesn't know anything about C++ object layout for classes that are declared in a header file.


Q:

Newtonsoft Json deserializer not working correctly

I am building an application that handles surveys for people to fill in, in a C# environment.
When I run the application normally, everything works fine, the deserialize works, the serialize works, everything works.
When I send a survey, everything again goes fine. When i re-open the application, the program automatically sends a request to the server to retrieve the surveys available. But when he tries to deserialize the json, he sees he needs to make 2 sub objects but does not fill them.
I checked to see if the json I was getting was correct, and it is. The problem seems that the deserialize doesn't know where the data has to go (even though he normally works with the exact same method).
What I get instead is:

root: This is the base variable and is null untill it gets filled. So I know the deserialize is doing something.
newSurvey: Created by the deserialize, but does not get filled (stays null)
result: Created by the deserialize, but does not get filled (stays null)

The json looks like this (please keep in mind I kept the data itself out and it is a stripped down version):
{
"id": "data",
"name": "data",
"description": "data",
"surveyVersion": "data",
"welcomeMessage": "data",
"exitMessage": "data",
"anonymousAnswers": false,
"publicationDate": "data",
"expirationDate": "data",
"serverInstanceName": "data",
"documentVersion": "data",
"questions": [
    {
        "id": "data",
        "position": 0,
        "text": "data",
        "answerRequired": true,
        "dependsOn": null,
        "dependencyType": null,
        "dependencyParameter": null,
        "choices": null,
        "type": {
            "name": "data",
            "hasChoices": false,
            "multipleAnswersPossible": false
        },
        "defaultValue": null,
        "openOption": null,
        "maxOpenOption": null,
        "maxCharacters": "data",
        "minimumAnswers": null,
        "maximumAnswers": null,
        "answers": null,
        "openAnswers": null
    }
]}

I checked the json using http://jsonlint.com/ and it is correct, I also checked the data manually and it contains all the data I need.
Now I don't know how I can make sure he deserializes normally if he doesn't want to do this. If I did not send a survey, everything works fine, this only happens after I send a survey and restart the application.
code where the error occurs:
if (jSONSurvey != "") {
            if (newSurveys != null) {
                var root = JsonConvert.DeserializeObject<RootObject> (jSONSurvey);
                if (root.newSurveys != null)
                    newSurveys = root.newSurveys;
            } else {
                newSurveys = new List<NewSurvey> ();
                var root = JsonConvert.DeserializeObject<RootObject> (jSONSurvey);
                if (root.newSurveys != null)
                    newSurveys = root.newSurveys;
            }

The crash part is the else statement.

A:

The RootObject class structure appears not to match the supplied data.
Try something like this to debug if it's the class or conversion that is failing.
 var root = JsonConvert.DeserializeObject(jSONSurvey);
 Console.WriteLine(root.id);

If the root object is populated with data, then the structure of your RootObject class does not allow for the properties.


Q:

Sending mail through Command line RHEL 7

I ‘m having difficulty sending mail.
My mail.rc is below
account gmail {
set smtp-use-starttls
set ssl-verify=ignore
set smtp-auth=login
set smtp=smtp://smtp.gmail.com:587
set from=”email@gmail.com”
set smtp-auth-user=uname
set smtp-auth-password=***********
set ssl-verify=ignore
set nss-config-dir=/etc/pki/nssdb/
}

But I’m getting error
[root@localhost ~]# echo -e “Mail body text” | mailx -A gmail    -s“Mail       subject” uname.example.com

[root@localhost ~]# Error in certificate: Peer’s certificate issuer is   not recognized.
smtp-server: 534-5.7.14 Please log in via your web browser and
smtp-server: 534-5.7.14 then try again.
smtp-server: 534-5.7.14 Learn more at
smtp-server: 534 5.7.14 https://support.google.com/mail/answer/78754  205sm11220769pfy.32 – gsmtp
“/root/dead.letter” 11/337
. . . message not sent.

I think I’m having a certificate issue. I used the firefox certificates also. Still same issue.
I’m using RHEL7 .
Could you please help me

A:

I changed some setting in google account, more likely to reduce the security little bit.
Following is the link to do so.
http://www.google.com/accounts/DisplayUnlockCaptcha
Below link will enable the acess to less secure apps.
https://support.google.com/accounts/answer/6010255


Q:

Быстрые способы нахождения всех простых чисел меньше N

Какие существуют алгоритмы наиболее быстрого нахождения всех простых чисел меньше N кроме всем известных:

Решето Эратосфена
Решето Аткина
Решето Сундарама

И какие существуют быстрые реализации на Python (Vanilla, Numpy, etc.)?
Наивная реализация решета Эратосфена:
def eratosthenes2(n):
    multiples = set()
    for i in range(2, n+1):
        if i not in multiples:
            yield i
            multiples.update(range(i*i, n+1, i))

Аналогичный вопрос в англоязычной версии SO
PS идея создания данного вопроса связана с постоянно появляющимися новыми вопросами об эффективной реализации нахождения всех простых чисел меньше N.

A:

В качестве ответа я решил сравнить самые удачные реализации из ответов на данный вопрос и сделать замеры времени (для этого я использовал модуль reporttime из этого ответа @jfs:
primes.py

import numpy
from math import sqrt, ceil

def rwh_primes(n):
    """ Returns  a list of primes < n """
    # (c) Robert William Hanks - https://stackoverflow.com/a/3035188/5741205
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

def rwh_primes1(n):
    """ Returns  a list of primes < n """
    # (c) Robert William Hanks - https://stackoverflow.com/a/3035188/5741205
    sieve = [True] * (n//2)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
    return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]]

def rwh_primes2(n):
    """ Input n>=6, Returns a list of primes, 2 <= p < n """
    # (c) Robert William Hanks - https://stackoverflow.com/a/3035188/5741205
    n, correction = n-n%6+6, 2-(n%6>1)
    sieve = [True] * (n//3)
    for i in range(1,int(n**0.5)//3+1):
      if sieve[i]:
        k=3*i+1|1
        sieve[      k*k//3      ::2*k] = [False] * ((n//6-k*k//6-1)//k+1)
        sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1)
    return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]]

def primesfrom3to(n):
    """ Returns a array of primes, 3 <= p < n """
    # (c) Robert William Hanks - https://stackoverflow.com/a/3035188/5741205
    sieve = numpy.ones(n//2, dtype=numpy.bool)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = False
    return 2*numpy.nonzero(sieve)[0][1::]+1

def primesfrom2to(n):
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    # (c) Robert William Hanks - https://stackoverflow.com/a/3035188/5741205
    sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)
    for i in range(1,int(n**0.5)//3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[       k*k//3     ::2*k] = False
            sieve[k*(k-2*(i&1)+4)//3::2*k] = False
    return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]

def sieveOfEratosthenes(n):
    """sieveOfEratosthenes(n): return the list of the primes < n."""
    # Code from: <dickinsm@gmail.com>, Nov 30 2006
    # http://groups.google.com/group/comp.lang.python/msg/f1f10ced88c68c2d
    if n <= 2:
        return []
    sieve = list(range(3, n, 2))
    top = len(sieve)
    for si in sieve:
        if si:
            bottom = (si*si - 3) // 2
            if bottom >= top:
                break
            sieve[bottom::si] = [0] * -((bottom - top) // si)
    return [2] + [el for el in sieve if el]

def sieveOfAtkin(end):
    """sieveOfAtkin(end): return a list of all the prime numbers <end
    using the Sieve of Atkin."""
    # Code by Steve Krenzel, <Sgk284@gmail.com>, improved
    # Code: https://web.archive.org/web/20080324064651/http://krenzel.info/?p=83
    # Info: http://en.wikipedia.org/wiki/Sieve_of_Atkin
    assert end > 0
    lng = ((end-1) // 2)
    sieve = [False] * (lng + 1)

    x_max, x2, xd = int(sqrt((end-1)/4.0)), 0, 4
    for xd in range(4, 8*x_max + 2, 8):
        x2 += xd
        y_max = int(sqrt(end-x2))
        n, n_diff = x2 + y_max*y_max, (y_max << 1) - 1
        if not (n & 1):
            n -= n_diff
            n_diff -= 2
        for d in range((n_diff - 1) << 1, -1, -8):
            m = n % 12
            if m == 1 or m == 5:
                m = n >> 1
                sieve[m] = not sieve[m]
            n -= d

    x_max, x2, xd = int(sqrt((end-1) / 3.0)), 0, 3
    for xd in range(3, 6 * x_max + 2, 6):
        x2 += xd
        y_max = int(sqrt(end-x2))
        n, n_diff = x2 + y_max*y_max, (y_max << 1) - 1
        if not(n & 1):
            n -= n_diff
            n_diff -= 2
        for d in range((n_diff - 1) << 1, -1, -8):
            if n % 12 == 7:
                m = n >> 1
                sieve[m] = not sieve[m]
            n -= d

    x_max, y_min, x2, xd = int((2 + sqrt(4-8*(1-end)))/4), -1, 0, 3
    for x in range(1, x_max + 1):
        x2 += xd
        xd += 6
        if x2 >= end: y_min = (((int(ceil(sqrt(x2 - end))) - 1) << 1) - 2) << 1
        n, n_diff = ((x*x + x) << 1) - 1, (((x-1) << 1) - 2) << 1
        for d in range(n_diff, y_min, -8):
            if n % 12 == 11:
                m = n >> 1
                sieve[m] = not sieve[m]
            n += d

    primes = [2, 3]
    if end <= 3:
        return primes[:max(0,end-2)]

    for n in range(5 >> 1, (int(sqrt(end))+1) >> 1):
        if sieve[n]:
            primes.append((n << 1) + 1)
            aux = (n << 1) + 1
            aux *= aux
            for k in range(aux, end, 2 * aux):
                sieve[k >> 1] = False

    s  = int(sqrt(end)) + 1
    if s  % 2 == 0:
        s += 1
    primes.extend([i for i in range(s, end, 2) if sieve[i >> 1]])

    return primes

def sundaram3(max_n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/2073279#2073279
    numbers = list(range(3, max_n+1, 2))
    half = (max_n)//2
    initial = 4

    for step in range(3, max_n+1, 2):
        for i in range(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)

        if initial > half:
            return [2] + list(filter(None, numbers))

Замеры времени:
import os
import pandas as pd

os.chdir(r'C:\work\project\primes_timing')

import primes
from reporttime import get_functions_with_prefix, measure

funcs = get_functions_with_prefix('', module=primes)

d = {}
for n in [10**3, 10**4, 10**5, 10**6]:
    m = measure(funcs, args=[n])
    d[n] = pd.Series({b:a for a,b in m})
r = pd.DataFrame(d)

Вывод на печать:
name                     time ratio comment
primesfrom3to         21 usec  1.00 [1000]
sieveOfEratosthenes 40.1 usec  1.91 [1000]
rwh_primes          50.2 usec  2.39 [1000]
primesfrom2to       63.6 usec  3.02 [1000]
sundaram3           91.8 usec  4.37 [1000]
rwh_primes1          110 usec  5.25 [1000]
rwh_primes2          129 usec  6.12 [1000]
sieveOfAtkin         286 usec 13.61 [1000]

name                     time ratio comment
primesfrom3to       69.3 usec  1.00 [10000]
primesfrom2to        172 usec  2.48 [10000]
sieveOfEratosthenes  375 usec  5.41 [10000]
rwh_primes           447 usec  6.45 [10000]
rwh_primes2          503 usec  7.26 [10000]
rwh_primes1          577 usec  8.33 [10000]
sundaram3           1.22 msec 17.66 [10000]
sieveOfAtkin         2.2 msec 31.72 [10000]

name                     time ratio comment
primesfrom3to        306 usec  1.00 [100000]
primesfrom2to        371 usec  1.21 [100000]
sieveOfEratosthenes 3.82 msec 12.47 [100000]
rwh_primes          3.94 msec 12.84 [100000]
rwh_primes2         4.19 msec 13.68 [100000]
rwh_primes1         5.37 msec 17.53 [100000]
sundaram3           15.2 msec 49.57 [100000]
sieveOfAtkin        21.3 msec 69.47 [100000]

name                     time  ratio comment
primesfrom2to       2.29 msec   1.00 [1000000]
primesfrom3to       3.05 msec   1.33 [1000000]
rwh_primes2         38.7 msec  16.91 [1000000]
rwh_primes1         48.3 msec  21.12 [1000000]
rwh_primes          52.5 msec  22.96 [1000000]
sieveOfEratosthenes   61 msec  26.64 [1000000]
sieveOfAtkin         205 msec  89.64 [1000000]
sundaram3            245 msec 107.27 [1000000]

DataFrame с результатами:
In [67]: r
Out[67]:
                      1000      10000     100000    1000000
primesfrom2to        0.000064  0.000172  0.000371  0.002288
primesfrom3to        0.000021  0.000069  0.000306  0.003046
rwh_primes           0.000050  0.000447  0.003936  0.052516
rwh_primes1          0.000110  0.000577  0.005373  0.048307
rwh_primes2          0.000129  0.000503  0.004191  0.038678
sieveOfAtkin         0.000286  0.002197  0.021293  0.205074
sieveOfEratosthenes  0.000040  0.000375  0.003823  0.060955
sundaram3            0.000092  0.001223  0.015194  0.245407

график:
import matplotlib.pyplot as plt
import matplotlib

matplotlib.style.use('ggplot')

r.T.plot(loglog=True, grid=True, figsize=(8, 6))
plt.xlabel('N - generate all primes below N')
plt.ylabel('Time in seconds')
plt.show()


Q:

Can't ping LAN machines while on wired connection

I have weird situation where a single machine on my home network can't access another. The network is provided by TP-Link WR841ND router to following machines:

A - 192.168.1.117 - Win8.1 machine, wired connection,
B - 192.168.1.200 - Ubuntu 12.04 server machine, wired connection,
C - 192.168.1.111 - Macbook, wireless connection,
D - 192.168.1.210 - Raspberry Pi, wireless connection.

The problem is that A and B can't ping each other, both with Destination host unreachable error.

A can ping C and D.
B can ping C and D.
C can ping A, B, D.
D can ping A, B, C.

If I take wireless dongle from D and use it on A, everything suddenly works - it's only when both A and B are connected via wired connection the problems arise.
arp -a on box A doesn't list B:

Interface: 192.168.1.117 --- 0xa
  Internet Address      Physical Address   Type
  192.168.1.1           *mac-address*     dynamic
  192.168.1.111         *mac-address*     dynamic
  192.168.1.210         *mac-address*     dynamic

arp -a on box B lists A, but with <incomplete> where mac addresses of other devices are:

A (192.168.1.117) at <incomplete> on eth0
C (192.168.1.111) at *mac-address* [ether] on eth0
router (192.168.1.1) at *mac-address* [ether] on eth0
D (192.168.1.210) at *mac-address* [ether] on eth0

arp -a on box C lists everything:

router (192.168.1.1) at *mac-address* on en0 ifscope [ethernet]
A (192.168.1.117) at *mac-address* on en0 ifscope [ethernet]
B (192.168.1.200) at *mac-address* on en0 ifscope [ethernet]
D (192.168.1.210) at *mac-address* on en0 ifscope [ethernet]

The router is running  DD-WRT v24-sp2 (06/23/14) firmware. Resetting factory settings didn't help, neither did disabling SPI firewall, toggling AP isolation on or off, or poking other buttons in frustration.
Any suggestions?

A:

It turned out to be bug in DD-WRT router firmware. Appears that this old bug is back in builds dated after 29.03.2014


Q:

java: List.contains() performance difference with manual searching

I tried to demonstrate the difference between List.contains() and manually searching execution times the result is awesome. Here is the code,
public static void main(String argv[]) {
    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("b");

    long startTime = System.nanoTime();

    list.contains("b");

    long endTime = System.nanoTime();
    long duration = endTime - startTime;

    System.out.println("First run: "+duration);

    startTime = System.nanoTime();
    for(String s: list){
        if(s.equals("b"))
            break;
    }
    endTime = System.nanoTime();

    duration = endTime - startTime;
    System.out.println("Second run: "+duration);

}

Output:

First run: 7500
Second run: 158685

how contains() function makes such a big difference?
which search algorithm does it use?
if list conatins the searched element, does it terminate searching at first element?

A:

First off, it is not wise to trust results coming from a singular test like that.  There are too many variable factors, caching implications to consider, and other such things - you should rather consider writing a test that uses randomization over trials to some extent, and performs the different checks millions of times, not just once.
That said, I expect your results will remain the same;  ArrayList implements contains() using its own indexOf() method, which loops directly over the underlying array it stores.  You can see this for yourself here
The foreach loop, on the other hand, requires instantiating an Iterator, accessing the array through all of its methods, and just in general doing a lot more work than ArrayList's own direct implementation does.  Again, though, you should benchmark it more thoroughly!

A:

Writing a correct microbenchmark is hard. If you use a better benchmark, you'll likely see that the difference between the approaches is minor - at least, the following benchmark is far more robust, and shows a mere 10% difference in execution time between the two approaches:
public abstract class Benchmark {

    final String name;

    public Benchmark(String name) {
        this.name = name;
    }

    abstract int run(int iterations) throws Throwable;

    private BigDecimal time() {
        try {
            int nextI = 1;
            int i;
            long duration;
            do {
                i = nextI;
                long start = System.nanoTime();
                run(i);
                duration = System.nanoTime() - start;
                nextI = (i << 1) | 1;
            } while (duration < 1000000000 && nextI > 0);
            return new BigDecimal((duration) * 1000 / i).movePointLeft(3);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString() {
        return name + "\t" + time() + " ns";
    }

    public static void main(String[] args) throws Exception {
        final List<String> list = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            list.add("a");
        }

        Benchmark[] marks = {
            new Benchmark("contains") {
                @Override
                int run(int iterations) throws Throwable {
                    for (int i = 0; i < iterations; i++) {
                        if (list.contains("b")) {
                            return 1;
                        }
                    }
                    return 0;
                }
            },
            new Benchmark("loop") {
                @Override
                int run(int iterations) throws Throwable {
                    for (int i = 0; i < iterations; i++) {
                        for (String s : list) {
                            if (s.equals("b")) {
                                return 1;
                            }
                        }
                    }
                    return 0;
                }
            }
        };

        for (Benchmark mark : marks) {
            System.out.println(mark);
        }
    }
}

prints (on my dated notebook, on a Java 7 Oracle JVM in server mode):
contains    10150.420 ns
loop        11363.640 ns

The slightly larger overhead of the loop is likely caused by the Iterator checking for concurrent modification and twice for the end of the list on every access, see the source code of java.util.ArrayList.Itr.next() for details.
Edit: With very short lists, the difference is more pronounced. For instance for a list of length 1:
contains    15.316 ns
loop        69.401 ns

Still, nowhere near the 20:1 ratio your measurements indicate ...

A:

As you can see from the code contains needs O(n) iterations. If you re-implement your for loop to:
for(int i=0; i < list.size(); i++){
    if(list.get(i).equals("b"))
        break;
}

you'll see dramatic improvement in your search time. So you can put blame on List iterator for the time overhead. Iterator instantiation and calls of next and hasNext methods are adding some milliseconds.


Q:

Copy Constructor

Im trying to do the copy part of a "deep copy" with my copy constructor:
class myClass
{
public:

    myClass ( const char *cPtr, const float fValue )
    myClass ( const myClass& myClassT );

private:

    const char* &myAddress;
    float MyFloater;

};

//myClass.cpp

myClass::myClass( const char *cPtr, const float fValue )
{
// Initialize both private varaible types
   const char* &myAddress = cPtr;
   float myFloater = fValue;
}

myClass::myClass( const myClass& classType )
{
// copy what we did ...
      myAddress = myClass.myAddress;
      myFloater = myClass.myFloater;
}

with just that, im getting only the, "must initialize whataver varaible in base/member initalizer list.
They are initalized in the constructor!
What would i need to do with the classtype object address?

A:

const char* &myAddress;

is a reference, so it must be initialized in an initializer list during the constructor, i.e.
myClass::myClass(const char *& cPtr, const float fValue): myAddress(cPtr)

Note that this is a bad way to handle this situation (of course, depending on what you're trying to do), since if the pointer passed goes out of scope, then you're screwed.
A better way to do this (again, depending on what you're trying to do) is just to copy the pointer over, and during your "deep" copy, reallocate and copy its contents. Unless you actually need a reference to the pointer, of course.

A:

Several problems:
1) Why are you repeating the variable declaration in the first constructor?
2) Why are you declaring the myAddress as a reference rather than just as a pointer?
A reference always has to be initialized in the constructor initialization list. This is likely the cause of your error message. Initializing in the constructor body is not acceptable to C++.
In the second constructor, you probably want something like:
myClass::myClass( const myClass& classType ):myAddresss(classType.myAddress), myFloater(classType.myFloater)
{
}

The reason for this has to do with how objects are constructed. At the point where the body of the constructor executes, the object is already considered to have been "built" so references should already be valid, so your assignment of a reference is rejected by C++.
And by the way, this is not really a deep copy...

A:

in addition to what others said, you are not really doing a 'deep copy' what you are doing is setting the pointer to point the same, that is not a deep copy. You need to duplicate whatever the pointer is pointing to as well (to be on the safe side).


Q:

How dangerous is SMBv1?

I have a NAS (network disk) from Zylex which stopped working under Windows 10 a while ago. Investigation shows that it uses SMBv1, which was implicated in several ransomware attacks and was therefore disabled by Microsoft. I have not yet found a workaround (I'm still looking) so it seems that my choices are to re-enable SMBv1 (as described in the Microsoft support guide)
or to buy a new NAS.
Recent posts on Zyxel's site suggests that Zyxel are aware of the problem but have no plans to fix it. I have the latest firmware.
We (my wife and I, both retired) have a home network with two laptops, two tablets, two smartphones, a network printer and the NAS, we use internet extensively but not dangerously. We don't click on strange links or the like, but I could imagine us falling for a well-crafted Facebook post or something similar.
So my question is: how dangerous is SMBv1? Should I re-enable SMBv1 or buy a new NAS?

A:

There are a number of CVEs against SMBv1 including:

Arbitrary Code Execution CVE-2017-0148
Denial of Service CVE-2017-0280

So it comes down to what is an acceptable risk for you, and do you try to compensate for it by putting other controls in place like using an AV, a firewall, automatic patching, OpenDNS, etc.
Is it worth it to enable it for now and then look for a replacement for your NAS in the meantime? Only you can answer.
Me, I'd leave it on using all of the above extra security measures and look on Amazon to replace the NAS in the near term.


Q:

Adding Custom Identity Provider using SAML 2.0 (SiteMinder) to Azure ACS

I'm looking for help adding a custom identity provider to ACS.  I'm currently working on an application hosted in Windows Azure. For authentication - we are trying to configure ACS to work with CA SiteMinder.
We have previously been told that ACS can natively support custom identity providers using SAML 2.0 tokens, but we are not sure how to properly add this connection in ACS. Simply trying to add it through the Management Portal does not give us this option and we are forced to use WS-Federation. Is there any way to do this without reconfiguring SiteMinder to provide to use WS-Federation?
Certain threads suggest PowerShell cmdlets exist to add identity providers in ACS, but all such links appear to be several years old (and now dead).
One of the original blog announcments: http://www.cloudidentity.com/blog/2011/05/17/announcing-sample-acs-cmdlets-for-the-windows-azure-appfabric-access-control-service/
The current Windows Azure PowerShell commands do not appear to have options for interacting with ACS.

A:

ACS doesn't support SAML (the protocol). It is confusing, because WS-Federation uses SAML Tokens too.
On a side note: if your app is only going to authenticate users in your CA SiteMinder, then there's not much value in in having an intermediary (ACS). If you can turn on WS-Fed in SM, then just connect the app to it. WIF only supports WS-Fed, by the way, so you'll need WS-Fed regardless (or use some other library besides WIF).
An intermediary is valuable when you have multiple identity sources: your SM, someone else's, etc. and can act as a broker of authentication.
Depending on the protocols you need to support ACS might or might not be a good candidate (do you need OAuth? SAML? WS-Fed? etc).


Q:

How to check for DOM equality with jQuery?

I'm basically building a simple list, and one of the items in the list is selected. I'm accomplishing this by having a "selected" class applied to whichever item I want to have selected.  I have two buttons that go forward and backward which traverse this list.  However, when the user gets to the first or the last element in the list, I want to do a post back.  This is where I'm stuck, because I'm having trouble identifying that the currently selected item is not the first or the last.
Simple Example:

item 1

item 2

item 3

Let's say the user presses the next button, at this point I'm checking for something similar to this:
if (jQuery('#list p.selected') == jQuery('#list p:last-child'))
    //do post back

However, this logic is returning false, which leads me to believe I'm approaching this the wrong way.
What is the best way for me to check for this kind of logic using jQuery?

A:

Although you can compare jquery objects as Matt has shown, or simply with index operator
if($("#list p.selected")[0] == $("#list p:last-child")[0])...

this is rarely needed with jQuery. There  is a better way!
if($("#list p.selected").is(":last-child"))....

or the other way round, more readable
if($("#list p:last-child").is(".selected"))....

A:

jQuery is an object, so you're technically comparing two different (but similar) objects, which will always be false.
Try:
if (jQuery('#list p.selected').get(0) == jQuery('#list p:last-child').get(0))

jQuery.get()


Q:

Need a suitable toxic chemical for a murder plot in my novel

I need ideas for a chemical or disease which kills the victim upon holding it in the palm for about 4 or 5 seconds. The death isn't necessarily immediate, as it might take days to kill the victim in the case of an incurable disease.
If the substance can't kill the victim, at least it should cause permanent damage to the heart, nervous system, or brain.  An overall skin disfigurement or damage to any other vital organs will be okay!
Something mixed in DMSO?
The specific chemical or disease should be somewhat easy to acquire with some effort for a common man because it must sound obvious for the readers.
Don't suggest nerve agents or Anthrax please. Because they are inaccessible for a common man.

A:

The canonical example is
Dimethylmercury

Dimethylmercury is an organomercury compound. A highly volatile, reactive, flammable, and colorless liquid, dimethylmercury is one of the strongest known neurotoxins, with a quantity of less than 0.1 mL capable of inducing severe mercury poisoning, and is easily absorbed through the skin. Dimethylmercury is capable of permeating many materials, including plastic and rubber compounds. It has a slightly sweet odor, although inhaling enough of the chemical to notice this would be hazardous. (Wikipedia, s.v. dimethylmercury)
Dimethylmercury is extremely toxic and dangerous to handle. Absorption of doses as low as 0.1 mL can result in severe mercury poisoning. The risks are enhanced because of the high vapor pressure of the liquid.
Permeation tests showed that several types of disposable latex or polyvinyl chloride gloves (typically, about 0.1 mm thick), commonly used in most laboratories and clinical settings, had high and maximal rates of permeation by dimethylmercury within 15 seconds. The American Occupational Safety and Health Administration advises handling dimethylmercury with highly resistant laminated gloves with an additional pair of abrasion-resistant gloves worn over the laminate pair, and also recommends using a face shield and working in a fume hood.
Dimethylmercury is metabolized after several days to methylmercury. Methylmercury crosses the blood–brain barrier easily, probably owing to formation of a complex with cysteine. It is eliminated from the organism slowly, and therefore has a tendency to bioaccumulate. The symptoms of poisoning may be delayed by months, resulting in cases in which a diagnosis is ultimately discovered, but only at the point in which it is too late for an effective treatment regimen to be successful.
The toxicity of dimethylmercury was highlighted with the death of Karen Wetterhahn, a professor of chemistry at Dartmouth College, in 1997. Professor Wetterhahn specialized in heavy metal poisoning. After she spilled a few drops of this compound on her latex glove, the barrier was compromised, and within minutes it was absorbed into her skin. It circulated through her body and accumulated in her brain, resulting in her death ten months later. This accident is a common toxicology case-study and directly resulted in improved safety procedures for chemical-protection clothing and fume use, which are now called for when any exposure to such severely toxic and/or highly penetrative substances is possible (e.g., in chemical munitions stockpiles and decontamination facilities).

The beauty of it is that dimethylmercury is easily synthesized:

The compound was one of the earliest organometallics reported, reflecting its considerable stability. It is formed by treating sodium amalgam with methyl halides:
$\mathrm{Hg} + 2 \mathrm{Na} + 2 \mathrm {CH}_3\mathrm{I} \rightarrow \mathrm {Hg}(\mathrm{CH}_3)_2 + 2 \mathrm {NaI}$

Methyl iodide ($\mathrm {CH}_3\mathrm{I}$) itself is also easy to make.
All in all, all you need in order to make one the deadliest known substances is access to a high-school chemistry laboratory.

A:

Honeybee.

https://cronkitenews.azpbs.org/2018/02/21/advocacy-groups-pressure-state-to-ban-bee-killing-pesticides/
I like this because if your victim is allergic, he can very definitely die from a bee sting.  It takes seconds to get stung.  This method is not applicable to the general population, so if user63214 is some disgruntled would-be murderer I am not an accessory.  But for a story it could work just fine.

A:

Caffeine

known to work with DMSO (some people consume it this way)
wikipedia: "pure powdered caffeine, which is available as a dietary supplement, can be lethal in tablespoon-sized amounts"

Warfarin

accessible as rat poison
a few grams should be enough (1-5 mg tablets are used in medicine)
use with DMSO? no idea if that would work
causes bleeding, necrosis...

Hydrofluoric acid

indirectly accessible in glass etching kits
or you can just buy it
how scary do you wish your novel to be?