Q:

Issues getting python 3 linux created script to run on Windows python 3

If anyone can help me, that would be great. I created a python server and client script on Linux with python version 2.6. To my understanding as long as I install the same version of python in Windows, I should be able to run the same script with out a problem. I did this and the script doesn't do anything except print out "Importerror: no module named fcntl". I'm adding the server code and the client. If any one can shed some light on what it is that I'm doing wrong, that would be great. As well, since I'm already here, how can I possibly also get the client side code to run automatically in windows with out having to install python in client side machines.
CLIENT
  #!/usr/bin/env python

import socket
import fcntl
import struct

#############################
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]

host = socket.gethostname()

#print host
#print getHwAddr('eth0')
#print get_ip_address(enter code here'eth0')
info = "<"+get_ip_address('eth0')+">","{"+ getHwAddr('eth0')+"}","~"+host+"~"
############################

TCP_IP = 'IP'
TCP_PORT = xxxx
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(str(info))
data = s.recv(BUFFER_SIZE)
s.close()

#print "received data:", data

SERVER
import socket
import re
import subprocess

TCP_IP = ''
TCP_PORT = XXXX
BUFFER_SIZE = 2048  # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(50)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
     data = conn.recv(BUFFER_SIZE)
     if not data: break
     print "received data:", data
     da = open("data.txt", "wb")
     da.write(data);
     conn.send(data)  # echo
subprocess.Popen(["python", "ReadandInsert.py"])
conn.close()

Also, quick mention. The server side code will only run in Linux and the client code will be running in Windows. Thank you again for anyone that can lend a hand...!!

A:

fcntl only exists on Unix platforms.
Try using the following to get the mac address on Windows in replace of your fcntl.ioctl() call:
import netifaces as nif
...
...
def getHwAddr(ip):
    'Returns a list of MACs for interfaces that have given IP, returns None if not found'
    for i in nif.interfaces():
        addrs = nif.ifaddresses(i)
        try:
            if_mac = addrs[nif.AF_LINK][0]['addr']
            if_ip = addrs[nif.AF_INET][0]['addr']
        except IndexError:
            if_mac = if_ip = None
        except KeyError:
            if_mac = if_ip = None
        print if_ip, ip
        if if_ip == ip:
            return if_mac
    return None

This is from a user name @kursancew, but I think it is very appropriate.  I modified the name to match.
Then, just fix this line so you can configure by IP instead of by interface name across the board (interface names in Windows are a bit ... longer).
ip_address = '123.234.34.5'    # from your configuration
...
...
info = "<"+ip_address+">","{"+ getHwAddr(ip_address)+"}","~"+host+"~"


Q:

CSS background text filling the box

I'm trying to make a copy of a website as my first CSS/HTML exercise.
I can't figure out how to make the menu list so it has its background filling the box (extending until the right border).
Picture of what I have now (right side of the picture, red lines show where the background should go) and what I want to get (left side).
My code.
I've tried so far to achieve it e.g. with 'width' and 'display' parameters, but e.g. display: block; remove the lines between text. I'm out of ideas.

A:

        display: block;
        width: 100%;
        margin-bottom: 2px;

to the #menu


Q:

draw an svg arc between lat longs

The following draws a curve:
var curvedLine = {
    path: 'M 50,-150 A 100,100 0 0 100 -3,0',
    fillColor: 'transparent',
    fillOpacity: 0.5,
    scale: 1,
    strokeColor: 'gold',
    strokeOpacity: 0.6,
    strokeWeight: 7
};

var marker = new google.maps.Marker({
    position: newLoc,
    icon: curvedLine,
    map: map
});

In the curvedLine, after A, can I give a location coordinates on the  map?
Because when the map is zoomed out, curvedLine size remains same. I want it to scale along with the map zoom.

A:

I have written a function. Please review it.
function drawCurvedLine(startLatLng, endLatLng, offset, right, left, lineColor) {
    var midLoc = getMidPoint(startLatLng, endLatLng);// Get the mid point of the start and end LatLngs
    var midLoc1 = getMidPoint(startLatLng, midLoc);// Get the mid point of the start LatLng and mid LatLng
    var midLoc2 = getMidPoint(midLoc, endLatLng);// Get the mid point of the mid LatLng and end LatLng
    var heading = google.maps.geometry.spherical.computeHeading(startLatLng, endLatLng);// Compute the heading of the start and end LatLngs

    // Change the heading based on right or left value
    var headingOffset;
    if (right == 1 && left == 0) {
        headingOffset = 90;
    }
    else if (right == 0 && left == 1) {
        headingOffset = -90;
    }

    var offsetLoc = google.maps.geometry.spherical.computeOffset(midLoc, offset / 1.5, heading + headingOffset);// Get the offset location of the mid point of start and end LatLngs
    var offsetLoc1 = google.maps.geometry.spherical.computeOffset(midLoc1, offset / 2, heading + headingOffset);// Get the offset location of the mid point of midLoc and start LatLng
    var offsetLoc2 = google.maps.geometry.spherical.computeOffset(midLoc2, offset / 2, heading + headingOffset);// Get the offset location of the mid point of midLoc and start LatLng

    // Draw poly line along above computed locations
    var curve = new google.maps.Polyline({
        path: [startLatLng, offsetLoc1, offsetLoc, offsetLoc2, endLatLng],
        geodesic: true,
        strokeColor: lineColor,
        strokeOpacity: 0.6,
        strokeWeight: 7
    });

    curve.setMap(map);

    // Add an arrow to the end of the curved line
    var arrow = new google.maps.Marker({
        position: newLoc,
        map: map,
        icon: {
            path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
            scale: 4,
            strokeColor: lineColor,
            strokeOpacity: 1,
            strokeWeight: 5.0,
            fillColor: 'transparent',
            fillOpacity: 0.6,
            rotation: google.maps.geometry.spherical.computeHeading(offsetLoc2, endLatLng)
        },
    });

}


Q:

import google-sample-code from github to java app

I would like to use the following function from google java-docs-samples in my code like this:
BigQueryUtils.getPages(...)

I added in pom.xml
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-bigquery</artifactId>
    <version>0.5.1</version>
</dependency>

and in my code:
import com.google.cloud.bigquery.samples;

public class MyClass {

  public static void method() {
    BigQueryUtils.getPages(...);
  }

i get this message:
 The import com.google.cloud.bigquery.samples cannot be resolved

how can I  import above libraries in my project?
EDIT
I also tried adding this on the pom, didnt help
    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>doc-samples</artifactId>
        <version>1.0.0</version>
    </dependency>

I get this message in the pom:
Missing artifact com.google.cloud:doc-samples:jar:1.0.0

A:

The samples/examples are not part of the Maven central repo. As per the documentation, you would need to build the project yourself, and then include the local jar file that is built if you want to use those classes/methods:

Clone/download the repo
cd to bigquery
mvn clean package -DskipTests
Include the jar in your project

Bear in mind though, that these are just samples/examples. I wouldn't be depending on them for building solutions. They exist purely to guide and get people started with the APIs.


Q:

basic for loop and write(line), joining strings

I am working on an assignment for school. These are my first attempts with Python. We are supposed to copy Juliet and Romeo into a new file but only with act and scene indications, keeping only Juliet and Romeos partitions. Here are my two issues: for some reason, sometimes it copies the title of the scene twice. Second issue, whenever J or R speaks, the partition must be shrunk to one line. Cannot seem to find my way into the problem.
Any help will be greatly appreciated.
my clean version, duplicity of indication
# opening files
orig = open('RomeoAndJuliet_clean.txt')
nohead = open('RomeoAndJuliet_cleanNoHeader.txt', 'w')
clean = open('theLovers.txt', 'w')

# declaring booleans
doIHaveToCopyTheLine=False
Romeo = False
Juliet = False
act = False
scene = False

# dissecting the play ##################################
orig = open('RomeoAndJuliet_clean.txt')
# creating the loop
for line in orig.readlines():
    # conserving the announcement of acts and scenes
    if 'ACT ' in line: # added a space so it doesn't copy a part of the    header "CONTRACT"
        act = True
    else:
        act = False
    if 'Scene' in line:
        scene = True
    else:
        scene = False
    # excluding the other characters of the play
    if '>>' in line:
        if 'Romeo' in line:
            Romeo = True
        else:
            Romeo = False

        if 'Juliet' in line:
            Juliet = True
        else:
            Juliet = False
    # assigning functions to the booleans
    if Juliet:
        clean.write(line)

    if Romeo:
        clean.write(line)

    if scene:
        clean.write(line+'\n')

    if act:
        clean.write(line+'\n')

nohead.close()
clean.close()
orig.close()

A:

you can combine conditions with or. That should eliminate the duplicates. Then, you may want to accumulate utterances of Romeo and Julia until neither of them says anything anymore, and then write the collected utterances to the file:
# opening files
orig = open('RomeoAndJuliet_clean.txt')
nohead = open('RomeoAndJuliet_cleanNoHeader.txt', 'w')
clean = open('theLovers.txt', 'w')

# dissecting the play ##################################
orig = open('RomeoAndJuliet_clean.txt')
act = False
scene = False
Romeo = False
Juliet = False
# creating the loop

condensed = ''    # This will accumulate the utterances of R and J until    neither of them speaks anymore

for line in orig.readlines():
    act == 'ACT ' in line           # added a space so it doesn't copy a part of the    header "CONTRACT"
    scene == 'Scene' in line

    if act or scene:
        clean.write(line+'\n')
        if condensed != '':
            clean.write(condensed)

    elif '>>' in line:
        Romeo == 'Romeo' in line
        Juliet == 'Juliet' in line
        if Romeo or Juliet:
            condensed += line + "\n"        # Add to the lines of R and J
        elif condensed != '':             # (that is, if there is anything at all to flush...)
            clean.write(condensed)
            condensed = ''              # Prepare for new utterances

if condensed != '':                         # Maybe there are left-over utterances?
    clean.write(condensed)

nohead.close()
clean.close()
orig.close()


Q:

Bluetooth frequency-hopping advantages

i'm learning now the about Bluetooth (and BLE) and feel I need some explanation what the advantages of using frequency-hopping method. Can anyone please explain me in simple words (with examples, please) what we earn from the frequency-hopping? i know it should minimize interference, but don't understand how and why.
Thanks!

A:

Frequency hopping radios have a bunch of possible carrier frequencies that they can use for communicating. The receiving end of the link has to hop in sync with the transmitter and this means being able to predict correctly where to "move" its carrier frequency and when. This is usually accomplished by a "table" held in software at each end and some mechanism for keeping in sync.
If the pair of radios "fail" to communicate on one particular hop, there is a mechanism that allows both to recover from this fail and, importantly, that particular hop frequency is "marked" as temporarily unsuitable. Thus there is an algorithm at both ends that causes the "table" to evolve.
The upshot is that both ends of the link are evolving a "hop" table and that table contains frequencies that are generally the best to use to avoid data loss from interferers.


Q:

Jquery Mobile align text box

I have the following listview with text boxes. I wanted to get the same feel as the ipad.
How do I align the text boxes so are right below one another. Currently it looks mismatched.

  First Name:
        <input type="text" name="fname" id="fname" value=""    />

  MI:
        <input type="text" name="mi" id="mi" value="" style="width:5%;"  />

A:

Don't know why you needed to set style for ul and input tags.
But I have put together a fiddle with different styling you can achieve.
http://jsfiddle.net/nachiket/nnRPv/
Does any one of it helps?


Q:

Check multiple OR operators in IF statement

I have the following C++ code:
if(x==y||m==n){
cout<<"Your message"<<endl;
}

If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".
Is there a way to print each "Your message" independently based on each condition using a single if statement?
The output would be identical to the below using multiple if statements.
if(x==y){
cout<<"Your message"<<endl;
}

if (m==n){
cout<<"Your message"<<endl;
}

A:

Not that I'd ever do it this way, but ...
for(int i = 0; i < (x==y)+(m==n); ++i) {
  std::cout << "Your message\n";
}

Let me expand on this. I'd never do it this way because it violates two principles:
1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.
2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.
Given these two principles, here is how I would actually code it:
if(x==y) {
  std::cout << "Your x-y message\n";
}
if(m==n) {
  std::cout << "Your m-n message\n";
}

Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.


Q:

SQL . Call midnight timestamp unix without having to enter it manually

I have a table with 4 columns value , animal_id, food_id and timestamp. Time stamp records the data in unix time. Currently my script is working fine and produces a table like this. This is all great and all but this forces me to go edit the file and change the timestamp each day for today's midnight timestamp and this is quite time consuming. Is there a way to produce this line of code for every day without having to update it ? Thank you in advance. I use oracle 10g.
The line in the script I want to change
WHERE timestamp BETWEEN 1406073600 AND (1406073600 + 86400)
The Script
SELECT MAX(value),animal_id, food_id
FROM farm1
WHERE timestamp BETWEEN 1406073600 AND (1406073600 + 86400)
group by animal_id, food_id ;

The Table Results
MAX(VALUE)  animal_id    food_id
---------- ---------- ----------
      9302          8       9081
      8015         10       9081

A:

You can convert a date to a Unix-style epoch timestamp number with:
(your_date - date '1970-01-01') * 60 * 60 * 24

... since the timestamp is the number of seconds since 1970-01-01.
So to run your query for all records yesterday (which your sample seems to be doing):
SELECT MAX(value),animal_id, food_id
FROM farm1
WHERE timestamp >= (trunc(sysdate - 1) - date '1970-01-01') * 60 * 60 * 24
AND timestamp < (trunc(sysdate) - date '1970-01-01') * 60 * 60 * 24
GROUP by animal_id, food_id ;

BETWEEN is inclusive so will catch both midnights, which could potentially lead to a value being included in two days' runs, or skewing the results for one of them. I've changed from that to explicit >= and < to make it inclusive. Or you could just subtract 1 from the later time of course, to make it 23:59:59.
SQL Fiddle demo (including a value being picked up from the wrong with your original query).


Q:

Mudar a cor de uma imagem no css (jquery)

Tenho uma imagem na minha página:

Em um momento da minha aplicação, várias mudanças no meu css são feitas para mudar totalmente a cor das coisas, invocando isso com chamadas jquery como segue abaixo:
 $("body").css({"background-color" : "black"});

Porém, também preciso fazer isso com essa imagem, mas um simples background-color não adianta.
Como posso mudar a cor seguindo esse padrão jQuery?

A:

Uma das técnicas simples que vc pode fazer e colocar a imagem em preto e branco e depois colocar uma película de cor por cima dela, usando cor rgba, ou Hexadecimal com transparência conforme vc achar melhor. Assim facilita para vc trocar os valores das cores depois com o jQuery ou JS.
Veja um exemplo da mesma imagem em várias cores apenas com CSS. Encapsulei a imagem em uma div e coloquei um filtro grayscale(100%) depois usando um pseudo elemento ::after na div eu coloquei uma película colorida por cima da imagem e usei um mix-blend-mode para fazer uma "mistura" entre a cor e a imagem.
Veja que no exemplo abaixo eu fiz um blend com "scree" e outro com "overlay", vc pode usar qualquer outro blend-mode e ainda ajustar o canal Alpha no cor rgba para ter um resultado melhor para cada tipo de imagem.
OBS: deixei uns comentários no CSS para te ajudar

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    line-height: 0;
}
div {
    display: inline-block;
    position: relative;
}
div[class] img {
    filter: grayscale(100%); /* filtro que deixa a imagem preto e branco */
}

div[class]::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
}
div.red::after {
    background-color: rgba(255, 0, 0, .5); /* .5 é onde vc contra a opacidade da cor rgbA*/
    mix-blend-mode: screen; /* aqui vc pode testar outrs filtros para ver o que da o melhor resultado para sua imagem*/
}
div.blue::after {
    background-color: rgba(0, 0, 255, .5);
    mix-blend-mode: overlay;
}

Documentação sobre os filtros de CSS: https://developer.mozilla.org/en-US/docs/Web/CSS/filter
Documentação sobre o Mix-Blend-Mode: https://developer.mozilla.org/pt-BR/docs/Web/CSS/mix-blend-mode


Q:

How do I make the Managed Navigation menu appear the same on all pages

Apologies if this is amazingly obvious somehere...
I've implemented a SP2013 Publishing Site and enabled the friendly URLs and Managed Navigation.  For what it's worth, I've also used the Starter Pages from Randy and opted for the HTML file option to do my branding.  This all appears to work nicely.
It seems that when you use the top navigation menu to drill down into a term/page, it will then appear empty and have no links.
Is it possible to have the same menu as the top level (with the dropdowns etc) appear on all pages?

A:

In the master page (HTML)... On the  tag there is a property called StartFromCurrentNode which when set to false achieves the same menu on all pages.

-->


Q:

Unable to successfully extract timestamp to date and time in pyspark

I am having trouble extracting the time and date from a timestamp. The data is read as a string, so I saw that people are able to use date_format to essentially convert it into the format we want. Here is what I tried below
import pyspark.sql.functions as F
from pyspark.sql.functions import date_format

data = df_data.select(date_format(F.col("timestamp"),"MM/d/yy").alias("date"),
        date_format(F.col("timestamp"),"HH:mm").alias("time"),
        date_format(F.col("timestamp"), "M/d/yy").alias("current_date_formated")).show(10)

My input data looks like this:

  timestamp
11/9/18 14:11
11/9/18 14:27
11/9/18 14:42
11/9/18 14:57

The output of my code above is spewed as under my date and time alias returns rows of null. I have also tried using to_date but didn't work either
import pyspark.sql.functions as F

data = df_data.select(date_format(F.col("timestamp"),"MM/d/yy").alias("date"),
        F.to_date(F.col("timestamp"),"HH:mm").alias("time"),
        F.to_date(F.col("timestamp"), "M/d/yy").alias("current_date_formated")).show(10)

A:

You have the right idea with date_format. The only thing your missing is it to first and foremost convert your string timestamp to Timestamp Type. And then you can do your formatting. I assumed your input data is in the format of day-month-year, if not, you can switch it to "MM/dd/yy HH:mm".
from pyspark.sql import functions as F
df.withColumn("timestamp", F.to_timestamp("timestamp","dd/MM/yy HH:mm"))\
  .withColumn("time",F.date_format("timestamp","HH:mm"))\
  .withColumn("current_date_formated",F.date_format("timestamp", "M/d/yy")).show()

+-------------------+-----+---------------------+
|          timestamp| time|current_date_formated|
+-------------------+-----+---------------------+
|2018-09-11 14:11:00|14:11|              9/11/18|
|2018-09-11 14:27:00|14:27|              9/11/18|
|2018-09-11 14:42:00|14:42|              9/11/18|
|2018-09-11 14:57:00|14:57|              9/11/18|
+-------------------+-----+---------------------+


Q:

Finding the number of times each word in a hashset occurs in text document

I'm implementing a Naive Bayes text classification algorithm in Java.
What I have done so far is, declare a hashset called Vocabulary which stores all the unique words from a given text file (test file).
One of the steps in the algorithm is to concatenate all the members of the test files into a single text file. This turns out to be a fairly big file with the words from each file.
Now, I have to count the number of occurrences of each word in the Vocabulary with the concatenated text file. My first guess is to keep a sort of an array structure which contains the frequencies of each word. But then again, I would have way too many entries.
Could anyone please give me better suggestions?

A:

Use a dictionary (HashMap) where the words are the keys and the values are the number of occurrences. If the HashSet fits into memory, HashMap should as well.


Q:

Component based entity system API naming problems

My engine uses a component-based entity system internally, and I want to bind it to Lua for scripting.
Now, I want to save people who write scripts for it typing work. In C++, to set the position of an entity, you'd do the following:
pEntity->GetComponent< CPoint >()->SetPos( Vector( X, Y ) );

That means, if I'd bind it to Lua 1:1 you'd also have to:
ent:GetComponent( CP_POINT ):SetPos( 123, 456 )

But let's be honest, would you want to type so much just to set an entities' position?
I don't think so, that's why I "hid" the component system from Lua:
Right now, what you do is
ent:SetPos( 123, 456 )

The component stuff is handled internally. You can still manually add and remove components from Lua with ent:AddComponent and ent:RemoveComponent, etc.
Now, this doesn't seem perfect either:

The Entity metatable gets cluttered because it has to take all functions of all components
Naming problems: ent:SetJointMotorEnabled() again seems kind of bad

Do you have any ideas how I could find a better naming scheme for component functions, without risking the scripting comfortability?

A:

We have a similar situtation in our project, and we solved the problem by saving components (not functions) to LUA metatables. Basically, when we are creating an entity (or game object as we call them) on LUA side, code looks something like:
function createShip()
    ...

    self.transform = registerToComponent("transform")
    self.sprite = registerToComponent("sprite")

    ...
end

Now, we can use simply
entity.transform:setPosition(5.2, 4.8)
entity.sprite:setTexture("ship.png")

to set position (and texture). And we are totally happy with this!
(And actually I think this is better than having just entity:setPosition and entity:setTexture since when you have lots of components, resulting entity API would be just a big mess.)

A:

The fundamental problem here is that you've exposed the component system to the API. You need to encapsulate that stuff behind your interface.


Q:

Choose between words “perverse” and “deviant”

I want to express the concept of a crowd of people with wrong idea of good and bad things (like people from some classical books who make principal characters abandon their love and so on). Can I use the expression perverse crowd or deviant crowd. I feel that something is wrong, because these words are usually used to refer to something sexually abnormal? What is a right adjective to use?

A:

Go ahead and use perverse. OED:

1.a. Of a person, action, etc.: going or disposed to go against what is reasonable, logical, expected, or required; contrary, fickle, irrational.
  . . .
  3. Obstinate, stubborn, or persistent in what is unreasonable, foolish, or wrong; remaining set in a course of action in spite of the consequences.

Yes, there is also this:

5 That is (regarded as) sexually perverted.

But sexual meanings and applications of a word need not always utterly swallow up all others.


Q:

Creating a shorten URL for products using Amazon advertising API

I'm using Amazon's API to browse for some products and I would like to generate an affiliate link for some of them.
I know I can get a normal affiliate link from the DetailPageURL field in the response (and that I can create one manually following the affiliate link format) but I would like to find an automated way to create a shorten URL for a product that contains my tag.
2 technical notes:

Shorten URLs are the ones Amazon provides that look like amzn.to/12345
I know I create these manually via the associates panel, but I'm looking for a way to get them using an API.

Thanks!

A:

Apparently this can be done using bit.y's API, as every Amazon URL shortened by bit.ly will get the amzn.to/{unique_id} format.


Q:

Error inserting data into AlwaysEncrypted column

Using the new AlwaysEncrypted feature, I encrypted a DateTime column in one of my tables and this is the error I'm getting when trying to insert a new date:
Message: [SqlException: Operand type clash: datetime2(7) encrypted with (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'TestDb') is incompatible with datetime encrypted with (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'TestDb') Statement(s) could not be prepared.]

I've been getting insertion errors for strings too, but after changing the data type from varchar(24) (for example) to nvarchar(max) everything worked smoothly. Any suggestions?

A:

Turns out it is an Entity Framework issue. So althought I initially used model first, the .NET DateTime was converted to a Sql datetime, but then EF uses Sql datetime2 for binding.
The wired thing is that I never got an error before converting the column to Always Encrypted. Why this never occurred before is still a mystery to me, but the sql below has solved my issue. I highly recommend running this before applying Always Encrypted to the column, just to avoid further errors:
ALTER TABLE [TestTable] ALTER COLUMN Dob datetime2


Q:

Goto the Nth Page

It is common to need to make a page selection interface. It typically looks like this:
prev 1 ... 3 4 [5] 6 7 ... 173 next

Which means there are totally 173 pages, and you are on the 5th page currently.
This challenge requires you take the total number of pages and the current page number as input, and output a string (or an array) to "display" the page selector.
Input
2 positive integers

current page number
count of pages

It is guaranteed that 1 <= current <= total.
Output
Output a string or an array which represent the ui for page selectors.

If output as string, a single space (U+0020) should be used between each pages.
If output as an array, the array should produce same result as the string after convert each item to string and join them with a single space.

The three dots (...) is not optional for array output.

Details

If current == 1, no "prev" will be outputted, otherwise, "prev" comes first.
If current == total, no "next" will be outputted, otherwise, "next" comes last.
The first page (1) and the last page (total) should always be outputted.
The current page, (current - 1) page, (current - 2) page, (current + 1) page, (current + 2) page should be outputted as long as the are in the range of [1..total].
No other pages numbers should be outputted.
Pages outputted should be sorted in ascending order.
Output should not contain duplicate page numbers.
Current page should be highlighted by wrap it in a pair of [].
If there is a gap between any neighbors, three dots (...) should be inserted.

Test Cases
Current Total    Output
1       1        [1]
1       2        [1] 2 next
1       10       [1] 2 3 ... 10 next
3       3        prev 1 2 [3]
3       6        prev 1 2 [3] 4 5 6 next
4       6        prev 1 2 3 [4] 5 6 next
4       7        prev 1 2 3 [4] 5 6 7 next
3       10       prev 1 2 [3] 4 5 ... 10 next
5       10       prev 1 ... 3 4 [5] 6 7 ... 10 next
10      10       prev 1 ... 8 9 [10]
52      173      prev 1 ... 50 51 [52] 53 54 ... 173 next

Rules

This is code-golf, the shortest code wins!

A:

JavaScript (ES6), 130 122 121 bytes
Invoke with currying syntax, e.g. f(3)(10).
x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_)

f=

x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_)

console.log(f(1)(1))
console.log(f(1)(2))
console.log(f(1)(10))
console.log(f(3)(3))
console.log(f(3)(6))
console.log(f(4)(6))
console.log(f(4)(7))
console.log(f(3)(10))
console.log(f(5)(10))
console.log(f(10)(10))
console.log(f(52)(173))

Try it online!
-1 byte (Arnauld): Set X to X-x.

A:

Retina, 125 113 109 107 bytes
.+
$*
r`1\G
 1$'
¶

O`1+
\b(1+) \1\b
[$1]
 .* (1+ 1+ \[)|(] 1+ 1+) .*
$2 ... $1
^1
prev 1
1$
1 next
1+
$.&

Try it online! Link includes test cases. Saved 12 bytes thanks to @MartinEnder. Explanation:
.+
$*

Convert to unary.
r`1\G
 1$'

Generate all the page numbers in reverse order.
¶

Delete the newline separating the input. (There's also a space there from the page number generation anyway.)
O`1+

Sort the pages back into ascending order. This also sorts the current page, which is now duplicated.
\b(1+) \1\b
[$1]

Unduplicate and wrap []s around the current page.
 .* (1+ 1+ \[)|(] 1+ 1+) .*
$2 ... $1

Add an ellipsis if the current page is at least 5, or if there are at least 4 pages after the current page. (Note trailing space, to avoid including the last page in the ellipsis.)
^1
prev 1

Add the prev if the current page is not 1.
1$
1 next

Add the next if the current page is not the last page.
1+
$.&

Convert back to decimal.

A:

6502 machine code (C64), 160 bytes
00 C0 20 9B B7 86 FB CA F0 01 CA 86 FD 20 9B B7 86 FC A6 FB E8 E4 FC B0 01 E8
86 FE A2 01 E4 FB F0 1A A9 91 A0 C0 20 1E AB A2 02 E4 FD B0 0D A9 2E 20 D2 FF
CA 10 FA 20 3F AB A6 FD 86 9E E4 FB D0 05 A9 5B 20 D2 FF A9 00 20 CD BD A6 9E
E4 FB D0 05 A9 5D 20 D2 FF 20 3F AB A6 9E E4 FC F0 25 E4 FE F0 05 E8 86 9E D0
D5 E8 E4 FC F0 0D A2 02 A9 2E 20 D2 FF CA 10 FA 20 3F AB A6 FC A9 00 20 CD BD
20 3F AB A6 FC E4 FB F0 07 A9 99 A0 C0 20 1E AB 60 50 52 45 56 20 31 20 00 4E
45 58 54 00

Online demo -- Usage: sys49152,[current],[total], e.g. sys49152,5,173.
The numbers must be in the range [1..255] with current <= total. As this wasn't specified otherwise, this is the "natural" unsigned integer range on an 8bit processor.

Explanation as commented disassembly listing:
         00 C0       .WORD $C000        ; load address
.C:c000  20 9B B7    JSR $B79B          ; read 8bit integer
.C:c003  86 FB       STX $FB            ; store current page
.C:c005  CA          DEX                ; calculate lower start for ...
.C:c006  F0 01       BEQ .stl
.C:c008  CA          DEX
.C:c009   .stl:
.C:c009  86 FD       STX $FD            ; ... range and store
.C:c00b  20 9B B7    JSR $B79B          ; read 8bit integer
.C:c00e  86 FC       STX $FC            ; store total pages
.C:c010  A6 FB       LDX $FB            ; load current page
.C:c012  E8          INX                ; calculate upper end for ...
.C:c013  E4 FC       CPX $FC
.C:c015  B0 01       BCS .stu
.C:c017  E8          INX
.C:c018   .stu:
.C:c018  86 FE       STX $FE            ; ... range and store
.C:c01a  A2 01       LDX #$01           ; check whether first page is current
.C:c01c  E4 FB       CPX $FB
.C:c01e  F0 1A       BEQ .sequence      ; then directly to sequence
.C:c020  A9 91       LDA #<.prev        ; output string for ...
.C:c022  A0 C0       LDY #>.prev
.C:c024  20 1E AB    JSR $AB1E          ; ... "prev 1 "
.C:c027  A2 02       LDX #$02           ; check whether page 2 is in range ...
.C:c029  E4 FD       CPX $FD
.C:c02b  B0 0D       BCS .sequence      ; ... then directly to sequence
.C:c02d  A9 2E       LDA #$2E           ; load character '.'
.C:c02f   .ellip1:
.C:c02f  20 D2 FF    JSR $FFD2          ; output ...
.C:c032  CA          DEX
.C:c033  10 FA       BPL .ellip1        ; ... 3 times
.C:c035  20 3F AB    JSR $AB3F          ; output space
.C:c038  A6 FD       LDX $FD            ; load lower start for range
.C:c03a   .sequence:
.C:c03a  86 9E       STX $9E            ; store to temporary
.C:c03c   .seqloop:
.C:c03c  E4 FB       CPX $FB            ; compare with current
.C:c03e  D0 05       BNE .notcurrent1   ; yes -> output '['
.C:c040  A9 5B       LDA #$5B
.C:c042  20 D2 FF    JSR $FFD2
.C:c045   .notcurrent1:
.C:c045  A9 00       LDA #$00
.C:c047  20 CD BD    JSR $BDCD          ; output number
.C:c04a  A6 9E       LDX $9E            ; compare with current
.C:c04c  E4 FB       CPX $FB
.C:c04e  D0 05       BNE .notcurrent2   ; yes -> output ']'
.C:c050  A9 5D       LDA #$5D
.C:c052  20 D2 FF    JSR $FFD2
.C:c055   .notcurrent2:
.C:c055  20 3F AB    JSR $AB3F          ; output space
.C:c058  A6 9E       LDX $9E
.C:c05a  E4 FC       CPX $FC            ; compare position with last page
.C:c05c  F0 25       BEQ .printnext     ; if eq jump to part printing "next"
.C:c05e  E4 FE       CPX $FE            ; compare position to upper end of range
.C:c060  F0 05       BEQ .printellip2   ; if eq jump to part printing "..."
.C:c062  E8          INX
.C:c063  86 9E       STX $9E            ; next number
.C:c065  D0 D5       BNE .seqloop       ; and repeat loop for sequence
.C:c067   .printellip2:
.C:c067  E8          INX
.C:c068  E4 FC       CPX $FC            ; compare next number with last page
.C:c06a  F0 0D       BEQ .printlast     ; if eq jump to part printing page num
.C:c06c  A2 02       LDX #$02
.C:c06e  A9 2E       LDA #$2E           ; load character '.'
.C:c070   .ellip2:
.C:c070  20 D2 FF    JSR $FFD2          ; output ...
.C:c073  CA          DEX
.C:c074  10 FA       BPL .ellip2        ; ... 3 times
.C:c076  20 3F AB    JSR $AB3F          ; output space
.C:c079   .printlast:
.C:c079  A6 FC       LDX $FC            ; output last page number
.C:c07b  A9 00       LDA #$00
.C:c07d  20 CD BD    JSR $BDCD
.C:c080  20 3F AB    JSR $AB3F          ; output space
.C:c083   .printnext:
.C:c083  A6 FC       LDX $FC            ; compare current page with last page
.C:c085  E4 FB       CPX $FB
.C:c087  F0 07       BEQ .done          ; if eq nothing else to do
.C:c089  A9 99       LDA #<.next        ; output string for ...
.C:c08b  A0 C0       LDY #>.next
.C:c08d  20 1E AB    JSR $AB1E          ; "next"
.C:c090   .done:
.C:c090  60          RTS
.C:c091   .prev:
.C:c091  50 52 45 56 .BYTE "prev"
.C:c095  20 31 20 00 .BYTE " 1 ", $00
.C:c099   .next:
.C:c099  4E 45 58 54 .BYTE "next"
.C:c09d  00          .BYTE $00


Q:

Can I directly stream from HttpResponseMessage to file without going through memory?

My program uses HttpClient to send a GET request to a Web API, and this returns a file.
I now use this code (simplified) to store the file to disc:
public async Task<bool> DownloadFile()
{
    var client = new HttpClient();
    var uri = new Uri("http://somedomain.com/path");
    var response = await client.GetAsync(uri);

    if (response.IsSuccessStatusCode)
    {
        var fileName = response.Content.Headers.ContentDisposition.FileName;
        using (var fs = new FileStream("C:\test\" + fileName, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            await response.Content.CopyToAsync(fs);
            return true;
        }
    }

    return false;
}

Now, when this code runs, the process loads all of the file into memory. I actually would rather expect the stream gets streamed from the HttpResponseMessage.Content to the FileStream, so that only a small portion of it is held in memory.
We are planning to use that on large files (> 1GB), so is there a way to achieve that without having all of the file in memory?
Ideally without manually looping through reading a portion to a byte[] and writing that portion to the file stream until all of the content is written?

A:

It looks like this is by-design - if you check the documentation for HttpClient.GetAsync() you'll see it says:

The returned task object will complete after the whole response
  (including content) is read

You can instead use HttpClient.GetStreamAsync() which specifically states:

This method does not buffer the stream.

However you don't then get access to the headers in the response as far as I can see. Since that's presumably a requirement (as you're getting the file name from the headers), then you may want to use HttpWebRequest instead which allows you you to get the response details (headers etc.) without reading the whole response into memory. Something like:
public async Task<bool> DownloadFile()
{
    var uri = new Uri("http://somedomain.com/path");
    var request = WebRequest.CreateHttp(uri);
    var response = await request.GetResponseAsync();

    ContentDispositionHeaderValue contentDisposition;
    var fileName = ContentDispositionHeaderValue.TryParse(response.Headers["Content-Disposition"], out contentDisposition)
        ? contentDisposition.FileName
        : "noname.dat";
    using (var fs = new FileStream(@"C:\test\" + fileName, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        await response.GetResponseStream().CopyToAsync(fs);
    }

    return true
}

Note that if the request returns an unsuccessful response code an exception will be thrown, so you may wish to wrap in a try..catch and return false in this case as in your original example.


Q:

Android download - using output stream approach

        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;
        // return "Server returned HTTP " + connection.getResponseCode()
        // + " " + connection.getResponseMessage();

        // download the file
        input = connection.getInputStream();
        output = new FileOutputStream(IRConstant.issueFolder(y, m, d, i) + "/" + parms[0].currPage + ".zip");

        Log.d (TAG,"output: " + output);

        byte data[] = new byte[1024];
        int count;
        while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
        }

The above code is how I implement the download function, the problem is , how to set it to overwrite the existing file if there is a file aleready exist which specific by the output stream ? thanks

A:

Try to use another constructor:
public FileOutputStream (File file, boolean append)

Constructs a new FileOutputStream that writes to file. If append is true and the file already exists, it will be appended to; otherwise it will be truncated. The file will be created if it does not exist.
But I think that the default constructor is already overwriting the existing file
public FileOutputStream (String path)

Constructs a new FileOutputStream that writes to path. The file will be truncated if it exists, and created if it doesn't exist.


Q:

Trying to remove categories only if the categories dont have subcategories

I have categories and subcategories and Im trying to do a system like if I want to remove a category I only can do that if I remove my subcategories first.
My subcategories have the id_father of the categories.
Like this:
(Warnings and Technology are the Categories)

My Problem:
When I remove a category with subcategories not appear my error message that I have in code below (This category has subcategories) and the category  is in fact removed from my database.
I have reviewed the code many times but I can not understand where the error is.
Can you please give me a little help?
My php code:
if(!empty($_GET['deleteCategory']))
    {
     $idDel = $_GET['deleteCategory'];
     $readDeleteCategory = $pdo->prepare("SELECT * FROM categories where id_father = ?");
     $readDeleteCategory->bindValue(1, $idDel);
     $num_rows_ReadDeleteCategory = $readDeleteCategory->rowCount();
     //if dont return results we have the delete and show the message
    if(! $num_rows_ReadDeleteCategory >=1)
        {
        $deleteCategory = $pdo->prepare("DELETE FROM categories WHERE id =?");
        $deleteCategory->bindValue(1,$idDel);
        $deleteCategory->execute();
        echo 'category removed with sucess.';
            }
    else
        {
        echo 'This category has subcategories. Remove subcategories first.';
        }
     }

if(!empty($_GET['deleteSubcategory']))
    {
    $idDel = $_GET['deleteSubcategory'];
    $deleteCategory = $pdo->prepare("DELETE FROM categories WHERE id =?");
    $deleteCategory->bindValue(1,$idDel);
    $deleteCategory->execute();
    echo 'Category removed with sucess.';
    }

A:

I think you're just missing a simple line.
 $readDeleteCategory->bindValue(1, $idDel);
 $readDeleteCategory->execute();
 $num_rows_ReadDeleteCategory = $readDeleteCategory->rowCount();


Q:

How to make a Windows CLI from a Mac

Wondering how to make a command-line interface / tool on a Mac that works on Windows. I know you can create an exe from the entire node.js repo, but I'm wondering how to do this at a lower level. Writing some C library and compiling with VisualStudio perhaps. Wondering what a hello world CLI (something that just prints hello world to the terminal) would look like for Windows, when compiling/testing from a Mac.

A:

To produce a Windows executable on a Mac you need a cross-compiler. You can use either Brew or MacPorts to install MinGW (or MinGW-w64 for x86_64 binaries) toolchain.
See "Install MinGW-w64 using Brew" or select the required port from this list.
After installing, you will have the 'i686-w64-mingw32-gcc' binary and installed C run-time library, so that you may compile your 'app.c' file with
/path/to/i686-w64-mingw32-gcc -o app.exe app.c

command.
As a starter, I would use a "Hello, World" test like
#include <stdio.h>
int main() { return printf("Hello, world!\n"); }

If your CLI tool depends on third-party libraries, you would have to compile all libraries using 'i686-w64-mingw32-gcc' compiler (this usually requires some library-specific setup in each case).
To quickly debug some platform-independent things you may either compile the same app for MacOS or run compiled .exe file with Wine emulator.


Q:

How to install extensions in Magento on SSH

How do I install a Connect 2.0 extension to my local development box without using the /downloader UI? How can I script this in a deployment routine?

A:

rm -rf var/cache var/session
chmod 550 ./mage
./mage mage-setup .
./mage config-set preferred_state stable
/*This link you get from Magento Connect*/
./mage install http://connect20.magentocommerce.com/community Mage_All_Latest --force


Q:

selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally with ChromeDriver Chrome and Selenium

I am trying to run a webscraper on a linux server. The full error is below
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.10.267518,platform=Linux 4.4.0-141-generic x86_64)

I have seen similar questions asked on stackoverflow, the solutions are to include the '--headless' and '--no-sandbox' arguments. However, I am already doing this.
I am able run this code locally, however, I am unable to make it work on the server.
I have also checked to see that everything is up to date, and everything is.
ChromeDriver 2.10.267518
selenium     3.141.0

Here is the code snippet where the error occurs.
options.add_argument('--headless')
options.add_argument('--no-sandbox')

caps = DesiredCapabilities.CHROME
caps['loggingPrefs'] = {'performance': 'ALL'}

driver = webdriver.Chrome(options=options, desired_capabilities=caps, executable_path='/usr/local/bin/chromedriver')

I have also tried to run the above code without the executable_path option but I still get the same error.

A:

I was using a config file that was setting the header value to True, so the code was trying to run with a browser and failing. This was a stupid mistake but I'm posting the solution anyway in case it helps someone.
I also had to remove the line below
options.add_argument('--no-sandbox')

and change this line
options.add_argument('--headless')

to
options.add_argument('headless')


Q:

Querying on a pointer Parse with Swift

So here is the result im trying to achieve i have 2 classes one is Parses User class , and the other is called Content. I am querying Content lets say if A matches B i want to get the appropriate username from the User class and the photo.
Any help would be greatly appreciated

A:

What I get from your description is sender is the property of Content class and username is the User class and you are trying to get the Content of a particular user
PFQuery *query = [PFQuery queryWithClassName:@"Content"];
[query whereKey:@"sender" equalTo:[PFUser currentUser]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    for (PFObject *content in objects)
    {
        // getting the user who created the Content
        PFObject *user = [content objectForKey:@"file"];

        PFFile *imageFile = [user objectForKey:@"photo"];
        [imageFile getDataInBackgroundWithBlock:^(NSData *result, NSError *error) {
            if (!error)
            {
                UIImage *image = [UIImage imageWithData:result];
                imageView.image = image;
            }
         }];
    }
}];

Let me know if you have any questions.


Q:

Localized XML files

I have an XML file in English that I translated into Italian and French.
In my project xcode4 I have added them but because the files have the same name I do not know how to call them from code.
For strings there is NsLocalizedString but for files how do you accomplish this?

A:

See the NSBundle reference:

pathForResource:ofType:
Returns the full pathname for the resource identified by the specified name and file extension.
The method first looks for a matching resource file in the non-localized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics.

(emphasis added)
So you’d use:
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"xml"]

Provided that your files are localized using the localization tool in Xcode’s file inspector which automatically puts the files into the correct *.lproj folder.


Q:

React unexpected number rendered

I have the following React example, and I'm trying to show a success toast (from mdbootstrap library) every time the isShowing state is true.  This works as expected regarding the toast, but a number is displayed next to the button, and increments after each click. This number also appears as a children of the main div from the App file ( See attached image and codesandbox link) .
Thanks in advance!
import React, { Component } from "react";
import Nav from "./Navbar";
import Routes from "./Routes";
import Mes from "./Message";
import { Button, toast } from "mdbreact";
import "./App.css";

class App extends Component {
  state = {
    isShowing: false
  };

  handleClick = () => {
    this.setState({
      isShowing: true
    });
  };

  render() {
    return (

        <Mes />
        <Button color="primary" onClick={this.handleClick}>
          show Alert{" "}
        </Button>
        {this.state.isShowing ? toast.success("Success message") : ""}
        <Routes />

    );
  }
}

export default App;

codesandbox link : https://codesandbox.io/s/l2xqplx4rm

A:

You don't need to render toast.success in your code. Remove
{this.state.isShowing ? toast.success("Success message") : ""}

In above code case your binding the toast's toast.success methods response which is nothing but the active toast length. So its displaying number over there.
Just below code is enough to show toast on button click.
import React, { Component } from "react";
import Nav from "./Navbar";
import Routes from "./Routes";
import Mes from "./Message";
import { Button, toast } from "mdbreact";
import "./App.css";

class App extends Component {

  handleClick = () => {
     //show toast
     toast.success("Success message");
  };

  render() {
    return (

        <Mes />
        <Button color="primary" onClick={this.handleClick}>
          Show Alert
        </Button>
        <Routes />

    );
  }
}

export default App;

Here is updated code


Q:

Check if column has same value for a client group

I have a table like the below and want to identify duplicate referrals
Client      Team                Referred Date

client1     Referred Team1      2016-02-16
client1     Referred Team1      2016-02-16
client1     Referred Team1      2016-02-16
client1     Referred Team1      2016-01-28
Client2     Referred Team4      2015-07-03
Client2     Referred Team4      2015-07-03
Client3     Referred Team7      2015-04-09
Client3     Referred Team7      2015-04-09
Client3     Referred Team7      2015-04-09
Client3     Referred Team2      2016-09-28
Client3     Referred Team1      2016-10-20
Client4     Referred Team8      2016-11-18

My query so far below, but i dont seem to get the desired result
SELECT
ClientId
,Team
,COUNT(*) as DuplicateCount

FROM MyData
group by
ClientId
,Team
having COUNT(*) >1

I would like  the below result
Client      Team                Duplicate Count (Times referred to the same team)

client1     Referred Team1      4
Client2     Referred Team4      2
Client3     Referred Team7      3
Client4     Referred Team8      1

thanks in advance

A:

you can use row_number and subquery as below
 Select top (1) with ties * from (
     Select Client, Team , Cnt = Count(ReferredDate)
         from yourtable
         group by Client, Team ) a
     order by row_number() over(partition by Client order by cnt desc)


Q:

Adding created_at and updated_at to LOAD DATA INFILE data

I have a table that I'm planning to populate from a CSV file. The file includes 22 columns and the table includes 24. The differences are created_at and updated_at fields at the end of the column list.
What I really want to happen is for each record to be created and for the last 2 columns to be defaulted.
I added the columns like so:
ALTER TABLE mytable
  ADD created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  ADD updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
;

My loader script looks like this:
LOAD DATA LOCAL INFILE '/tmp/my.csv'
    REPLACE INTO TABLE mytable
    CHARACTER SET utf8
    FIELDS TERMINATED BY ','
           OPTIONALLY ENCLOSED BY '"'
    IGNORE 1 LINES
;

What I'd like, of course, is for the created_at and updated_at value to get set when a new record is inserted. If a record is ever replaced, the updated_at value should be replaced?
Possible? I'm using MariaDB 10.0.26 and both dates are always created with values of 0000-00-00 00:00:00.

A:

Perhaps...
Changelog for 10.0.1
Skip down to "MDEV-452", where it says:

MDEV-452 Add full support for auto-initialized/updated timestamp and datetime
Generalized support for auto-updated and/or auto-initialized timestamp and datetime columns. This patch is a reimplementation of MySQL's "WL#5874: CURRENT_TIMESTAMP as DEFAULT for DATETIME columns". In order to ease future merges, this implementation reused few function and variable names from MySQL's patch, however the implementation is quite different.
TODO: The only unresolved problem in this patch is the semantics of LOAD DATA for TIMESTAMP and DATETIME columns in the cases when there are missing or NULL columns. I couldn't fully comprehend the logic behind MySQL's behavior and its relationship with their own documentation, so I left the results to be more consistent with all other LOAD cases.
The problematic test cases can be seen by running the test file function_defaults, and observing the test case differences. Those were left on purpose for discussion.

If you feel that there is still an issue with MariaDB, file a bug there.


Q:

Python check for word in list

I'm writing a spell checking function and I'm using two text files: one that has misspelled text and a text file with a bunch of words from the dictionary. I have turned the text of misspelled words into a list of strings and the text file with dictionary words into a list of words. Now I need to see if the words in my misspelled list are in my list of dictionary words.
def spellCheck():
    checkFile=input('Enter file name: ')
    inFile=open(checkFile,'r')

# This separates my original text file into a list like this
# [['It','was','the','besst','of','times,'],
# ['it','was','teh','worst','of','times']]

    separate=[]
    for line in inFile:
        separate.append(line.split())

# This opens my list of words from the dictionary and
# turns it into a list of the words.

    wordFile=open('words.txt','r')
    words=wordFile.read()
    wordList=(list(words.split()))
    wordFile.close()

# I need this newList to be a list of the correctly spelled words
# in my separate[] list and if the word isn't spelled correctly
# it will go into another if statement...

    newList=[]
    for word in separate:
        if word in wordList:
            newList.append(word)
    return newList

A:

Try this:
newList = []
for line in separate:
    for word in line:
        if word in wordList:
            newList.append(word)
return newList

The problem you had was that you were iterating over separate, which is a list of lists. There does not exist any list in your wordList, which is why that if-statement always fails. The words that you want to iterate over are in the sublists contained in separate. So, you can iterate over these words in a second for-loop. You can also use for word in itertools.chain.from_iterable(separate).
Hope this helps


Q:

Wrong behaviour of wrapfigure environment when using "placement = outer"

I'm trying to place some pictures inside my text using the wrapfig package of Donald Arseneau with KOMAscript of Markus Kohm. The intention is to place the pictures partly in the margin area at the outer side of a twosided document.
According to the package documentation I have to set the placement parameter value to the capital letter O to gain the outside edge–far from the binding, and the overhang parameter to a value of how much the figure should hang out into the margin.
That's what I have done in the attached minimum working example. As you can see in the attached picture, this works fine on odd pages, but the picture is misplaced on even pages.
Additional it seems that the overhang parameter -- different from the manual's description -- specifies the value how much the figure should hang into the text (not the margin).
Is it my fault, or a bug in the package?
\documentclass[twoside]{scrartcl}

\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{blindtext}

\begin{document}

\section{Hello, World!}
\Blindtext

\begin{wrapfigure}{O}{1cm}
    \includegraphics[width=3cm]{qr}
\end{wrapfigure}
\Blindtext

\blindtext

\begin{wrapfigure}{O}{1cm}
    \includegraphics[width=3cm]{qr}
\end{wrapfigure}
\Blindtext

\end{document}

A:

I can make out that you have seen the manual, but still have a look at this:

Now in this:
\begin{wrapfigure}{O}{1cm}

you haven't specified the overhang but the width as 1cm and putting a picture of width=3cm.
Let us correct it:
\begin{wrapfigure}{O}[1cm]{3cm}

Here overhang is 1cm and total width is 3cm.
The code:
\documentclass[twoside]{scrartcl}

\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{blindtext}

\begin{document}

\section{Hello, World!}
\Blindtext

\begin{wrapfigure}{O}[1cm]{3cm}
    \includegraphics[width=3cm]{example-image-a}
\end{wrapfigure}
\Blindtext

\blindtext

\begin{wrapfigure}{O}[1cm]{3cm}
    \includegraphics[width=3cm]{example-image-b}
\end{wrapfigure}
\Blindtext

\end{document}


Q:

Can a US city charge money for people wanting to live there?

For example,
A mayor may say, only residents can vote. And each resident must pay $20k to buy residency at market price.
Can a mayor do that?
In general, is it possible that a city is "privatized" like malls? In private malls, the malls decide who can be a tenant on those malls right. Can a city be like that?
For example, can an experimental city levy "poll taxes" or give resident dividend?
Say a city is filled with ancaps. Say those ancaps want only ancaps to be able to vote for cities' policy. They may want to say, you know, this city is privately owned and only shareholders can stay. Hence, only those who think ancap is so good they're willing to pay $20k for it stay in the city.

A:

I know the Reedy Creek Improvement District (AKA the part of Disney World that is managing utility services, building codes and inspections, and emergency services) keeps tight control on the "city" government by basically making it a company town.  Only Disney Employees and their families live there and can thus vote.  I'm not sure what the rule for purchasing these houses are (I had an employee friend sneak me behind the parks to see one neighborhood... it's very well hidden) so I don't know if they charge people for the houses.   RCID can do this because they lobbied the State of Florida to give them wide berth in the law to such an extent that they only pay property taxes and submit to elevator inspections when interacting with the state... everything else is governed by local laws (At the time the group of companies asking for this exemption lobbied Florida, FL wasn't aware they were all owned by Disney... and now a days they tend to not threaten Disney with regulations because they're bringing in the tourist dollars, which is where Florida gets a good deal of its taxes from.

A:

A major may say, only residents can vote.

Isn't that the case already?

And each resident must pay $20k to buy residency at market price.
Can a major do that?

Not arbitrarily like that. They'd expose themselves to anti-discrimination laws in some form or another.

Can a US city charge money for people wanting to live there?

That's de facto the case already, owing to property taxes.


Q:

Type function from type T to type integral where sizeof(integral) >= sizeof(T)

I want a type function, that takes a type T and returns the smallest integral type I satisfying sizeof(I) >= sizeof(T).
Any thoughts, insights, or comments about how to approach this? C++11 is available, thoughts with C++14 are welcome.
For the curious:
I'm working through elements of programming.
I have a function which maps from a group, like int, to itself. Let x be in the domain of the function and y be obtained by applying f to x some number of times. I want to know how many times I have to apply my function to x before I get y. This value is called the distance, and is some integer. If the group type is specified in k bits, the total number of distinct values is pow(2,k). The total number of possible jumps between elements is then pow(2,k) - 1. So an integral type with the same size as the group type is sufficiently large to hold all the possible distances that this distance function could return.

A:

This should do it:
template<typename T>
struct identity {
    typedef T type;
};

template<typename T, typename Head, typename... Tail>
struct best_type {
    typedef typename std::conditional<
        sizeof(Head) >= sizeof(T),
        identity<Head>,
        best_type<T, Tail...>
    >::type::type type;
};

template<typename T>
struct type_to_integral {
    typedef typename best_type<T, uint8_t, uint16_t, uint32_t, uint64_t, uint_least64_t>::type type;
};

Live demo here.


Q:

Homomorphism into Kneser  graphs  $KG(n, k)$

Is there a characterization of graphs $G$ such that $\exists$ $\phi : G \rightarrow KG(n,k)$,  where $KG(n,k)$ is the Kneser graph ($k  \leq  \lceil \frac{n}{2}\rceil $).
Any references on the subject will be appreciated.

A:

Homomorphisms into Kneser graphs are another way of describing fractional colourings; an introduction to how this all works is the topic of one of the chapters in my favourite book on Algebraic Graph Theory. There are other much more detailed references on fractional colourings, but not necessarily from the homomorphism viewpoint.
But just as there is no useful "characterization" of, say, graphs with 3-colourings (unless P=NP) there is no characterization of graphs with a given fractional chromatic number (except for a few trivial cases).


Q:

Android: Encoded Camera Preview Frames always in landscape. How to rotate?

Goal: Streaming Android Camera to Wowza Server in proper orientation no matter the orientation of device (i.e. the video is always right side up)
I've looked at all the questions on here regarding camera orientation and so far they all seem to just change the preview which is rendered to the screen or set a flag in the MP4 file (not appropriate for my use case: streaming).
I'm streaming camera frames to a Wowza server and on the Wowza server the received video is always landscape. This is fine if the phone is always held in the same orientation but I can't guarantee my users will do this. From what I've gathered, when you grab frames directly from the camera and feed them to the encoder, you are getting the natural orientation of the device's camera (which may be mounted landscape in my case) and this is completely unaffected by the preview. This is problematic because if the device is rotated during the stream, the image is rotated with it.
I have tried using openGL matrix to transform the preview in a custom GLSurfaceView.Renderer and all it does is transform the View on the screen, not the frames sent to the encoder.
I have read over Grafika's examples and am not sure where in the process I need to rotate frames before they are fed to the encoder. I am using a SurfaceTexture as a camera preview which is then rendered to a GLSurfaceView (and using my own custom GLSurfaceView.Renderer).
How can I rotate the frames to the encoder?
Ideally I would do this in openGL. I had thought about rotating the frames before filling mediacodec.dequeueInputBuffer buffers but this will be done using the CPU and I'm wary because of the real-time application. Maybe I am overlooking something with regards to the preview. I've seen other broadcasting applications tear down the Preview layer on the UI and rebuild it whenever the device is rotated.
References:
https://github.com/Kickflip/kickflip-android-sdk/
https://github.com/google/grafika

A:

The camera Activities in Grafika render every frame twice: once for the display, and once for encoding.  You want to do the same thing, but throw in a rotation (and make an appropriate adjustment to the MediaCodec / MediaRecorder configuration, i.e. 720x1280 vs. 1280x720).
For example, consider the drawFrame() method in ContinuousCapture.  It selects the SurfaceView's EGLSurface, draws, then switches to the video encoder's EGLSurface and calls the same draw method.  It even throws in a call to drawExtra() just to show that it can.
In both cases you're just rendering GLES onto an EGLSurface, and the EGLSurface gets its dimensions from the underlying Surface, which either came from SurfaceView or MediaCodec.  If you modify FullFrameRect#drawFrame() to take a matrix argument, and pass in a rotation matrix in place of the identity matrix it currently uses, you should get the result you want.


Q:

Editing PDF with XPDF (or with something else)

I would like to ask if it is possible to edit PDF files using the xpdf library and if yes how? I guess this is possible but i could not find any tutorial nor documentation for xpdf so i have realy no idea :( . I'm also open for using another library if any other has support for pdf editing. My only requirement for such library is that it has to be a C++ library or at least a C one and has to be cross-platform (Windows and Linux)
I Only need basic editing of a pdf file for example:

"this is a text in a pdf document" would be changed to "this is a text in pdf" with a different text color as well.

Thanks for all your replies!

A:

Just so you understand the scope of what you're getting into, "basic editing" of PDF content is nearly always non-trivial.
Page content in PDF is represented by short RPN programs that paint on the page.  It's a small language similar to PostScript in semantics, but without looping structures or function definitions (so there is no halting problem).  In a sane world, your text on the page is going to be represented by something like this:
BT /F1 12 Tf 72 720 Td (this is a text in a pdf document) Tj ET

which when translated into something more familiar, is this:
BeginText();
SetFont(F1, 12.0);  // Font 1, 12.0 pt
TextMoveTo(72, 720);
ShowText("this is a text in a pdf document");
EndText();

So in this case, you have to transform this into something like this:
BeginText();
SetFont(F1, 12.0);  // Font 1, 12.0 pt
TextMoveTo(72, 720);
ShowText("this is a ");
SetFont(F2, 12);
ShowText("text");
SetFont(F1, 12);
ShowText(" in a pdf document");
EndText();

which would become:
BT /F1 12 Tf 72 720 Td (this is a ) Tj /F2 12 Tf (text) Tj /F1 12 Tf
( in a pdf document) Tj ET

in the equivalent PDF.  The problem is many-fold:

You have to extract out the page and all its resources (non-trivial)
You have to generate a new page, inserting new resources (you're adding a new font), embedding the font if allowable
Alter the content stream of the page to include your changed content.

And 3 is where you're going to get hung up, because there are an infinite number of ways to generate a page that has the content you describe and even with a decent library, you're going to have a hard time getting maybe 70% of them.  Let me briefly describe why this is as bad as it sounds.  There are PDF generation programs (I'm looking at you, troff) that lay all the plain text on a page first, then lay all the italic text, then all the bold text.  I swear, I'm not making this up.  Some programs want to lay text down very precisely, so if you're lucky, they'll use the TJ operator which lays out text with specific kerning.  If you're not lucky (which is most of the time), they're instead lay out the text with a set of moves before every single glyph on the page.  And what if your text is laid our on a curve or an unusual orientation (maps, ads)?  What about the cases where someone subtly changes the font size for a greater distinction between upper and lower case or simulates small caps?
This is why, when I wrote the find text tool for Acrobat 1.0, it took me two months of sweat to handle as many of the edge cases.  This is not editing text - it's just trying to find a single word or phrase.
I'm not going to recommend a library for you - sorry - I gave xpdf a brief look over and it's not clear whether or not it has PDF generation capabilities or if it is simply a consumer of PDF.  PdfLib, which is a commercial product, appears to be to generate PDF, although it's not clear if it can consume it, but you could certainly get both sides by gluing them together.
If it were me, I would use tools that I've developed and I'd still be a little shy of this task.  My library is being used by Atalasoft, the company I work for, to generate PDFs from whole cloth and to do editing within a very limited domain (annotations, document metadata).  The hardest part is that we do our very best to hide the complexity of PDF from our customers.  In general, our customers want us to understand the spec instead of them and make the rest easy - but tasks like this (redaction is another one), are really hard to do without understanding the depth of the PDF specification.  If you start entering the library world of PDF manipulation, you should start with reading the spec, especially chapter 8 (Graphics) and chapter 9 (Text), and you'll get a better understanding of what you're going to have to do with the library.


Q:

Recovery of data after "Erase disk and install Ubuntu"

I am new to Ubuntu. I have just installed Ubuntu on my system and unfortunately I have selected the "Erase disk and install Ubuntu"-option while installing
the same.
It has deleted all my previous valuable data and an important project. Kindly tell me how I can recover all data.
I had Windows 7 before installing Ubuntu.

A:

Generally when it says deleted all the data it doesn't actually refer to delete. Your partition has just been labeled for overwrites with use. That is, the information has been classified as worthless and will be overwritten when more useful data needs to be stored(i.e. your new data like installing Ubuntu) So the more data you use the more of your 'supposed deleted data' is going to get overwritten.
Sadly there is no way to completely reverse the process, But
There are many tools for recovery of deleted data

http://www.cgsecurity.org/wiki/TestDisk

Command line, could be a challenge if you aren't comfortable &

http://www.cgsecurity.org/wiki/PhotoRec

Are some of the tools you can use
Do note this is only if the data is still present in some form hidden/ghost and has not been corrupted by overwriting of the bytes.
Some of the Steps you can perform Using testdisk:
1) Under Unix/Linux/BSD, you need to be root to run TestDisk (ie. sudo testdisk-6.13/testdisk_static). You must have installed testdisk in the first place using, in my case it was
tar -xjf /<path to>/testdisk-7.0.linux26-x86_64.tar.gz
cd testdisk-7.0.linux26-x86_64
./configure
make
sudo make install

After you download it, in that order.
Then you can try the following recommended steps from testdisk's intruction webpage:
1) To repair a filesystem not listed by TestDisk, run testdisk device, i.e.
testdisk /dev/mapper/truecrypt0

or
testdisk /dev/loop0

to repair the NTFS or FAT32 boot sector files from a TrueCrypt partition. The same method works with filesystem encrypted with cryptsetup/dm-crypt/LUKS.
To repair a filesystem on top of a Linux RAID device.
testdisk /dev/md0

2) Press Create in the next step, if it gives an error opt for 'No Log'
3) All hard drives should be detected and listed with the correct size by TestDisk:
Use up/down arrow keys to select your hard drive with the lost partition/s.
Press Enter to Proceed.
4) Partition table type selection
TestDisk displays the partition table types.
Select the partition table type - usually the default value is the correct one as TestDisk auto-detects the partition table type.
Press Enter to Proceed.
5) Current partition table status
TestDisk displays the menus (also see TestDisk Menu Items).
menus
Use the default menu "Analyse" to check your current partition structure and search for lost partitions.
Confirm at Analyse with Enter to proceed.
Now, your current partition structure is listed. Examine your current partition structure for missing partitions and errors.
Analyse
The first partition is listed twice which points to a corrupted partition or an invalid partition table entry.
Invalid NTFS boot points to a faulty NTFS boot sector, so it's a corrupted filesystem.
Only one logical partition (label Partition 2) is available in the extended partition. One logical partition is missing.
Confirm at Quick Search to proceed.
6) Quick Search for partitions
TestDisk displays the first results in real time.
quick search
During the Quick Search, TestDisk has found two partitions including the missing logical partition labeled Partition 3.
first results
Highlight this partition and press p to list your files (to go back to the previous display, press q to Quit, Files listed in red are deleted entries).
All directories and data are correctly listed.
Press Enter to proceed.
7)  For the rest of the steps I highly recommend you visit the testdisk website as there are many exhaustive steps with complete details
http://www.cgsecurity.org/wiki/TestDisk


Q:

How to win at roulette?

I know that the answer to my attention-grabbing question is : "You can't win at roulette, it's a negative Expected Value game".
Yes, you're right, long term speaking.
Let's imagine a medium-short term situation (just an after-dinner at the casinò) where there will be <100 bets.
What's the best strategy to use to win some money?
I imagine a hypothetical formula that considers our "money target" and percentage of success as inversely proportional (the more we want to win the less likely we are going to succeed).
What do you think? Are those "red-black double if lose" systems useful?

A:

If you want to maximise your probability of increasing your fortune to some target amount of money $\$a$ (greater than the amount you already have) then the correct strategy is the "bold strategy". If you have an amount of money $\$b$, then you should bet $\min\left(a-b,b\right)$ (i.e. bet everything you have unless you are near to your target, in which case bet just what you need to reach the target). This is because roulette is a negative expectation game, every time you bet you are on average going to lose money. So you want to achieve your target as quickly as you can. The Martingale strategy (double-if-you-lose) is bad because you make lots of bets, each one of which is negative expectation.
The bold strategy is proved to be optimal in this paper: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC223086/pdf/pnas00211-0067.pdf.
Of course, while this strategy does maximise the chance of hitting the target, it also has a large probability of losing all your money. In real life, "the only winning move is not to play".

A:

The negative expected value applies to short term as well. You simply do not have the odds.
Read up on Martingale, it is the system you mention at the end. Even that is not going to help you. If you lose too many times in a row and do not have enough cash, you lose big time.
So it is true, it is a negative EV game. Play for fun, not for sure profits.
Edit: If I had to, I would play a game where expected win is around zero and does not require great capital. That is e.g. betting a fixed amount on the same color over and over (or switch colors, does not matter). You should be about even (zero disrupts it), but if you get lucky, you might win/lose something.


Q:

Is it always necessary to wait for every thread to terminate before actually closing main one?

Suppose I have a main thread and a normal thread, whose execution lasts more than the former one.
Something like it:
public class Test{
     private int count;

     public void doTest(){
        (new MyThread()).start();

     }
     public static void main(String[] args){
           Test t = new Test();
           t.doTest();
     }

     private class MyThread extends Thread{
            public void run(){
                 while(count < 100){
                     count++;
                     ..wait some secs ...
                 }

            }

     }

}
Is it wrong to just leave code like that? Or would it be more correct perform a join() on the thread so to make sure that  it  correctly ends?

A:

This is one of the question, for which the answer is: It depends.
There is no technical reason to have the main thread running till all other threads are terminated. In fact, you can handle the main thread like every other thread. As I recommend to not have a thread keeping alive when it already has done its business and can be terminated, a main thread that only starts other threads should simply terminate after starting the others.
Remind: The JVM itself is not terminated when the main thread terminates. The JVM will only terminate when all non-daemon threads are terminated.


Q:

Exclude first 5 posts of specific categories in the main loop

I read this article about how to set an offset for one specific category in the loop. I was wondering about if this was possible for more than just one category.
My problem with the code suggested in the article linked above is that I am using a single widget to show five posts from a category I can set in the widget options by ID.
I cannot wrap my head around how to collect the post_IDs of the posts already looped through.
Situation:
I am using custom widgets on my blog page to show the 5 latest posts in two specified categories - let's call them categoryA and categoryB.

Answer to @Pieter Goosen's question in the comments: Yes, I can specify the
  category by manually entering an ID in the widget settings and it's
  saved in the DB.

Below these widgets the blog page loops through all my posts and shows them.
Effect:
The main loop on the blog page (the one below the widgets) displays the posts from categoryA and categoryB again. They appear double because the widgets above already looped through the categories A and B.
Question:
Is it possible to exclude the first five posts from categoryA and categoryB in the main loop? Could it be done with pre_get_posts? Using get_query_var? How?
EDIT
My own approaches
FIRST TRY
I modified my widget codes like this:
global $do_not_duplicate;
while($featured_posts->have_posts()): $featured_posts->the_post();
    $do_not_duplicate[] = get_the_ID();

As my widgets are being registered in my functions.php file, I added these lines to it:
global $do_not_duplicate;
$do_not_duplicate = array();
include('widgets/widgets.php');

Finally on the index.php, I added this line to the main loop:
if(have_posts()) :
    global $do_not_duplicate;
    while(have_posts()): the_post();
        if( in_array( $post->ID, $do_not_duplicate ) ) continue;
        get_template_part('content');
    endwhile;
endif;

Please note: This basically works but does not exactly remove the posts from the main query but skip them. This means the default posts_per_page setting won't be fulfilled and this won't work with Jetpack infinite scroll. Also, using globals is not the way to go.
SECOND TRY
I adapted @birgire suggestion and modified it a little. I thought about using the suggested pre_get_posts  filter in combination with a foreach-loop for the categories used by the widgets in order to gather the IDs of the posts queried by them.
Here's my snippet:
add_action('pre_get_posts', 'modified_mainloop', 10);
function modified_mainloop($query) {
    if(!is_admin() && $query->is_home() && $query->is_main_query()) {
        $cats_to_exclude = get_categories('include=3,4,9');
        foreach($cats_to_exclude as $category) {
            if($category->term_id == '9') {
                $num_posts_to_exclude = 3;
            } else {
                $num_posts_to_exclude = 5;
            }
            $posts_to_exclude = get_posts(array(
                'posts_per_page' => $num_posts_to_exclude,
                'category__in'   => array($category->term_id),
                'fields'         => 'ids'
            ));

        }
        $query->set('post__not_in', (array) $posts_to_exclude);

    }
}

Please note: Idea is OK, but code does not work.

A:

You might try this kind of pre_get_posts hook approach (untested):
add_action( 'pre_get_posts', function( $q )
{
    $exclude_cats = [ 12, 34 ]; // <-- Edit these category ids!

    if(    ! is_admin()
        && $q->is_main_query()
        && ! is_singular()
        && ! is_category( $exclude_cats )
    )
    {
        $exclude_post_ids = get_posts(
            [
                'fields'         => 'ids',
                'posts_per_page' => 5,
                'category__in'   => $exclude_cats,
            ]
        );
        $q->set( 'post__not_in', (array) $exclude_post_ids );
    }
} );

where you might have to adjust this further to your needs.
You also might want to use category slugs instead, but then you would have to setup a proper tax_query, since category__in only supports an array of category ids.

A:

Here is a concept that you can try out to exclude 5 posts per category each from category 3 and 5 where posts are excluded that belongs to category 9 and either of the before mentioned categories.
Here is the function: (CAVEAT: Requires PHP 5.4+ as I used new short array syntax. Change as needed)
/**
 * function get_sticky_category_posts()
 *
 * Get an array of post ids according to arguments given.
 *
 * @author Pieter Goosen
 * @see https://wordpress.stackexchange.com/q/187477/31545
 *
 * @param array $args
 */
function get_sticky_category_posts( $args = [] )
{
    /*
     * If the array is empty or not valid, return null
     */
    if ( empty( $args ) || !is_array( $args ) )
        return null;

    $ids = '';

    foreach ( $args as $k=>$v ) {

        /*
         * Check that $v['taxonomy'], $v['included_terms'] and $v['posts_per_page'] are all set. If not, return null
         */
        if (    !isset( $v['taxonomy'] )
             || !isset( $v['included_terms'] )
             || !isset( $v['posts_per_page'] )
        )
        return null;

        /*
         * Sanitize and validate user input
         */
        $included_terms = filter_var( $v['included_terms'], FILTER_VALIDATE_INT, ['flags'  => FILTER_FORCE_ARRAY] );
        $taxonomy       = filter_var( $v['taxonomy'], FILTER_SANITIZE_STRING );

        /*
         * Create tax_query according to whether $v['excluded_terms'] is set
         */
        if ( !isset( $v['excluded_terms'] ) ) {
            $tax_query = [
                [
                    'taxonomy'         => $taxonomy,
                    'terms'            => $included_terms,
                    'include_children' => false,
                ],
            ];
        } else {
            $tax_query = [
                [
                    'taxonomy'         => $taxonomy,
                    'terms'            => $included_terms,
                    'include_children' => false,
                ],
                [
                    'taxonomy'         => $taxonomy,
                    'terms'            => filter_var( $v['excluded_terms'], FILTER_VALIDATE_INT, ['flags'  => FILTER_FORCE_ARRAY] ),
                    'include_children' => false,
                    'operator'         => 'NOT IN'
                ],
            ];
        } // endif ( !$v['excluded_term'] ) statement

        /*
         * Use get_posts to get an array of post ids to exclude
         */
        $posts_to_exclude = get_posts(
            [
                'posts_per_page' => filter_var( $v['posts_per_page'], FILTER_VALIDATE_INT ),
                'fields'         => 'ids',
                'tax_query'      => $tax_query
            ]
        );
        if ( $posts_to_exclude ) {

            /*
             * Concatenate all ids into a string using implode
             */
            $ids .= implode( ' ', $posts_to_exclude );
            $ids .= ' ';
        } //endif ( $posts_to_exclude )

    } //end foreach

    /*
     * If we don't have any ids, thus empty string, return null
     */
    if ( !$ids )
        return null;

    /*
     * Create a single flat array of post ids. Use rtrim to remove trailing white space
     */
    return explode( ' ', rtrim( $ids ) );
}

Her is how it works:

You need to pass a multi-dimensional array to the function's arguments in the following format
$args = [
    0 => ['posts_per_page' => 5, 'taxonomy' => 'category', 'included_terms' => 3, 'excluded_terms' => 9],
    1 => ['posts_per_page' => 5, 'taxonomy' => 'category', 'included_terms' => 4, 'excluded_terms' => 9],
];
$a = get_sticky_category_posts( $args );

There are four allowed parameters, of which you have to set the posts_per_page, taxonomy and included_terms (which needs to be an integer or an array of term ids) parameters, otherwise the function returns null. The other allowed parameter (which is not required and can be omitted) is excluded_terms which is also an integer or an array of term ids and is the terms in which a posts should not be in. The above will return the following (ie means the following)

5 post ids from the taxonomy term 3 from the taxonomy category, but posts that are in term 3 and 9 should not be returned
5 post ids from the taxonomy term 4 from the taxonomy category, but posts that are in term 4 and 9 should not be returned
The returned array from the function (var_dump( $a )) looks something like this
array(10) {
  [0]=>
  string(3) "159"
  [1]=>
  string(3) "149"
  [2]=>
  string(3) "129"
  [3]=>
  string(3) "126"
  [4]=>
  string(3) "119"
  [5]=>
  string(2) "76"
  [6]=>
  string(3) "528"
  [7]=>
  string(3) "394"
  [8]=>
  string(3) "147"
  [9]=>
  string(2) "97"
}

This array can now be passed to pre_get_posts to the post__not_in parameter to exclude the posts from the function. You can also use this array of ids in any other place, maybe return them to a custom query or other purposes like sticky posts on other pages except the home page as used in this answer :-)
Here is a use case with pre_get_posts. This will remove the required posts from the main query. (Requires PHP 5.4+ due to the syntax in the function and the use of closures (closures are available PHP 5.3+)
add_action( 'pre_get_posts', function ( $q )
{
    if (    !is_admin() // Not necessary for home page, included it to be used on any other template like category pages
         && $q->is_main_query() // Make sure this is the main query
         && $q->is_home() // Targets the home page only
    ) {
        if ( function_exists( 'get_sticky_category_posts' ) ) {

            $args = [
                0 => ['posts_per_page' => 5, 'taxonomy' => 'category', 'included_terms' => 3, 'excluded_terms' => 9],
                1 => ['posts_per_page' => 5, 'taxonomy' => 'category', 'included_terms' => 4, 'excluded_terms' => 9],
            ];
            $sticky_cat_posts = get_sticky_category_posts( $args );

            if ( !empty( $sticky_cat_posts ) ) {
                $q->set( 'post__not_in', $sticky_cat_posts );
            }
        }
    }
});


Q:

Optimized modular multiplicative inverse for Bitcoin (secp256k1)

I have written an application to brute-force attack Bitcoin addresses for OpenCL. It implements a simple exhaustive search starting from public key G (private key 1) and point increment (addition of G) to get next key.
It works, but its performance is one order of magnitude slower than its CPU implementation using GMP (same point increment algorithm but with GMP routines instead of custom ones). On GMP implementation, hashing is the bottleneck. On OpenCL implementation, point increment is the bottleneck.
My point increment implementation uses modular multiplicative inverse via binary extended GCD (algorithm 14.61 of Handbook of Applied Cryptography). It is one order of magnitude slower than GMP implementation using mpz_invert().
What I need is an optimized point increment (point addition with G) optimized for curve secp256k1. This is an educational project, so my knowledge about the subject is limited. I don't know if there is a way to accomplish it without using modular multiplicative inverse or if there is a way to speed up this calculation for my particular application.
I saw and implementation (by Segher Boessenkool) using modular exponentiation with precomputed values, but there was no information on how to get those values for other curves. I failed to replicate GMP implementation. Its source code is huge and a mess of mixed optimized C and assembly code impossible to understand for me.
Requirements:

A fast point addition by G implementation.
Safety is irrelevant due to its use.
If possible, optimized for curve secp256k1.
If possible, precompute as much as possible.

Question:
How can I improve speed of elliptic curve point addition in my specific case?

Notes on comments:

The search is sequential inside each OpenCL kernel, but parallel considering the whole program. My worksize is optimized experimentally, getting close to theoretical GPU FLOPS performing SHA-256 only, so the bottleneck is not in OpenCL usage, but algorithmic implementation of elliptic curve cryptography.
The performance one order of magnitude smaller I am talking about is measured on CPU, not GPU. I get about 30 kKeys/s with my own modular multiplicative inverse and 200 kKeys/s (a laptop) with GMP. On GPU I get about 2 MKeys/s. Computing unoptimized SHA-256+RIPEMD-160 hash only, without point addition, I get about 1 GHashes/s (AMD Radeon RX 580).
Main program computes an array of public keys using scalar multiplication. It can compute them pseudo-randomly or equally spaced. This array is feed to the OpenCL kernel, and each instance computes RIPEMD160(SHA256(P)) == TARGET, RIPEMD160(SHA256(P+G)) == TARGET, RIPEMD160(SHA256(P+2G)) == TARGET, ... For now, there is only a single target address.
OpenCL is not the issue here. Profiling on CPU reveals that 90% of the time is expend computing modular multiplicative inverse. Same algorithm with GMP mpz_invert() uses only 25% of the time to do same step, using the remaining time on hash computation.

A:

Half-extended binary GCD
The extended binary GCD of the HAC's algorithm 14.61 mentioned in the question, when given positive integers $x$ and $y$ , computes integers $a$ , $b$ , $v$ with $ax+by=v=\gcd(x,y)$ . When $v=1$, it follows that $a$ is the multiplicative inverse of $x$ .
In our context, $0<x<y$, $y$ odd, $\gcd(x,y)=1$ (the last two conditions are met since $y$ is $p=2^{256}-2^{32}-977$ of secp256k1$v=1$ , which is prime); thus $a$ is always the inverse. Importantly, we do not need $b$ , which allows simplifications. This leads to the half-extended binary GCD, which I hope can help to some degree:

If $x$ is odd then $u\gets x$ ; else $u\gets x+y$ ;
$v\gets y$ ; $a\gets0$ ; $d\gets 1$ ;   [or $d\gets y-1$ in unsigned variant, see note]
While $v\ne1$
[invariant here and at start of the next while loop: $u$ and $v$ are odd and distinct]

While $v<u$

$u\gets u-v$ ; $d\gets d-a$ ;   [or $d\gets d+a$ in unsigned variant, see note]
While $u$ is even (that's at least once)

If $d$ is odd then $d\gets d+y$ ;
$u\gets u/2$ ; $d\gets d/2$ ;

$v\gets v-u$ ; $a\gets a-d$ ;   [or $a\gets a+d$ in unsigned variant, see note]
While $v$ is even (that's at least once)

If $a$ is odd then $a\gets a+y$ ;
$v\gets v/2$ ; $a\gets a/2$ ;

$a\gets a\bmod y$ ; that's the desired inverse.

Note: As shown, $a$ and $d$ are signed. In an unsigned variant we can keep them non-negative, by making the three changes noted.
As shown, $a$ and $d$ can grow to several times $y$ (in absolute value for the signed variant). We can devote some extra bits to this. I conjecture without proof that $\max(|a|,|d|)<4y\log_2(y)$ (or $\max(a,d)<8y\log_2(y)$ for the unsigned variant). Alternatively, we can change $a\gets a+y$ into $a\gets a-y$ when $a\ge0$ for the signed variant (for the unsigned one, that can be when $a\ge y'$ for some convenient $y'\ge y$, e.g. $y=2^{256}$ ); and same for $d\gets d-y$ . This is enough to ensure everything stays below $4y'$, or $2^{258}$ in the context.
Possible optimization: the number of times $i$ that the "While $u$ is even" loop is run is predictable from the low-order bits of $u$, and we can group the overall effect on $u$ and $d$ into a single loop. What needs to be added to $d$ depends on $i$, the $i$ low-order bits of $d$, and $y$ . It can be precomputed since $y$ is fixed. Even if we do this for $i$ up to 2 or 3 only (then iterate if necessary), that saves significantly (on a classical CPU at least). Same for $v$ and $a$.
The (half)-extend Euclidean algorithm (see this answer) also computes the multiplicative inverse, and has a simple variant avoiding multiplication (the quotient is made a power of two). It can be competitive. The two can be blended.

GPUs are best at SIMD workloads
GPUs shine at workloads where the same instruction flow applies to different independent jobs launched in parallel. Taking different code paths in simultaneously launched jobs at best dramatically reduces performance. Thus GPU-friendly algorithms are those with long sequences without tests, and tests which predictably mostly take the same path in different jobs. Algorithms often need to be tweaked towards that.
[hopefully more to come there]

It's a brute force attack
The attack require about $2^{b-1}$ point addition to find a private key with $b$ unknown bits, or about $256-b$ known bits (e.g. at zero). I see no reason why there should be such keys, other than deliberately. Thus I'm doubtful on the overall usefulness of the thing. We can still think about it for educational purposes.

Starting from addresses forces using Cartesian coordinates
Because a version of the attack is said to be hash-bound, we know that the attack tries to find a private key from the hash (known as address) of the corresponding public key, rather than from the public key. This has been confirmed in comments of that other answer, which proposes a mathematical technique assuming the public key is known. I'm not exploring that avenue.
Thus, the bulk of the sequential version of the algorithm is to compute public keys $kG$ for incremental private key $k$ using point addition of $G$ to move from one public key to the other; hash the resulting public key (essentially) in its Cartesian uncompressed $X\|Y$ form; and check the hash.

The attack should be multi-target
There is a tremendous potential benefit in targeting multiple addresses simultaneously; only the comparison of the final hash is made slightly more compute intensive (it becomes a search among the addresses targeted), and all the rest is shared. That's too good to ignore.

Outer loop for GPU (it's fine)
When optimizing an algorithm for GPU or other highly parallel architecture, it is essential to split the task into independent jobs. That part of the question made me think it was not done:

search starting from public key G (private key 1) and point increment (addition of G) to get next key

With this algorithm, the overall search speed would not scale up with more GPU power: point increment is going to be a bottleneck no matter how optimized it is.
But the question now also has:

Main program computes an array of public keys using scalar multiplication.

and that suggests "starting from public key G (private key 1)" does not apply to the OpenCL jobs/kernels. Instead, the private key search interval is subdivided, the corresponding public key computed, and the search performed; that's fine.

A:

Actually, if the reason you are computing elliptic curve points is to compare them to a target one, you don't need to compute a multiplicative inverse.  Instead, if you keep the point your iterating in projective coordinates $H = (H_x, H_y, H_z$) and the target value in standard coordinates $T = (T_x, T_y)$, you can determine whether $H = \pm T$ simply by checking whether $H_x = T_x H_z$ (actually, if you're keeping $H$ in Jacobean coordinates, this is $H_x = T_x H_z^2$ instead).  As the additional overhead from doing computations with projective coordinates is less than the overhead from doing a modular inverse, this is a win.

A:

GMP also uses extended GCD. It is fast precisely because it uses a "a mess of mixed optimized C and assembly code". You can't expect to achieve similar performance without the same optimizations.
Alternatively, your implementation could be particularly slow, it's impossible to tell without access to it.


Q:

can't get html td element using javascript in jsf application

and in JavaScript
 document.getElementById('myId');

This is not working in JSF application. However, the same is working if I save the generated HTML in my system and open it .
Any Help ?

A:

When writing JavaScript code for a component based MVC framework which generates HTML, like JSF, you should not focus on the source code of the component based MVC framework, but on its generated HTML output.
If you can't tell this beforehand based on the source code, then you need to just open up the page in your favourite webbrowser and then rightclick the page and choose View Source. You'll see that the generated Client ID's are prepended by the ID's of the UINamingContainer components (like h:form, h:dataTable and f:subView). If you don't specify an ID for each of them, you will get an autogenerated ID like j_id_xxxx. To ease the work, you need to specify an ID for them. E.g.
<h:form id="form">

Also see this blog article for more information and hints. This blog article may also be useful to learn more about the wall between Java/JSP/JSF and JavaScript.


Q:

Getting syntax error in query using MySQL

I am getting the following error while executing my sql query.
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's%' ORDER BY gallery_id DESC' at line 1
I am explaining my query below.
$searchKey="Celli's"
$keyword = '%'.$searchKey.'%';
$query = "SELECT * from db_gallery WHERE description LIKE '" . $keyword . "'
          ORDER BY gallery_id DESC ";

Here I need to search value but when 's is coming with any keyword its throwing error. Please help me.

A:

There is a ' contained in $searchKey, so there are actually three 's in your query: not corresponding!
You should escape first (both are okay):
$mysqli = new mysqli("host", "user", "pass", "db");
$searchKey = $mysqli->real_escape_string($searchKey);

$mysqli = mysqli_connect("host", "user", "pass", "db");
$searchKey = mysqli_real_escape_string($mysqli, $searchKey);

See: http://php.net/manual/en/mysqli.real-escape-string.php