text:
Q: How can I determine Levenshtein distance for Mandarin Chinese characters? We are developing a system to do fuzzy matching on over 50 international languages using the UTF-8, UTF-16, and UTF-32 Unicode character standard. So far, we have been able to use Levenshtein distance to detect misspellings of German Unicode extended character words.
We would like to extend this system to handle Mandarin Chinese ideographs represented in Unicode. How would we perform Levenshtein distance calculation between similar Chinese characters?

A: Firstly, just to clarify: A Chinese character is not as such equivalent to a German or English word. Most of the things you'd consider as words (using a semantic or syntactic definition of "word") consist of 1-3 characters. It is straightforward to apply Levenshtein distance to such character sequences by representing them as sequences of UCS-2 or UCS-4 code points. As most words are short (esp. words of length 1 or 2 characters), it may be of limited use, though.
However, as your question is specifically about the edit distance between individual characters, I believe a different approach is required, and it may be very difficult indeed.
For a start, you'd have to represent each character as a sequence of the components / strokes it consists of. There are two problems:

*

*Some components consist themselves of even smaller components, so how to break a character down into "atomic" components is not uniquely defined. If you do it down to the level of individual strokes, you'd need a characterisation of every single stroke (position within the character, shape, direction etc.). I don't think anyone as every done this (I'd be most interested if anyone tells me otherwise).

*You'd need to put the strokes or components into an order. The obvious candidate is the canonical stroke order of the character, which is described in lexica, and there are even dictionary websites with animated stroke order diagrams. However, the data sources I know (for Japanese), generate these animations as sequences of bitmap graphics; I have never seen human or machine readable codes that represent the sequence of strokes (or even the names of individual strokes) in a form that is suitable for edit distance calculation.
One final thing you could try, though, is to render the character glyphs and calculate the edit distance based on how many pixels (or vectors) need to be changed to turn one character into another. I once did this for Latin characters and character combinations (on pixel basis) in the context of OCR post-correction, and the results were quite encouraging.

A quick answer to larsmans comment below: There are two related concepts defined by the Unicode Standard (in the below I refer to the 6.0 version, chapter 12):

*

*An index based on radicals and stroke counts. Each Han character consists of several components, one of which is the radical. A radical/stroke count index is a character list sorted by radical (i.e. all characters that share the same radical grouped together), and each radical-specific group internally sorted by the number of strokes used in the rest of the character. Unfortunately, even this is not uniquely defined – there are characters whose radical is defined differently by different traditional lexica, and stroke counting can also be difficult. Here is what the Unicode Standard says:

To expedite locating specific Han ideographic characters in the code charts, radical-stroke indices are provided on the Unicode web site. [...]
  The most influential authority for radical-stroke information is the eighteenth-century
  KangXi dictionary, which contains 214 radicals. The main problem in using KangXi radicals today is that many simplified characters are difficult to classify under any of the 214
  KangXi radicals. As a result, various modern radical sets have been introduced. None, however, is in general use, and the 214 KangXi radicals remain the best known. [...]
  The Unicode radical-stroke charts are based on the KangXi radicals. The Unicode Standard
  follows a number of different sources for radical-stroke classification. Where two sources
  are at odds as to radical or stroke count for a given character, the character is shown in both positions in the radical-stroke charts.

Note that even if we assume the radical/stroke index to be unambiguous and correct, it wouldn't suffice as a source of information to transform a character into a sequence of components, because the only component of the character fully described by this is the radical.

*Ideographic description sequences (section 12.2): Unicode defines code points for the basic components of characters (most of them can themselves be used as standalone characters anyway), and there are codepoints used to glue those together to form a sequence of components that describes the composition of a more complex character. So this works in a way similar to combining characters, but there are important differences:

*

*The order of components is not uniquely defined

*There is no definition of a rendering mechanism for such sequences

*There is no mapping from ordinary characters to corresponding ideographic description sequences (although the Standard mentions that such mappings, to some extent, exist in the sources they used to compile the Han character set).

The Standard suggests that ideographic description sequences be used to describe complex or rare charactes that are not represented by any existing code point; but it explicitly discourages the use of description sequences in place of ordinary characters:

In particular, Ideographic Description Sequences should not be used to provide alternative
  graphic representations of encoded ideographs in data interchange. Searching, collation,
  and other content-based text operations would then fail.

A: I wrote a python package fuzzychinese to correct misspellings of Chinese words.
As @jogojapan has said, if you really want to calculate Levenshtein distance, it makes more sense to use sub-character structures such as radicals or strokes. You can use the Stroke() or Radical() classes from fuzzychinese to break down characters, and then calculate Levenshtein distance.
However, I am not sure Levenshtein distance works well for correcting misspelling Chinese words. In the package I wrote, I calculated tf–idf vector for n-gram strokes and used cosine similarity to match words.


text:
Q: How do I check if xml-rpc are working on OpenERP 7? I'm trying to figure out if my server is accepting or not xmlrpc request. What I know is that when I try to access http://my_ip:8069/xmlrpc/common or http://my_ip:8069/xmlrpc/object  on my browser I get a "File not found error". Is that what is expected?
Do I have to start my server with any flag to start xml-rpc suport?
Here is my openerp-server.conf
admin_passwd = my_pass
db_host = False
db_port = False
db_user = openerp
db_password = False
addons_path = /opt/openerp/v7/addons,/opt/openerp/v7/web/addons,/home/lfc/openerp/v7/addons
;Log settings
logfile = /var/log/openerp/openerp-server.log
; log_level = error
log_level = debug

And my starting script:
#!/bin/sh

### BEGIN INIT INFO
# Provides:             openerp-server
# Required-Start:       $remote_fs $syslog
# Required-Stop:        $remote_fs $syslog
# Should-Start:         $network
# Should-Stop:          $network
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Enterprise Resource Management software
# Description:          Open ERP is a complete ERP and CRM software.
### END INIT INFO

PATH=/bin:/sbin:/usr/bin
DAEMON=/opt/openerp/v7/server/openerp-server
NAME=openerp-server
DESC=openerp-server

# Specify the user name (Default: openerp).
USER=openerp

# Specify an alternate config file (Default: /etc/openerp-server.conf).
CONFIGFILE="/etc/openerp-server.conf"

# pidfile
PIDFILE=/var/run/$NAME.pid

# Additional options that are passed to the Daemon.
DAEMON_OPTS="-c $CONFIGFILE"
# Added option to debug
#DAEMON_OPTS="-c $CONFIGFILE --debug --log-level=debug"

# Log File
LOGFILE=/var/log/openerp/openerp-server.log

[ -x $DAEMON ] || exit 0
[ -f $CONFIGFILE ] || exit 0

checkpid() {
    [ -f $PIDFILE ] || return 1
    pid=`cat $PIDFILE`
    [ -d /proc/$pid ] && return 0
    return 1
}

case "${1}" in
        start)
                #Check if deamon is already running
                checkpid
                if [ "$pid" != "" ]; then
                        echo "$NAME already running with pid $pid."
                else
                #Only starts if not running
                echo -n "Starting ${DESC}: "
                start-stop-daemon --start --quiet --pidfile ${PIDFILE} \
                        --chuid ${USER} --background --make-pidfile \
                        --exec ${DAEMON} -- ${DAEMON_OPTS} --logfile=${LOGFILE}

                echo "${NAME}, OK."
                fi
                ;;

        stop)
                echo -n "Stopping ${DESC}: "

                start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
                        --oknodo

                #Check existence of PID file. If exists, then remove it
                checkpid
                if [ "$pid" != "" ]; then
                `rm ${PIDFILE}`
                echo -n "${PIDFILE} removed "
                fi

                echo "${NAME}, Stoped!"
                ;;

        restart|force-reload)
                echo -n "Restarting ${DESC}: "

                start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
                        --oknodo
                echo -n "\n${NAME}: STOPPED"
                sleep 1

                #Check existence of PID file. If exists, then remove it
                checkpid
                if [ "$pid" != "" ]; then
                `rm ${PIDFILE}`
                echo -n "\n${PIDFILE} REMOVED "
                fi
                sleep 1

                start-stop-daemon --start --quiet --pidfile ${PIDFILE} \
                        --chuid ${USER} --background --make-pidfile \
                        --exec ${DAEMON} -- ${DAEMON_OPTS}

                echo "\n${NAME}: STARTED\n"
                ;;

        *)
                N=/etc/init.d/${NAME}
                echo "Usage: ${NAME} {start|stop|restart|force-reload}" >&2
                exit 1
                ;;
esac

exit 0

A: You have to access it with valid data.
Common (xmlrpc/common) is for connection purposes and Object (xmlrpc/object) is to access tables and functions (modules).
For that you can create an api using Python, PHP, Java, etc
For example check this link

A: To check it You may use openerp-proxy project, which can be used as lib or CLI client to OpenERP / Odoo using xml-rpc or json-rpc.
So to test your connection:
$ pip install openerp_proxy  # also install IPython if you like it
$ openerp_proxy   # this will openen python/IPython shell
>>> db = session.connect()     # This will ask you required info for connection
>>> db.registered_objects      # this should return list of registered Openerp/Odoo models

Hope this will help

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to save the state of the stepper in iOS? I'm doing an app to be used as an inventory.
I need to know how to save the state of the stepper
So if I or another user close the app, the state of the stepper won't change.
My app is targeting multiple users, so if one user has changed the stepper state it will be saved and changed for other users.

A: The main idea: save UIStepper's value.

It depends on your needs how you should save it:

*

*If you have just one main stepper and this is the whole idea of your
app, you can save value to UserDefaults and then retrieve it
let stepper = UIStepper()

// Saving
UserDefaults.standard.set(stepper.value, forKey: "stepperValue")

// Retrieving
stepper.value = UserDefaults.standard.double(forKey: "stepperValue")

*If you have various number of steppers and their values are also connected with some model, you should use FileManager to save encoded values of steppers or you can also use some database like CoreData or Realm.


text:
Q: Is there a way to make a computer boot when plugged in(or power returns after an outage)? I've been using a little netbook as a personal server for 2 years give or take a few months, but soon I'll be going off to college. I plan on leaving it at my house, but if the power goes out I won't be there to turn it back on if the battery dies while the power is out.
Are there any ways to make it boot autonomously after an outage, or make it consume little to no power when not plugged in?
It looks like it's an 'Acer Aspire one series zg5', and it's running Ubuntu 11.04 server edition.

A: Usually there is. Look in the BIOS settings for Power Options, and find a "Action when lost power" or similar. Change it to  "Last State" or "Power On".
Your BIOS may or may not have it depending on bios manufacturer.


text:
Q: Mandar Array a través de Volley a Mysql desde SQLite Actualmente estoy enviando datos de un formulario a través de la librería Volley a Mysql, el problema que me acontece es que necesito enviar los datos en Arrays directamente desde mi BD SQLite a Mysql y no desde el mismo formulario:
Tablas SQLite
db.execSQL("CREATE TABLE formulario(\n" +
                "  id_formulario INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
                "  id_oportunidad_fk int(11),\n" +
                "  fechaCreacion date,\n" +
                "  HoraTermino time,\n" +
                "  num_propiedad varchar(11),\n" +
                "  norma_aplicada varchar(50),\n" +
                "  artefactos_instalados varchar(200),\n" +
                "  FOREIGN KEY(id_oportunidad_fk) REFERENCES oportunidades(id_oportunidad));");

db.execSQL("create table oportunidades(\n" +
                "id_oportunidad INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
                "fecha_oportunidad date NOT NULL,\n" +
                "fecha_creacion datetime NOT NULL,\n" +
                "hora time NOT NULL,\n" +
                "observacion varchar(1000) NOT NULL,\n" +
                "oportunidad int(11) NOT NULL;");

Intenté esta Lectura de datos SQLite pero es lo primero que no resulta
public Cabecera verCabecera(int id){

        DbHelper dbHelper = new DbHelper(context, "rs0401-2", null, 1);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cabecera formulario = null;
        Cursor cursorCabecera = null;

        cursorCabecera = db.rawQuery("select * FROM formulario WHERE id_formulario = " + id + " LIMIT 1", null);

        if (cursorCabecera.moveToFirst()){
                formulario = new Cabecera();
                 Map<String, String> parameters = new HashMap<String, String>();
                    parameters.put("fecha", cursorCabecera.getString(0));
                    parameters.put("rancho", cursorCabecera.getString(1));
                    parameters.put("sector", cursorCabecera.getString(2));
                    parameters.put("trabajador", cursorCabecera.getString(3));
                    parameters.put("hora", cursorCabecera.getString(4));
                    ProcessRequest(parameters);

        }
        cursorCabecera.close();

        return formulario;

    }

No tengo problema con la API, pero si como generar el código de volley para que lea Array directamente desde SQLite.


text:
Q: ValueError: operands could not be broadcast together with shapes (3,) (0,) My aim is to make the image1 move along the ring from its current position upto 180 degree. I have been trying to do different things but nothing seem to work. My final aim is to move both the images along the ring in different directions and finally merge them to and make them disappear.I keep getting the error above.Can you please help? Also can you tell how I can go about this problem?
from visual import *
import numpy as np
x = 3
y = 0
z = 0
i = pi/3
c = 0.120239 # A.U/minute
r = 1
for theta in arange(0, 2*pi, 0.1):        #range of theta values; 0 to
  xunit = r * sin(theta)*cos(i) +x
  yunit = r * sin(theta)*sin(i) +y
  zunit = r*cos(theta) +z

ring = curve( color = color.white )       #creates a curve
for theta in arange(0, 2*pi, 0.01):

  ring.append( pos=(sin(theta)*cos(i) +x,sin(theta)*sin(i) +y,cos(theta)   +z) )

  image1=sphere(pos=(2.5,-0.866,0),radius=0.02, color=color.yellow)
  image2=sphere(pos=(2.5,-0.866,0),radius=0.02, color=color.yellow)
  earth=sphere(pos=(-3,0,-0.4),color=color.yellow, radius =0.3,material=materials.earth) #creates the observer
  d_c_p = pow((x-xunit)**2 + (y-yunit)**2 + (z-zunit)**2,0.5) #calculates the distance between the center and points on ring
  d_n_p = abs(yunit + 0.4998112152755791) #calculates the distance to the nearest point
  t1 = ( d_c_p+d_n_p)/c
  t0=d_c_p/c
  t=t1-t0                                  #calculates the time it takes from one point to another

  theta = []
  t = []
  dtheta = np.diff(theta)                  #calculates the difference in theta

  dt = np.diff(t)                          #calculates the difference in t
 speed = r*dtheta/dt                      #hence this calculates the speed

 deltat = 0.005
 t2=0
 while True:
     rate(5)

     image2.pos = image2.pos + speed*deltat  #increments the position of the image1
  t2 = t2 + deltat

A: Your problem is that image2.pos is a vector  (that's the "3" in the error message) but speed*deltat is a scalar (that's the "0" in the error message). You can't add a vector and a scalar. Instead of a scalar "speed" you need a vector velocity. There seem to be some errors in indentation in the program you posted, so there is some possibility I've misinterpreted what you're trying to do.
For VPython questions it's better to post to the VPython forum, where there are many more VPython users who will see your question than if you post to stackoverflow:
https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users


text:
Q: If-Then-Else Opening Word Document I'm trying to create an If-Then-Else statement in MS Access VBA.
This statement is to open a specific word document but if the word document does not exist then open a different word document.
Below is the code I have and it works if I get rid of the else but that doesn't solve my problem because I need the else statement.
Dim appword As Word.Application
Dim doc As Word.Document
Dim Path As String

Set appWord = GetObject(, "word.application")

If Err.Number <> 0 Then
   Set appWord = New Word.Application
   appWord.Visible = True
End If

If Value = "Excused" Then
   Path = "C:\...existing docx"
Else
   Path = "C:\...different docx"
End If

Set doc = appWord.Documents.Open(Path, , True)

A: Use appword.Documents.Add to return a new Document.  You should also add an Error Handler when using GetObject.  You may also consider using Len(Dir(Path)) to test if the file exists.
Dim appword As Word.Application
Dim doc As Word.Document
Dim Path As String
On Error Resume Next
Set appword = GetObject(, "Word.Application")

If Err.Number <> 0 Then
    Set appword = New Word.Application
    appword.Visible = True
End If
On Error GoTo 0

If Value = "Excused" Then
    Path = "C:\...existing docx"
    Set doc = appword.Documents.Open(Path, , True)
Else
    Set doc = appword.Documents.Add
End If

A: Validate the document exists and if not add a new document.
Sub T()
    Dim appword As Word.Application
    Dim doc As Word.Document
    Dim Path As String

    Set appword = New Word.Application
        appword.Visible = True

    If Len(Dir("C:\...existing docx")) > 0 And Value = "Excused" Then
        Path = "C:\...existing docx"
        Set doc = appword.Documents.Open(Path, , True)
    Else
        Set doc = appword.Documents.Add
    End If
End Sub


text:
Q: Why does the font look so weird in terminal? It looks like its weirdly compressed. I don't know how this happened, everything was working fine and then all of a sudden this happened.

A: Open terminal > Edit > Preferences > Font. There should be a custom font box that is unchecked. Check the box that says custom font optional > select a custom font and font size in terminal.
Preferences in terminal:

Custom font enabled:

Text in terminal fixed and is back to normal:


text:
Q: electron + angular, pass Cookies from main to renderer I have an angular app build in electron where I need to make some request to an external API.
The HTTP request I will send from the angular app, but there, I do not get back the "set-cookie" header from the response.
When I make the same request from the main Process, I get the cookie.
When I run my angular app locally, without electron I also get the cookie.
So what can I do now to get cookies in the renderer??


text:
Q: HTML5 and MP4 vs. M2TS containers Problem:
To get an iOS app that streams video accepted into the app store, we need to have a  HLS version.
What's the problem?
Android does not support HLS well, and for other reasons, we need to store MP4 and HLS files of the same content.
What's the difference between MP4 and HLS and why do you need to store both?
MP4 is a container that stores H.264 video and AAC audio for best compatibility in HTML 5 browsers – jsvideo players often have flash fallback if the browser does not support MP4 video in HTML 5 that use the same MP4 file, but played through flash.
HLS is a protocol where text files (.m3u8) contain references to playlists, which themselves reference .ts files (or m2ts), which are mpeg-2 transport streams, not to be confused with mpeg-2 video. The .ts files are containers for the same H.264 video and AAC audio.
Why am I complaining?

*

*It takes time to create the HLS files and playlists from the MP4 files

*(Most importantly) We are now storing twice as much data on S3

*Why should  I care? If your S3 bill is $10K per month for storing both MP4 and HLS, now it is only $5K. Or put another way, if you are paying $100K for storing data in MP4, it would cost $200K to store the same content in both MP4 and HLS.
What do I want?
I want to store only the .ts files and serve both desktop users, iOS users, and Android users with that single file.
Is it possible?
Doesn't HLS require 5-10 second .ts segments instead of one big file?
As of IETF draft 7,  and version 4 of the protocol, HLS supports the tag EXT-X-BYTERANGE which allows you to specify a media segment as a byte range (subrange) of a larger URL.
Are .ts files compatible with HTML5 video?
Apparently not. They are a different container than MP4, yet contain the same video and audio content. Worth looking into how to store the raw video/audio data once and simply using the correct containers when necessary. If JS video players can convert HTML 5 MP4 files into Flash video on the fly if the browser does not support HTML 5 MP4, then why not be able to do the same with M2TS data?
I might be ignorant on some level, but maybe someone can shed some light on this issue, and possibly present a solution.

A: There currently is no good solution.
A little background.
Video streaming used to require custom protocols such as RTP/RTMP/RTSP etc. These protocols work fine except, we were basically building two separate networks. One HTTP based for standard web traffic, and the other one. The idea came along to split video into little chunks and serve them to the player over HTTP. This way we do not need special servers/software and we could take advantage of the giant HTTP CDNs that were being built. In addition. because the video was split into chunks, we can can encode the same video into different qualities/file sizes. Then the player can choose the best quality video for its current bandwidth. This was the perfect solution for mobile because of the constant changing network conditions. Several competing standard were developed. Move networks was the first to market [citation needed]. The design was copied by Microsoft (Smooth Streaming) and Apple (HTTP Live streaming aka HLS). Microsoft is phasing out smooth streaming in favor of DASH. DASH looks like it will become the default streaming solution of the future. Except, because of its design-by-comity approach, it has basically been stuck in comity for a few years. Now, in those few years, Apple sold Millions of IOS devices. So HLS can not just be discontinued.  Why doesn't everyone just use HLS then? I can think of three reasons 1) Its Apples standard, and people are haters. 2) Transport streams are a complicate file format. and 3) Transport streams a patent encumbered. MP4 is not patent encumbered but it also does not have the adaptive abilities. This make user experience poor on 2G networks. The only network supported by the iPhone 1. Also AT&T at the time did not want full bitrate video streamed over there woefully inadequate celular network. HLS was the compromise. All of this predates HTML5. So the video tag was not even considered in its design.
Addressing your points:

1) It takes time to create the HLS files and playlists from the MP4
  files

This is a programing website, Automate it.

2) We are now storing twice as much data on S3
  [sic] I want to store only the .ts files and serve both desktop users,
  iOS users, and Android users with that single file.

You and me both man :).
Possible solutions.
1) What is specifically wrong with Androids implementation? (except for lack of in older devices)
2) JW player can play HLS (Not sure about on android)
3) Server side transmux on demand.

Doesn't HLS require 5-10 second .ts segments instead of one big file?

You can do byte-ranges, but you need to make sure all devices you are interested in support it.

If JS video players can convert HTML 5 MP4 files into Flash video on
  the fly if the browser does not support HTML 5 MP4, then why not be
  able to do the same with M2TS data?

They don't convert. Flash natively supports mp4. It is possible to convert TS in AS3/JS. I have done it. JW player can convert TS in browser. video.js may be able to as well.


text:
Q: php pdo how to pull down and set default values from the database $select_stmt = $db->prepare('SELECT * FROM new_product WHERE `user_id` = :id');
$select_stmt->execute(array(':id'=>$_GET['id']));
$row = $select_stmt->fetch(PDO::FETCH_ASSOC);

  尺寸
  <select class="form-control"  name ="Size" id="Size">
    <option>30*60</option>
    <option>15*90</option>
    <option>15*17.3</option>
  </select>

I would like to ask how I can use the foreach to select the value brought out of the database to the default value. For example: my database value is 15 * 90, how to select option =15 * 90 I use PDO here

A: You need to create a loop to process all the results from the query and add the relevant parts of each row to the HTML
<?php
$select_stmt = $db->prepare('SELECT xx,desc FROM new_product WHERE `user_id` = :id');
$select_stmt->execute(array(':id'=>$_GET['id']));

?>

    尺寸
    <select class="form-control"  name ="Size" id="Size">
<?php
while ( $row = $select_stmt->fetch(PDO::FETCH_ASSOC)) :
    // these are just example column names as you dont tell us
    // what the columns you want to use are called

    echo "<option value='$row[xx]'>$row[desc]</option>";

endwhile;
?>
    </select>


text:
Q: Add new timezone to moment.js timezone I have to add "Asia/Bangkok" (ICT) to moment.js, as it doesn't seem to support it by default.
After loading moment.js and moment-timezone.js I tried defining this specific timezone following this example:
moment.tz.add({
    "zones": {
        "Asia/Bangkok": [
            "6:42:4 - LMT 1880 6:42:4",
            "6:42:4 - BMT 1920_3 6:42:4",
            "7 - ICT"
        ],
    }
});

var currentTimeString = moment().tz('Asia/Bangkok').format('DD MMM YYYY, HH:mm:ss');

However, I keep getting the error:

"Moment Timezone has no data for Asia/Bangkok. See
  http://momentjs.com/timezone/docs/#/data-loading/."

Any ideas why?

A: I want to post my solution, for others struggling with the badly documented API of moment.js...
To create a time zone, you will have to create an unpacked timezone object:
var unpacked = {
    name    : 'Asia/Bangkok',
    abbrs   : ['ICT'],
    untils  : [null],
    offsets : [-420]
};

*Note that while ITC is UTC+7 the UTC offset in the array has to be the additive inverse (negative) of 7*60 = 420 for some reason.*
Before you can use it, you will also have to pack this object, and for that you need to include moment-timezone-utils.js
var packed = moment.tz.pack(unpacked);
It will spit out the packed timezone format partly encoded in Base 60:
Asia/Bangkok|ICT|-70|0|
Now it can be added:
moment.tz.add('Asia/Bangkok|ICT|-70|0|');
If you don't want to go through all this trouble, there is also a pre-packed file on GitHub, where you can pick the needed timezone.


text:
Q: Can vagrant cache files used within chef scripts in way similar way to vagrant boxes? When you download a vagrant box. The first time it has to download from a server. Then it caches that box for future use.
Is there a way to do this for files within a chef script. For example we use wget to pull down a zip file for some software. These usually take 40 minutes. I would like to have this only download one time (for each unique version) and cache the file somewhere for global usage later. So that if I create another vagrant machine that references the same zip file, it will use the cached file instead of downloading again. Is this possible?

A: Especially if you use remote_file resource, you can use the vagrant-cachier plugin to cache the downloaded files to a synced folder from the host. Even with direct wget calls you could specify a generic bucket and download files there.
Another approach is to use a caching web proxy in your local network, on your host, or even on another VM (see polipo-box for an example), and use the vagrant-proxyconf plugin to automate the configuration of the Vagrant VMs.


text:
Q: SQL query to count if multiple rows bounded by 2 rows with a bool flag true meet certain conditions Say I have a large data set like this
row | id | flag | sequence | count |   text
...
...
1     abc  true     22         1       textA
2     abc  false    23         8       textB
3     abc  false    24         2       textZ
4     abc  true     25         1       textA

5     bdf  false    10         1       textA
6     bdf  true     11         1       textB
7     bdf  false    12         2       textA
8     bdf  false    13         4       textF
9     bdf  false    14         6       textZ
10    bdf  true     15         1       textA
...
20    dhg  true     5         4       textF
21    dhg  false    6         20       textZ
22    dhg  true     7         1       textA

...
...

All rows with the same id are guaranteed to be in incremental sequence.
Please help to write write a query to count as 1 if

*

*multiple rows between 2 rows with true flag have at least 2 rows

*and sum(count) of > 4.

*and at least one of those row has textZ.

So in the above data set, rows 1-4 met the condition and should be counted as 1. rows 5-10 also met all the conditions so count is 2 now. Row 20-22 doesn't not meet the 2nd condition so count stays at 2. The output should be 2 for this query for the example above.
Thank you.

A: If I understand correctly, you can assign a grouping based on the number of true values before a given value:
select id, min(row), max(row)
from (select t.*,
             sum(flag = 'true') over (partition by id order by row) as grp
      from t
     ) t
where not flag
group by id, grp
having count(*) >= 2 and   -- the first "true" is included
       sum(count) > 4 and
       sum(text = 'textZ') > 0;

This doesn't actually check that the group ends with a true.  I'm not sure how important that is.
EDIT:
If you need the actual rows, then this gets a little more complicated but you can do it using window functions:
select id, min(row), max(row)
from (select t.*,
             sum(case when flag <> 'true' then 1 else 0 end) over (partition by id, grp_desc) as cnt_false,
             sum(case when flag <> 'true' then count else 0 end) over (partition by id, grp_desc) as sum_count,
             sum(case when flag <> 'true' and text = 'textZ' then 1 else 0 end) over (partition by id, grp_desc) as cnt_textZ
      from (select t.*,
                   sum(flag = 'true') over (partition by id order by row) as grp_inc,
                   sum(flag = 'true') over (partition by id order by row desc) as grp_desc
            from t
           ) t
     ) t
where cnt_false >= 2 and
      sum_count > 4 and
      cnt_textZ > 0;

Note that both group_inc and group_desc define groups.  If you can live with just one "true" row, then group_inc includes the first, and group_desc includes the last one.

A: I can't think of any "proper SQL" way of doing this, the problem just seems to be too complex to be done in the DBMS. Perhaps you should reconsider the design of your tables, to optimize this thing.
Luckily however, you are using MySQL, and MySQL being MySQL, brings a bunch of features of unorthodox nature and questionable forward compatibility, but regardless, can get the job done.
MySQL allows you to iterate through the table content while using control variables to "take notes" and make an algorithm of sorts while performing a SELECT.
As such, you could do something like this to select a list of ranges that match your criteria:
-- note: variables are hard-typed
SET @i = '', @c = 0, @m = 0, @s = 0;

SELECT
  `id`,
  `start`,
  `end`
FROM
(
  SELECT
    *,
    @s `start`,
    IF(`id` = @i AND `flag` AND @c >= 2 AND (`text` = 'TextZ' OR @m), `sequence`, 0) `end`,
    @s := IF(`flag`, `sequence`, IF(`id` <> @i, 0, @s)) `unused1`,
    @m := IF(`text` = 'TextZ', 1, IF(`flag`, 0, @m)) `unused2`,
    @c := IF(`id` = @i, IF(`flag`, 0, @c + 1), 0) `unused3`,
    @i := `id` `unused4`
  FROM `t`
) `a` WHERE `end` <> 0;

Here's a functioning example for you to test and fiddle around: http://sqlfiddle.com/#!9/95f2b/3
And a query that selects the eligible ranges:
http://sqlfiddle.com/#!9/95f2b/6


text:
Q: How to expand all mat-expansion-panel with complex array by click a button? I am trying to display Mat-expansion-panel by click "open all" button. Now, i face the problem is inner panel is not working. It only can open the outside  only. I would like to open all panel with inner panel. How to achieve it ?  Please help.
stackblitz link

A: Get all expansion panel instance using ViewChildren decorator
@ViewChildren(MatExpansionPanel) expansionPanel: QueryList<MatExpansionPanel>;

Then call open method on it when you click openAll button
openll() {
    this.expansionPanel.toArray().forEach((panel)=>{
      panel.open();
    })
}

Forked Working Example

A: You are trying to expand expansion panels, but you are selecting accordion, this is the problem with your code, what you can do is use viewchildren , select all expansion panels, and then open them when you want. here is how the code will look like
  @ViewChildren(MatExpansionPanel) panels: QueryList<MatExpansionPanel>;

openAll(){
this.panels.forEach(panel => panel.open();)}


text:
Q: SQL stored proc performance - huge WHERE clause I have a stored proc that runs a query with a HUGE where clause. In itself, the WHERE clause is very simple. It looks like
SELECT a, b, c FROM table
WHERE (cond1) OR (cond2) OR (cond3) OR (cond4)

where cond1, cond2, cond3 and cond4 all represent some requirement from our users.
My question is regarding the query performance: would it make sense to execute 4 separeate queries (each with one of the conditions cond{1..4}), insert the results into a temporary table, and then finally select everything from that temporary table?
What I'm wondering is, whether dbms' optimize for such situations.
FWIW, i'm using Syabse ASE - TDS 5.5.
Thanks
Harshath
PS: Please don't ask me to "do my own benchmarking". I will of couse be doing that eventually. What i'm really looking for links pointing to the internals of such optimizations, if any. TY :)

A: If you include everything in a single WHERE clause, at least the DBMS will have an opportunity to optimize it. If you use separate queries, then the DBMS won't be able to optimize.
Besides, it seems to me you are adding a bunch of overhead with the temporary table, multiple queries, and combining everything together. I can't imagine how your second option could ever be faster or even as fast.

A: Having a larger WHERE will almost always be faster than separating it out into multiple queries and then appending the results.
Consider that in multiple queries are you are scanning the table for each query - which adds considerable overhead, not to mention any kind of disk IO that might happen. It's best to compare all you need to compare while you have the data in memory, than risk losing it from memory only to have to pull it back into memory for the next query.

A: The reason split-up queries can be faster is that the smaller separate queries can be resolved using indexes, where the big query results in a table scan.
The first question is: does the table have indexes?  If not, a table scan will always be required, and splitting the query into N parts will just cause N table scans.
If there are indexes, you'd have to test if your the optimizer decides to use them.  If the query optimizer already uses them, there is no point in splitting the query.
If there are indexes, and the query optimizer does not use them, and your testing shows that it would be faster to use them, you can benefit from splitting the query.


text:
Q: Cannot mark a message as read while using mailboxer in rails How can I mark any message as read in mailboxer?
Even if I add the line: <% conversation.mark_as_read(current_user) %> in my view, it does not solve my problem.

A: In case anybody else has this issue in the future, the solution is to only put code like what is in the original question in something like MessagesController, and to create a form which points to that action.


text:
Q: search or filter data based on first letter match I am using ng-select library for implementing a search dropdown. I am trying to implement a custom function that will filter items by first matching letter in the dropdown when I start typing. For example if user types in 'A', it should only show People name in the dropdown that starts with "A".
I have created an stackblitz example. I tried using Array.filter() function, but filter function won't work since the 'item' I am getting returned from my 'customSearchFn' is not in an array. Is there a way to implement this without using filter function?
hello.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
    <ng-select
      [items]="people"
      bindLabel="name"
      autofocus
      [searchFn]="customSearchFn"
    >
    </ng-select>
  `,
  styles: [
    `
      h1 {
        font-family: Lato;
      }
    `
  ]
})
export class HelloComponent {
  @Input() name: string;
  people = [
    {
      id: '5a15b13c36e7a7f00cf0d7cb',
      index: 2,
      isActive: true,
      picture: 'http://placehold.it/32x32',
      age: 23,
      name: 'Karyn Wright',
      gender: 'female',
      company: 'ZOLAR',
      email: 'karynwright@zolar.com',
      phone: '+1 (851) 583-2547'
    },
    {
      id: '5a15b13c2340978ec3d2c0ea',
      index: 3,
      isActive: false,
      picture: 'http://placehold.it/32x32',
      age: 35,
      name: 'Rochelle Estes',
      disabled: true,
      gender: 'female',
      company: 'EXTRAWEAR',
      email: 'rochelleestes@extrawear.com',
      phone: '+1 (849) 408-2029'
    },
    {
      id: '5a15b13c2b1746e12788711f',
      index: 11,
      isActive: true,
      picture: 'http://placehold.it/32x32',
      age: 25,
      name: 'Nguyen Elliott',
      gender: 'male',
      company: 'PORTALINE',
      email: 'nguyenelliott@portaline.com',
      phone: '+1 (905) 491-3377'
    },
    {
      id: '5a15b13c605403381eec5019',
      index: 12,
      isActive: true,
      picture: 'http://placehold.it/32x32',
      age: 31,
      name: 'Mills Barnett',
      gender: 'male',
      company: 'FARMEX',
      email: 'millsbarnett@farmex.com',
      phone: '+1 (882) 462-3986'
    },
    {
      id: '5a15b13c947c836d177aa85c',
      index: 14,
      isActive: false,
      picture: 'http://placehold.it/32x32',
      age: 29,
      name: 'Yvette Navarro',
      gender: 'female',
      company: 'KINETICA',
      email: 'yvettenavarro@kinetica.com',
      phone: '+1 (807) 485-3824'
    },
    {
      id: '5a15b13c5dbbe61245c1fb73',
      index: 15,
      isActive: false,
      picture: 'http://placehold.it/32x32',
      age: 20,
      name: 'Elisa Guzman',
      gender: 'female',
      company: 'KAGE',
      email: 'elisaguzman@kage.com',
      phone: '+1 (868) 594-2919'
    }
  ];

  customSearchFn(term: string, item: any) {
    console.log(term);
    console.log(item);

  }
}

A: You only need to modify your customSearchFunction to:
 customSearchFn(term: string, item: any) {
     // check if the name startsWith the input, everything in lowercase so "a" will match "A"
     return item.name.toLowerCase().startsWith(term.toLowerCase())
 }

Working stackblitz
FYI, the custom function is called with every item on your list.


text:
Q: In opposing vs when opposing I'm having trouble with in, when, and where. I'd GREATLY appreciate some assistance with to the two questions below.
Q1 Which of the bolded terms should be used in the sentence below?

*

*In/When opposing Bob's motion, John bears the initial burden of . . . .

Here's some context: Bob filed a motion in court (a motion is a formal request for the court to do something). John must respond to, or oppose, that motion. In/when opposing that motion, John bears the burden of demonstrating X. In other words, to successfully oppose Bob's motion, John has to satisfy this burden.
Q2 In the sentence below, is the word "where" used correctly?

*

*Where, as here, the court's ruling is based on the parties' written submissions rather than an evidentiary hearing, the plaintiff need only demonstrate that X.

Context: Before issuing its ruling, the court may decide to hold a formal hearing to ask John and Bob to clarify or provide additional evidence in support of their arguments. Alternatively, the court may simply issue its ruling on the basis of Bob and John's written arguments, without the benefit of a formal hearing.
Thank you for your time.

A: *

*"In opposing Bob's motion" fits what you described.  "When opposing such-and-so types of motion, one bears etc." would fit a general guideline type of statement.

*Your "where" statement looks good.
I'm a recent paralegal graduate, and for my answers I'm going by what I've seen in legal writing.
It's always hard to choose between ELU and Law for this type of question.  If you want more participation here, you might provide a link to the question over in Law Meta and/or their chat (I don't know how much traffic their chat gets).


text:
Q: What's the correct way to count the bytes needed for a UTF8 conversion? I need to count the size, in bytes, that a substring will be once converted into a UTF8 byte array.  This needs to happen without actually doing the conversion of that substring.  The string I'm working with is very large, unfortunately, and I've got to be careful not to create another large string (or byte array) in memory.
There's a method on the Encoding.UTF8 object called GetByteCount, but I'm not seeing an overload that does it where I don't have to copy the string into a byte array.  This doesn't work for me:
Encoding.UTF8.GetByteCount(stringToCount.ToCharArray(), startIndex, count);

because stringToCount.ToCharArray() will create a copy of my string.
Here's what I have right now:
public static int CalculateTotalBytesForUTF8Conversion(string stringToCount, int startIndex, int endIndex)
{
  var totalBytes = 0;
  for (int i = startIndex ; i < endIndex; i++)
    totalBytes += Encoding.UTF8.GetByteCount(new char[] { stringToCount[i] });

  return totalBytes;
}

The GetByteCount method doesn't appear to have the ability to take in just a char, so this was the compromise I'm at.
Is this the right way to determine the byte count of a substring, after conversion to UTF8, without actually doing that conversion?  Or is there a better method to do this?

A: There doesn't appear to be a built-in method for doing this, so you could either analyze the characters yourself or do the sort of thing you're doing above. The only thing I would recommend -- reuse a char[1] array, rather than creating a new array with each iteration. Here's an extension method that jives well with the built-in methods.
public static class EncodingExtensions
{
    public static int GetByteCount(this Encoding encoding, string s, int index, int count)
    {
        var output = 0;
        var end = index + count;
        var charArray = new char[1];
        for (var i = index; i < end; i++)
        {
            charArray[0] = s[i];
            output += Encoding.UTF8.GetByteCount(charArray);
        }
        return output;
    }
}

A: So, there is an overload which doesn't require the caller create an array of characters first: Encoding.GetByteCount Method (Char*, Int32)
The issue is that this isn't a CLS-compliant method and will require you do some exotic coding:
public static unsafe int CalculateTotalBytesForUTF8Conversion(
    string stringToCount,
    int startIndex,
    int endIndex)
{
    // Fix the string in memory so we can grab a pointer to its location.
    fixed (char* stringStart = stringToCount)
    {
        // Get a pointer to the start of the substring.
        char* substring = stringStart + startIndex;

        return Encoding.UTF8.GetByteCount(substring, endIndex - startIndex);
    }
}

Key things to note here:

*

*The method has to be marked unsafe, since we're working with pointers and direct memory manipulation.

*The string is fixed for the duration of the call in order prevent the runtime moving it around - it gives us a constant location to point to, but it prevents the runtime doing memory optimization.

You should consider doing thorough performance profiling on this method to ensure it gives you a better performance profile than simply copying the string to an array.
A bit of basic profiling (a console application executing the algorithms in sequence on my desktop machine) shows that this approach executes ~35 times faster than looping over the string or converting it to a character-array.

*

*Using pointer: ~86ms

*Looping over string: ~2957ms

*Converting to char array: ~3156ms

Take these figures with a pinch of salt, and also consider other factors besides just execution speed, such as long-term execution overheads (i.e. in a service process), or memory usage.


text:
Q: Interpreting the expected value as an abstract integral? My notes contain the following notation
$$E(\theta\mid X) = \int \theta \, df(\theta\mid X) = \int \theta f(\theta\mid X) \, d\theta$$
The first integral looks like a Riemann–Stieltjes integral, although this sequence of equalities does not look correct to me. I thought that the general relation is (non-rigorously)
$$\int f(y)\,dg(y) = \int f(y)g'(y)\,dy$$
which indicates that $df(\theta \mid X)$ in the first line should instead be $dF(\theta \mid X)$, the cumulative density distribution function. Is there an error in the notes or am I missing something in this probabilistic interpretation?

A: Yes, it is meant to be:
$$\begin{align}
\mathsf E(\theta \mid X) & = \int \theta \;\operatorname d F(\theta\mid X) \tag{capital F}
\\ & = \int \theta \;f(\theta \mid X) \operatorname d \theta \tag{lowercase f}
\end{align}$$


text:
Q: OpenKm 6.3.0 is not starting in Ubuntu server Previously I used OpenKM 5.1.11 But now I want to install OpenKM 6.3.0.
I just unzip openkm-6.3.0-community-tomcat-bundle.zip. in /opt
I tried sudo /opt/tomcat/bin/catalina.sh run I got error.
So please help me solve this issue.
Thanks in Advance

A: There are few other configuration that you need to do which I believe is not mentioned in their documentation.

*

*OpenKM.cfg has to be updated
hibernate.hbm2ddl=create
for the first time until there are no issues in server startup.

*context.xml
Uncomment the Resource tag for hsqldb(A file based repository, which comes default with OpenKM)

*There are few other jar files which I believe is not present in tomcat lib folder which is required for OpenKM
spring-core-3.1.1.RELEASE.jar, mail-1.4.7.jar, log4j-initializer.jar, log4j-1.2.17.jar, jta-1.1.jar, jstl-1.2.jar, hsqldb.jar
If the above jars are already present then skip step#3


text:
Q: ifconfig down using ifconfig output On RH 6.7, using bash:
I need to free up some IP addresses using a script.
I am looking for a way to shutdown the bonding using the ifconfig xxx down command.
I search for list of candidate using this:
$ ifconfig |grep ^bond[0-9]:[1-9] |awk '{print $1}'

How may I easily use the output from this command to the down command?
xargs did not work for me:
$ ifconfig |grep ^bond[0-9]:[1-9] |awk '{print \$1}' | xargs -n 1 ifconfig  down

Thanks

A: Found a nice option:
for i in `ifconfig |grep ^bond[0-9]:[1-9] |awk '{print $1}'` ;   do
  ifconfig $i down;
done


text:
Q: php mysql code won't echo I got the following code:
    if(isset($_SESSION['user_id'])) { $query = "SELECT * FROM watchlist,movies WHERE watchlist.page=movies.id AND userid=". $_SESSION['user_id'];
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());

    while( $row = mysql_fetch_assoc($result) )
      {
        echo '
';
            echo '
';
            echo ''.$row['title'].'
';
            echo "
";
      }
    elseif(empty($row)) {
        echo "You dont have any movies in your watchlist!";
    }

My problem is that is doesnt echo when its empty how can I fix that?

A: elseif(empty($row)) {

That's wrong conditional structure, an elseif must come after an  if block or another elseif.
How can that code not generate a parse error for you?
Parse error: syntax error, unexpected T_ELSEIF on line 13

Also, as others mentioned, simply check for row count being 0
if(mysql_num_rows($result)==0)

A: You need to use
mysql_num_rows($result)

to check if there are 0 rows or more than that.

A: Checking empty($row) doesn't do what you think it does. What you want to check is mysql_num_rows($result) == 0.
A sidenote - mysql is deprecated in favor of mysqli.

A: Try that :
   if(mysql_num_rows($result) == 0)
  { echo "You dont have any movies in your watchlist!"; }
  else{
  while( $row = mysql_fetch_assoc($result) )
  {
    echo '
';
        echo '
';
        echo ''.$row['title'].'
';
        echo "
";
  }

  }

A: You could modify your code as below, also try to use mysqli instead of mysql
<?php
if(isset($_SESSION['user_id'])) { $query = "SELECT * FROM watchlist,movies WHERE watchlist.page=movies.id AND userid=". $_SESSION['user_id'];
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());

    $count = mysql_num_rows($result);

    if($count > 0 )
    {
        while( $row = mysql_fetch_assoc($result) )
        {
            echo '
';
            echo '
';
            echo ''.$row['title'].'
';
            echo "
";
        }
    }
    else {
        echo "You dont have any movies in your watchlist!";
    }
}
?>


text:
Q: How do I translate Apple API documentation in to real life code? I find this aspect of learning new things in Swift and Xcode very puzzling.
I cannot seem to decipher the actual code I need to write from what I read in the Apple API documentation; In my specific case: the API Reference for 'PlaygroundSupport', and the actual code I need, which is:
import PlaygroundSupport
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
PlaygroundPage.current.liveView = containerView

To me this seems like 'hidden knowledge' that I cannot divine from the API. There is no example usage given.
How would I find out from the Apple API that I needed to add UIView (as containerView) in the manner required? How can I learn to read Apple API documentation in the way that is assumed?

A: Reading API documentation is a lot like reading a math textbook: you need to understand every word you're reading, or else you might miss what you need. In this case, inspecting that documentation, you'd probably check out the PlaygroundPage class, and you'd see the liveView property described as "The active live view in the assistant timeline". If you're not sure what a "live view" is, or what "the assistant timeline" is, then some further searching might be required. If you are aware of those terms, however, you should instantly recognize this as the property you're looking for!
Keep browsing through the documentation and make sure you understand enough of each method or property to definitely rule it out or look into it further. It can be overwhelming at first, but as you read the Swift iBook, follow tutorials, and continue to read the documentation, you will find yourself understanding more and more of what it says.

A: As @andyvn22 mentions it just takes time to learn how to work with the documentation, understand the way it's trying to communicate to you and experiment. I'll show you my thought process:

*

*The page you linked has a import PlaygroundSupport and I could see there's a class PlaygroundPage - assuming you want to play with rendering UI's in the Playground, I dig into that.

*The PlaygroundPage seems to have a property called liveView which seems to let me interact with something in real time, so click through there... https://developer.apple.com/reference/playgroundsupport/playgroundpage

*I can see that liveView is a get/set so I know I need to pass it something, perhaps the view object I want to render in the playground? Let's click through to the PlaygroundLiveViewable protocol that this view must conform to... https://developer.apple.com/reference/playgroundsupport/playgroundpage/1964506-liveview

*Ah, so a UIView or UIViewController conform to the PlaygroundLiveViewable protocol - if I try and pass it one then it works as you seem to have ascertained in your question https://developer.apple.com/reference/playgroundsupport/playgroundliveviewable
It's not always straightforward because let's face it, writing documentation for a language that's only just settling in is a challenge. I'd recommend solidifying some software engineering foundations like classing, subclassing, the get/set paradigm and the more you learn the more patterns you'll spot and have an easier time following the documentation!


text:
Q: WPF AutoCompleteBox - How to restrict it choose only from the suggestion list? I would like to restrict WPF AutoCompleteBox (wpf toolkit control) to select an item only from the suggestion list. It should not allow users to type whatever they want.
Can someone suggest me how to implement this? Any sample code is appreciated.

A: Here's how I did it. Create a derived class and override OnPreviewTextInput. Set your collection to the control's ItemsSource property and it should work nicely.
public class CurrencySelectorTextBox : AutoCompleteBox
{
    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        var currencies = this.ItemsSource as IEnumerable<string>;
        if (currencies == null)
        {
            return;
        }

        if (!currencies.Any(x => x.StartsWith(this.Text + e.Text, true, CultureInfo.CurrentCulture))
        {
            e.Handled = true;
        }
        else
        {
            base.OnPreviewTextInput(e);
        }
    }
}

A: You can restrict user by Priview key down event. I hope it will work...

A: If you are databinding it to a property, like this for an example
<sdk:AutoCompleteBox ItemsSource="{Binding Sites, Source={StaticResource VmSchedulel}}" ValueMemberPath="SiteName"
                                             SelectedItem="{Binding Site, Mode=TwoWay}" FilterMode="ContainsOrdinal">
                            <sdk:AutoCompleteBox.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding SiteName}"/>
                                </DataTemplate>
                            </sdk:AutoCompleteBox.ItemTemplate>
                        </sdk:AutoCompleteBox>

If some text is entered which doesn't match anything in the ItemsSource, the SelectedItem will be equal to null.
In the set method of your property, you can just not set the value because it's null, and the Property will keep it's original value.
 set
        {
            if (value != null)
            {
                BaseRecord.SiteID = value.ID;
                PropChanged("Site");
            }
        }


text:
Q: Zooming into an image from user's touch point with UIScrollView in Swift The below Swift code manages zooming in and out of an UIImage inside a UIScrollView.
When double tapping, the image zooms into the centre and zooms out to the centre.
Question:
What code changes need to be made to set the zoom in point to be the centre of the image area the user touches on screen?
(For example, if the user double taps the top left of the image, the image would correspondingly zoom into the top left of the image.)
class ScrollViewController: UIViewController, UIScrollViewDelegate {
    var scrollView: UIScrollView!
    var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView = UIImageView(image: UIImage(named: "image.png"))

        scrollView = UIScrollView(frame: view.bounds)
        scrollView.backgroundColor = UIColor.blackColor()
        scrollView.contentSize = imageView.bounds.size
        scrollView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]

        scrollView.contentOffset = CGPoint(x: 1000, y: 450)

        scrollView.addSubview(imageView)
        view.addSubview(scrollView)

        scrollView.delegate = self
        setZoomScale()
        setupGestureRecognizer()
    }

    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }

    override func viewWillLayoutSubviews() {
        setZoomScale()
    }

    func setZoomScale() {
        let imageViewSize = imageView.bounds.size
        let scrollViewSize = scrollView.bounds.size
        let widthScale = scrollViewSize.width / imageViewSize.width
        let heightScale = scrollViewSize.height / imageViewSize.height

        scrollView.minimumZoomScale = min(widthScale, heightScale)
        scrollView.zoomScale = 1.0
    }

    func scrollViewDidZoom(scrollView: UIScrollView) {
        let imageViewSize = imageView.frame.size
        let scrollViewSize = scrollView.bounds.size
        let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
        let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0

        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
    }

    func setupGestureRecognizer() {
        let doubleTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
        doubleTap.numberOfTapsRequired = 2
        scrollView.addGestureRecognizer(doubleTap)
    }

    func handleDoubleTap(recognizer: UITapGestureRecognizer) {
        if (scrollView.zoomScale > scrollView.minimumZoomScale) {
            scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
        } else {
            scrollView.setZoomScale(scrollView.maximumZoomScale, animated: true)
        }
    }
}

A: According to this post. It works fine with me.
func handleDoubleTap(recognizer: UITapGestureRecognizer) {
    if (scrollView.zoomScale > scrollView.minimumZoomScale) {
        scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
    } else {
        let touchPoint = recognizer.locationInView(view)
        let scrollViewSize = scrollView.bounds.size

        let width = scrollViewSize.width / scrollView.maximumZoomScale
        let height = scrollViewSize.height / scrollView.maximumZoomScale
        let x = touchPoint.x - (width/2.0)
        let y = touchPoint.y - (height/2.0)

        let rect = CGRectMake(x, y, width, height)
        scrollView.zoomToRect(rect, animated: true)
    }
}

A: Here's a Swift 2.3 function for returning the location of a touch inside a zoomable UIScrollView:

*

*UIScrollView with UIImageView inside

*Zoomed or not - scrollView.zoomScale

*imageView.contentMode = .ScaleAspectFit

*The image can be bigger, high res than imageView and scrollView

*Any shape of the image, portrait, landscape or square

imageView.contentMode = .ScaleAspectFit
//import AVFoundation // needed for AVMakeRectWithAspectRatioInsideRect()

func getLocationOfTouchInImageInScrollView(paintLocation:CGPoint)->CGPoint {

    let imageSize = imageViewInScrollView.image!.size
    let imageFrame = scrollView.frame
    let imageRect = AVMakeRectWithAspectRatioInsideRect(imageSize, imageFrame)
    let imageHeightToViewHeight = max(imageSize.height, imageSize.width) / imageFrame.size.height

    let px = (max(0, min(imageSize.width, ((paintLocation.x - imageRect.origin.x) * imageHeightToViewHeight))))
    let py = (max(0, min(imageSize.height, ((paintLocation.y - imageRect.origin.y ) * imageHeightToViewHeight))))
    var imageTouchPoint = CGPointMake(CGFloat(px), CGFloat(py))

    return imageTouchPoint
}

Took me DAYS to write this one since I couldn't figure out the imageHeightToViewHeight variable, thought there was something else funny going on.


text:
Q: Python Script GetParameterAsText? I am writing a python script to be added to a toolbox and I do not know how to call an existing tool to be a parameter.
import geocoder  ##geocoding library
import csv
import arcpy     ##ArcGIS python module
import arcgisscripting
arcpy.env.overwriteOutput = True
gp = arcgisscripting.create()##creating geoproccessing object
env = arcpy.GetParameterAsText(0)
gs = arcpy.GetParameterAsText(1)  ##csv containing thousands of rows to be        reverse geocoded
cc = gp.SearchCursor(gs) ##creating arcpy searccursor to open and read csv
z=0
for add in cc:           ##looping thru all rows in csv
    Company = str(add.Company)
    Address = str(add.Address)
    City = str(add.City)
    State = str(add.State)
    Zip = str(add.Zip)
    geo = geocoder.google(str([Address,City,State,Zip]))
    addr = geo.latlng       ##returning xy for each row
    print addr
    if addr:
        x = addr[1]
        y = addr[0]
        firstrow = "Company"+","+"Address"+","+"X"+","+"Y"+","+"\n"
        line = str(Company)+','+str(Address)+','+str(x)+','+str(y)+','+'\n' ##line of info for new csv
        z+=1
        with open("Interm.csv", 'ab') as csvfile:  ##creating/opening/closing csv
            if z==1:
                csvfile.write(firstrow)
            else:
                csvfile.write(line)   ##writing line to csv
                print line
fc = arcpy.GetParameterAsText(2)
newpath =  arcpy.GetParameterAsText(3)#arcpy.CreateFeatureclass_management(env, fc, arcpy.GetParameterAsText(3),"","","",arcpy.GetParameterAsText(4))
arcpy.AddField_management(newpath, "Company", "TEXT")
arcpy.AddField_management(newpath, "Address", "TEXT")
cursor=arcpy.da.InsertCursor(newpath, ["Company","Address", "SHAPE@XY"])
outcsv = "Interm.csv"
curcsv = gp.SearchCursor(outcsv)
for geom in curcsv:
    addr = geom.Address
    comp = geom.Company
    X = float(geom.X)
    Y = float(geom.Y)
    newRow = (str(comp),str(addr),(X,Y))
    cursor.insertRow(newRow)
    print newRow

when i add the script to the toolbox and use arcpy.GetParameterAsText for createfeatureclass tool

 this is what shows when i set the parameters
then this shows up when I open the script to use

So what i want to do is have the create feature class tool parameters open in my script tool...

A: Since you already know what will be your new path, you could simply define it yourself...
import os
...
result = arcpy.CreateFeatureclass_management(env, fc, arcpy.GetParameterAsText(3),"","","",arcpy.GetParameterAsText(4))
if result.status == 4:
    newpath = os.path.join(env,fc)
    arcpy.AddField_management(newpath, "Company", "TEXT")
    arcpy.AddField_management(newpath, "Address", "TEXT")
...


text:
Q: Div only transitions the second time a key is clicked? I have a yellow div that moves left/up when the corresponding key is clicked. I want it to transition each times. This happens, but starting from the second time it is clicked. On the first click, it moves but there is no transition... What's wrong with my code?
.counter {
  border-radius: 50%;
  width: 20px;
  height: 20px;
  position: absolute;
  margin-top: -100px;
  margin-left: 60px;
  transition: top linear 1s, left linear 1s;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  padding: 20px;
}

#yellow {
  background-color: yellow;
}

P1

document.onkeydown = detectKey;

function detectKey(e) {

  var posLeft = document.getElementById('yellow').offsetLeft
  var posTop = document.getElementById('yellow').offsetTop

  if (e.keyCode == '39') {
    document.getElementById('yellow').style.left = (posLeft + 80) + "px"
  }
  if (e.keyCode == '38') {
    document.getElementById('yellow').style.top = (posTop - 50) + "px"
  }
}

A: I think you simply need to specify an initial top and left value in your CSS.
See the attached snipet.

document.onkeydown = detectKey;

function detectKey(e) {

  var posLeft = document.getElementById('yellow').offsetLeft
  var posTop = document.getElementById('yellow').offsetTop

  if (e.keyCode == '39') {
    document.getElementById('yellow').style.left = (posLeft + 80) + "px"
  }
  if (e.keyCode == '38') {
    document.getElementById('yellow').style.top = (posTop - 50) + "px"
  }
}
.counter {
  border-radius: 50%;
  width: 20px;
  height: 20px;
  position: absolute;
  /*margin-top:-100px;
   margin-left:60px;*/
  transition: top linear 1s, left linear 1s;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  padding: 20px;
  top: 0; /* <<< */
  left: 0; /* <<< */
}

#yellow {
  background-color: yellow;
}

P1


text:
Q: Visual Studio UserMacros (and general property sheet) Syntax? I've scoured around and haven't been able to find any kind of a decent reference guide on Visual Studio property sheets. Most of what you can do with them cannot be done through the UI, so I've got to think there is a reference guide somewhere that can be useful in understanding the available fields, syntax, etc.
Lunicon's answer to this question was really useful, but I'd really like to know where the information on what could be done in property sheets came from. I'm hoping it was not a lot of trial and error. ;)

A: This is not a decent reference guide at all, but I did notice that there is a schema for the property sheet defined here:  http://msdn.microsoft.com/en-us/library/ak4435es(v=vs.80).aspx


text:
Q: Printing files in filename order I want to print a directory of files in the order of filename ascending (not happening for me - seems to default in file creation order).
Code:
Dim PrintPDF As New ProcessStartInfo
For Each fileName1 In Directory.GetFiles(strALPRMailOutReports, "*.pdf", SearchOption.AllDirectories)
    PrintPDF.UseShellExecute = True
    PrintPDF.Verb = "print"
    PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
    fileNameOnly = Path.GetFileName(fileName1)
    PrintPDF.FileName = strALPRMailOutReports & "\" & fileNameOnly
    Process.Start(PrintPDF)
Next

A: A simple sort will do the trick.
 Dim files() As String = IO.Directory.GetFiles("Path here")
 Array.Sort(files)
 For Each fileName1 In files
     'Print fileName1
 Next


text:
Q: Is it possible to write this nested for loop as an apply function? I have a nested for loop that is taking absolutely forever to run. The code is for running through 10 hidden units for a neural networks model fitting. I have always understood that apply functions are much faster but have not been able to implement them for more complicated tasks. I was wondering if anyone could guide me with their expertise to see if my code below is able to be run with apply functions. Thank you!
Here,
"data.file" is a list of size 10. Each element in the list is a data frame with dimensions 3067 x 58.
"test" is a data frame with dimensions of 1534 x 58
for(k in 1:10){
    mis.err <- NULL
    for(i in 1:10){
            nett <- nnet(as.factor(type) ~., data = data.file[[i]], size = k, rang=0.7, maxit = 110)
            yhat <- predict(nett, test, type="class")
           tab <- table(yhat, as.factor(test[,58]))
           err <- 1-sum(diag(tab))/sum(tab)

           if (i == 1) mis.err <- err else me <- rbind(mis.err, err)

     }

     table <- rbind(table, c(k, mis.err))

 }

My end output desire is a 10 by 2 table with the k values on the first column and the mis.err values on the second column.
Thank you!


text:
Q: Can I create a List of functions in python? I am trying to create a list of functions in my program in order to use the random module to randomly choose. in theory it look and work with this
import random

def test1():
  print("1st function")

def test2():
  print("2nd function")

def test3():
  print("3rd function")

def test_func():
  test_list = [test1(), test2(), test3()]
  apple = random.choice(test_list)
  return print(apple)

test_func()

the result of this is it prints out test_list and prints "NONE" for apple is there a way to get it to randomly pick a function and only print that function.

A: you should add function reference to the list and call the function after.
def test_func():
  test_list = [test1, test2, test3]
  apple = random.choice(test_list)()

A: Yes, just don't call the functions when you put them in the list:
import random

def test1():
  print("1st function")

def test2():
  print("2nd function")

def test3():
  print("3rd function")

def test_func():
  test_list = [test1, test2, test3]
  apple = random.choice(test_list)
  return apple() #won't return anything due to it being a print function

test_func()

A: The problem here is that you are assigning the list the return values of the functions you created. Since they do not have a return value, it will be None.
What you need to do is assign the function itself by removing the parenthesis. You would also need to call the apple function by adding the parenthesis to it, not by printing it. So, your code will look like this:
import random

def test1():
    print("1st function")

def test2():
    print("2nd function")

def test3():
    print("3rd function")

def test_func():
    test_list = [test1, test2, test3]
    apple = random.choice(test_list)
    apple()

test_func()

A: def test1():
    print("1st function")
    #This returns "None"

The reason you are getting "None" printed to console is because you are printing the function, which does return a NoneType. Return defaults to None if not specified. To make it only print the desired function remove the line return print(apple)
You would also want to store references to your functions:
test_list = [test1, test2, test3]

so that they are not executed. Then you can run apple() to execute them in your main function.


text:
Q: certificatePinner not working with okhttp throwing SSLHandshakeException: CertPathValidatorException Trust anchor for certification path not found I've taken the code from Square's own github Readme:
 @Throws(Exception::class)
 fun run() {
      val client = OkHttpClient.Builder()
                .certificatePinner(CertificatePinner.Builder()
                          .add("api.somewebsite.nl", "sha256/SOME_KEY/SOME_KEY")
                          .build())
                .build()

      val request = Request.Builder()
                .url("https://api.somewebsite.nl")
                .build()

      try {
           val response = client.newCall(request).execute()
           if (!response.isSuccessful) {
                Log.i("TestCode","is Not Successful")
                throw IOException("Unexpected code $response")
           } else {
                Log.i("TestCode","is Successful")
           }

           for (certificate in response.handshake()!!.peerCertificates()) {
                println(CertificatePinner.pin(certificate))
           }

      } catch (e: SSLHandshakeException) {
           e.printStackTrace()
      }
 }

When going to this website using Chrome it works, indicating that the App has the Comodo CA certificate on the particular phone. For the SHA256 pin value I went to this site. This site is also mentioned in this excellent walkthrough.
I've used the latest versions of the libraries:
implementation "com.squareup.retrofit2:retrofit:2.5.0"
implementation "com.squareup.retrofit2:converter-moshi:2.5.0"
implementation "com.squareup.okhttp3:okhttp:3.14.1"

Here is the Logging:
 E/Conscrypt: ------------------Untrusted chain: ----------------------
 E/Conscrypt: == Chain0 ==
     Version:   3
 E/Conscrypt:  Serial Number:   serial_number
 E/Conscrypt:  SubjectDN:   CN=*.somewebsite.nl, OU=PremiumSSL Wildcard, OU=IT, O=somewebsite B.V., STREET=some_street, L=SomeCity, ST=SomeCity, OID.2.5.4.17=POSTAL_CODE, C=NL
 E/Conscrypt:  IssuerDN:   CN=Sectigo RSA Organization Validation Secure Server CA, O=Sectigo Limited, L=Salford, ST=Greater Manchester, C=GB
 E/Conscrypt:  Get not before:   Mon May 06 02:00:00 GMT+02:00 2019
 E/Conscrypt:  Get not after:   Mon Jul 05 01:59:59 GMT+02:00 2021
 E/Conscrypt:  Sig ALG name:   SHA256withRSA
 E/Conscrypt:  Signature:   SOME_SIGNATURE
 E/Conscrypt:  Public key:

 W/System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
 W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)
 W/System.err:     at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:336)
 W/System.err:     at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:300)
 W/System.err:     at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:185)
 W/System.err:     at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.java:224)
 W/System.err:     at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.java:107)
 W/System.err:     at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.java:87)
 W/System.err:     at okhttp3.internal.connection.Transmitter.newExchange(Transmitter.java:169)
 W/System.err:     at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:41)
 W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
 W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
 W/System.err:     at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
 W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
 W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
 W/System.err:     at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
 W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
 W/System.err:     at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
 W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
 W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
 W/System.err:     at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:221)
 W/System.err:     at okhttp3.RealCall.execute(RealCall.java:81)

A: Try to Modify OkHttpClient.Builder Object: see this solution


text:
Q: DateTime format issue on StoredProcedure - C# ASP.NET x MS SQL Server 2014 I'm facing an issue while running an SQL Server 2014 stored procedure from my C# ASP.NET application (MVC 3).
When I manually run this procedure with the same parameters, it returns me all proper results. When the procedure is executed from the C# application, the "reader" comes empty, without any data. It seems to be an issue on the DateTime format. What should I do to solve it?
Here is the code:
SQL:
ALTER PROCEDURE [dbo].[my_proc]
(
    @client_code AS varchar(7),
    @begin_date AS datetime,
    @end_date AS datetime
)
AS
BEGIN
    SET NOCOUNT ON;

SELECT *
    from [dbo].[my_table] c
    WHERE c.code = @client_code
    AND c.date1 >= @begin_date
    AND c.date2 <= @end_date

END

C#:
DateTime Today = DateTime.Today;
DateTime LastYear = Today.AddYears(-1);
sql = new SqlConnection(/*my string connection*/);
sql.Open();
adapter.SelectCommand = new SqlCommand();
adapter.SelectCommand.CommandText = "dbo.my_proc";
adapter.SelectCommand.Connection = sql;
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;

param1 = adapter.SelectCommand.Parameters.Add("@client_code", SqlDbType.VarChar);
param1.Value = cod_client;

param2 = adapter.SelectCommand.Parameters.Add("@begin_date", SqlDbType.Date);
param2.Value = LastYear.ToString("yyyy-MM-dd");

param3 = adapter.SelectCommand.Parameters.Add("@end_date", SqlDbType.Date);
param3.Value = Today.ToString("yyyy-MM-dd");

reader = adapter.SelectCommand.ExecuteReader();

A: You shouldn't convert DateTime to string. just pass it "as-is" to the stored procedure. If you want just date part then use Date. Remember do not change the data type.
param2 = adapter.SelectCommand.Parameters.Add("@begin_date", SqlDbType.Date);
param2.Value = LastYear.Date;

param3 = adapter.SelectCommand.Parameters.Add("@end_date", SqlDbType.Date);
param3.Value = Today.Date;

A: Try the AddWithValue method wich is less verbose and can identify the DataType of the parameter on the fly:
        adapter.SelectCommand.Parameters.AddWithValue("@client_code", cod_client);
        adapter.SelectCommand.Parameters.AddWithValue("@begin_date", LastYear.Date);
        adapter.SelectCommand.Parameters.AddWithValue("@end_date", Today.Date);


text:
Q: Django admin change plural model names My Django (Grappelli theme) admin lists all my apps and then the model names are displayed in plural form. To convert the name to plural, Django adds an 's' to the name of the model, however some of these are incorrect.  For example, 'Product categories' becomes 'Product categorys'
How can I change the names displayed in the admin views for these?

A: You need to specify a verbose_name_plural attribute in your model's Meta subclass.
Check: https://docs.djangoproject.com/en/1.10/ref/models/options/#django.db.models.Options.verbose_name_plural for more info.


text:
Q: Multiple method calling using single servlet I am new to JavaEE and have a query regarding a servlet that has multiple methods.
I want to know how I can call a specific method on a servlet, when I click "Submit" button in JSP.?
Someone have suggested to use HTML hidden fields but I have no idea on how to implement them in Jsp.

A: You can just give the submit button a specific name.
<input type="submit" name="action1" value="Invoke action 1" />
<input type="submit" name="action2" value="Invoke action 2" />
<input type="submit" name="action3" value="Invoke action 3" />

The name-value pair of the pressed button is available as request parameter the usual way.
if (request.getParameter("action1") != null) {
    // Invoke action 1.
}
else if (request.getParameter("action2") != null) {
    // Invoke action 2.
}
else if (request.getParameter("action3") != null) {
    // Invoke action 3.
}

A: Hidden fields in  a JSP are the same as in HTML:
<input type="hidden" name="name" value="value">

Then in your servlet you can do
if (request.getParameter("name").equals("value")) { /* do something */ }

A: Depends on which method you want to call. Assuming that the URL Pattern declared for your servlet in web.xml is /myservlet*,
For doGet, just use a URL
http://localhost:8080/myservlet?name=value

For doPost, use a form.
<form action="/myservlet" method="post">
    <input type="text" value="value" name="name" />
</form>

A: i dont think having 3 buttons is the best solution,basis on the logic and parameters method asked,
i believe this can be an accurate solution-
On the basis of parameters passed ,we can have 2 methods to access different actions via javascript-
1)getting values from user,checking them in javascript.
2)getting values from user,checking them in javascript,assigning values to hidden variables accordingly,calling servlets and using those hidden values.i have elaborated method1.
    <html>
<head>
    <script type="text/javascript">
    function nawab() {
    param = document.getElementById('param1').value;
    alert('in nawab');
    if (param != "") {
    if (param === 'abc') {
          alert('abc');
          document.forms[0].action = "nawabServlet";
          document.forms[0].submit();
    }
    if (param === 'def') {
     alert('def');
     document.forms[0].action = "nawabServlet2";
     document.forms[0].submit();
     }
}
else{
      alert('empty');
      document.forms[0].action = "nawabServlet";
      document.forms[0].submit();
     }
 }
 </script>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <title>nawab has come</title>
 </head>
 <body>
  <form>
        param1:<input type="text" name="param1" id="param1"></select>
        <input type="submit" onclick="nawab()">
   </form>
  </body>
</html>


text:
Q: Increment Serial Number using EXIF I am using ExifTool to change the camera body serial number to be a unique serial number for each image in a group of images numbering several hundred.  The camera body serial number is being used as a second place, in addition to where the serial number for the image is in IPTC, to put the serial number as it takes a little more effort to remove.
The serial number is in the format ###-###-####-#### where the last four digits is the number to increment.  The first three groups of digits do not change for each batch I run.  I only need to increment that last group of digits.
EXAMPLE
I if I have 100 images in my first batch, they would be numbered:
811-010-5469-0001, 811-010-5469-0002, 811-010-5469-0003 ... 811-010-5469-0100
I can successfully drag a group of images onto my ExifTool Shortcut that has the values
exiftool(-SerialNumber='001-001-0001-0001')

and it will change the Exif SerialNumber Tag on the images, but have not been successful in what to add to this to have it increment for each image.
I have tried variations on the below without success:
exiftool(-SerialNumber+=001-001-0001-0001)
exiftool(-SerialNumber+='001-001-0001-0001')

I realize most likely ExifTool is seeing these as numbers being subtracted in the first line and seeing the second line as a string.  I have also tried:
exiftool(-SerialNumber+='1')
exiftool(-SerialNumber+=1)

just to see if I can even get it to increment with a basic, single digit number.  This also has not worked.
Maybe this cannot be incremented this way and I need to use ExifTool from the command line.  If so, I am learning the command line/powershell (Windows), but am still weak in this area and would appreciate some pointers to get started there if this is the route I need to take.  I am not afraid to use the command line, just would need a bit more hand holding then normal for a starting point.  I also am learning Linux and could do this project from there but again, not afraid to use it, just would need a bit more hand holding to get it done.
I do program in PHP, JavaScript and other languages so code is not foreign to me.  Just experience in writing it for the command-line.
If further clarification is needed, please let me know in the comments.
Your help and guidance is appreciated!

A: If I understand your question correctly, something like this should work:
1..100 | % {
  $sn = '811-010-5469-{0:D4}' -f $_

  # apply $sn
}

or like this (if you iterate over files):
$i = 1
Get-ChildItem 'C:\some\folder' -File | % {
  $sn = '811-010-5469-{0:D4}' -f $i

  # update EXIF data of current file with $sn

  $i++
}

A: You'll probably have to go to the command line rather than rely upon drag and drop as this command relies upon ExifTool's advance formatting.
Exiftool "-SerialNumber<001-001-0001-${filesequence;$_=sprintf('%04d', $_+1 )}" <FILE/DIR>
If you want to be more general purpose and to use the original serial number in the file, you could use
Exiftool "-SerialNumber<${SerialNumber}-${filesequence;$_=sprintf('%04d', $_+1 )}" <FILE/DIR>
This will just add the file count to the end of the current serial number in the image, though if you have images from multiple cameras in the same directory, that could get messy.
As for using the command line, you just need to rename to remove the commands in the parens and then either move it to someplace in the command line's path or use the full path to ExifTool.
As for clarification on your previous attempts, the += option is used with numbers and with lists.  The SerialNumber tag is usually a string, though that could depend upon where it's being written to.


text:
Q: How to create fixed column width table inside a document using docx I am using docx npm to create a small report (word document) in angular 6.
I need to have a table with fixed column width so that whatever text is written inside it, it should get wrapped within the cell.
I have tried several options but unable to achieve this.
Appreciate your help on this.


text:
Q: C# syntax highlighting doesn't highlight newer keywords (including "await" and "yield") I noticed the C# keywords yield, await and async are not correctly highlighted by the C# syntax highlighter.
E.g.: Proper use of 'yield return', C# Socket.BeginReceive/EndReceive
Can these keywords be added to the formatter?


text:
Q: Create list of column names for insert into table I'm working on a query where I need to insert rows into a table and a temp table that have the same column names.
I would like to avoid repeating the column names in each insert statement and would prefer to create a list and just pass the list to the insert statements.
Here's what I have so far:
DECLARE @columnNameList varchar(MAX) = COALESCE(RecType, ColumnName,
    SourcePosition, MaxWidth, isNullable, dotNetDataType, [Format])

EXEC('INSERT INTO #RowList (' + @columnNameList + ')
    VALUES......

This almost works. I get an error for each column name that looks like this:

Invalid column name 'RecType'

I think the error is because the column name has single quotes around it as it is being converted to a string.
Is there a way to build a list of column objects rather than strings to pass in?

A: You can create a single line with all the columns of your table (myTableName here) separated with commas with STUFF and XML PATH
select STUFF((select ','+a.name
  from sys.all_columns a join sys.tables t
    on a.object_id = t.object_id
   and t.name = 'myTableName'
order by a.column_id
for xml path ('')
),1,1,'')

OUTPUT
column1,column2,...,columnN

A: Try this query below.
create table #rowlist (RecType int, ColumnName int,
    SourcePosition int, MaxWidth int, isNullable int, dotNetDataType int, [Format] int)

DECLARE @columnNameList nvarchar(MAX) ='(RecType, ColumnName,
    SourcePosition, MaxWidth, isNullable, dotNetDataType, [Format])'

DECLARE @SQLCMD nvarchar(MAX) =N'INSERT INTO #RowList ' + @columnNameList + N' VALUES (1,1,1,1,1,1,1)'

exec(@sqlcmd)


text:
Q: Localhost tcp throughput performance differences I have been using psping for measuring bandwith statistics on localhost on different computers: laptops, home computers and servers. All of them get to between 100 and 200 MB/s but my PowerPc at work manages to get to 800 MB/s.
What can cause these huge differences communicating with itself over localhost? The PowerPc outperforms all other devices I've tested with a factor 4 to 8.
PowerPc configuration

*

*Windows 7

*Intel(R) Xeon(R) CPU E3-1240 v3 @ 3.40GHz [Family 6 Model 60 Stepping 3]

*3.78 GFLOPS/core

*Symantec SEP

A Home computer configuration

*

*Windows 8.1

*Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz [Intel64 Family 6 Model 26 Stepping 5]   4

*2.64 GFLOPS/core

*BitDefender

psping command
psping -4 -b -l 8k -n 20000 localhost:1234

A few questions I expect to get and like to address up front I might be way off but this shows you my current understanding of things, feel free to set me straight.

*

*Antivirus related
I have turned of the antivirus component om my Home Computer without any noticable difference. Further, I have captured a WPA trace (XperfScripts) and the modules that have most CPU related activity are ntoskrnl.exe, netio.sys, tcpip.sys, ndis.sys and afd.sys. The first AV module that comes into the picture CPU related is avcuf32.dll accounting for 0.17% of total CPU.

*Localhost vs. 127.0.0.1
I have tried both and got the same results on all tested computers.

*Up-to-date drivers
The drivers on my Home computer are up-to-date. The drivers on the PowerPc are managed by our IT staff and lag behind somewhat but not that much (and the PowerPc is 4x faster on the tests anyway)

*netsh int tcp show global
There are some differences between both PC's. Chimney Offload State and NetDMA State on my Home Computer are disabled while on the PowerPc they are automatic and enabled.
My networking-fu is not good enough to know if that could explain for the differences but reading up on the subject, I doubt it is.

Edit
RAM details PowerPC
  capacity speed memorytype totalwidth datawidth typedetail
  -------- ----- ---------- ---------- --------- ----------
4294967296  1600          0         64        64        128
4294967296  1600          0         64        64        128
4294967296  1600          0         64        64        128
4294967296  1600          0         64        64        128

RAM details Home computer
    capacity speed memorytype totalwidth datawidth typedetail
  -------- ----- ---------- ---------- --------- ----------
2147483648  1333          1         72        64          2
4294967296  1333          1         72        64          2
2147483648  1333          1         72        64          2
4294967296  1333          1         72        64          2
2147483648  1333          1         72        64          2
4294967296  1333          1         72        64          2
   4194304    33         11          8         8       4096

A: I believe that the reason that the PowerPC on Windows 7 is much faster on localhost
loopback throughput, is because it can use NetDMA.
The Microsoft article NetDMA (Windows Drivers) defines NetDMA as :

The NetDMA interface provides a generic interface for memory-to-memory
  direct memory access (DMA) transfers. Although the interface is
  designed to copy packets that are received from high-performance
  network interface cards (NICs), you can also use the interface for
  other applications. There is no direct relationship between NetDMA and
  NDIS.

When using localhost loopback, it stands to reason that
memory copy operations are the main factor of throughput,
as frames are copied from the source-application memory, then between TCP layers
and finally to the memory of the target-application.
NetDMA can have an impact, since it allows network adapters to transfer data directly to your application, perhaps this way reducing the number of memory copies
even for the trivial loopback adapter.
Enabling NetDMA can be done in two ways :

*

*Enter netsh int tcp set global netdma=enabled in Command Prompt (cmd)
that is run as Administrator, then reboot.

*Regedit to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters and create a new DWORD item named EnableTCPA with the value 1, then reboot.

However, there are two prerequisites to enabling NetDMA :

*

*The Microsoft article Enabling NetDMA has this :

NetDMA must be enabled in the BIOS before performing this procedure.
  NetDMA support is often labeled IOAT support.

*The Microsoft article NetDMA (Windows Drivers) has this note :

The NetDMA interface is not supported in Windows 8 and later.

Putting both these requirements together, I can hazard the guess that,
as NetDMA is a BIOS function, it was not implemented in UEFI which is
used in Windows 8/2012.
Microsoft had therefore to improve localhost loopback
throughput in another way, especially for using in
Hyper-V, and had therefore created in Windows 8/2012 the Fast TCP Loopback,
defined as :

TCP Loopback Fast Path is a new feature introduced in Windows Server
  2012 and Windows 8. If you use the TCP loopback interface for
  inter-process communications (IPC), you may be interested in the
  improved performance, improved predictability, and reduced latency the
  TCP Loopback Fast Path can provide.  This feature preserves TCP socket
  semantics and platform capabilities including the Windows Filtering
  Platform (WFP), and works on both non-virtualized and virtualized
  operating system instances.
The TCP loopback interface provides a simple local IPC mechanism for
  processes on the same operating system instance, and it can easily be
  switched to a remote IPC mechanism by simply changing the destination
  IP address.

Unfortunately, Fast TCP Loopback is not transparent, requiring applications to
issue a WSAIoctl system call on the sockets for both sender and receiver,
therefore not being backward-compatible with existing bandwidth-measuring applications
such as PsPing and PCATTCP.
In my own tests on Windows 7, I have not fathomed all the mysteries surrounding NetDMA,
but I have managed to briefly turn it on, with the immediate benefit of doubling
my bandwidth as measured by PsPing. But as NetDMA did not survive a reboot
on that computer,
I do not recommend depending on it for throughput even
on computers that theoretically support it.


text:
Q: Google Apps email forwarding from non-existing email addresses We're planning to move all our corporate emails to Google Apps, but I couldn't find an answer to the following question anywhere. Hope anybody will help.
Currently, we have 10 real email addresses (that is, for everyone in our organization) plus a handful of administrative ones (like support@, registrationrequest@, etc.). After moving to Google Apps I'm only planning to keep these 10 "real" addresses and leave support@ as the only "administrative" address: there's no benefit in paying 50$ a year for an address which will receive a dozen emails a year.
So here's my problem: is it possible to tell Google Apps to forward all emails sent to an unknown (unregistered) address to a particular email box so that all emails sent to, say, registrationrequest@ will eventually end up in support@?

A: This is called a "catch-all" address: there is information on setting this up at http://www.google.com/support/a/bin/answer.py?hl=en&answer=33962
Note that this is a good way to get a lot of spam, but hopefully that will all get filtered.

A: Those administrative accounts could be handled by creating groups within Google Apps that then redirect mail to one or more individual e-mail accounts. Google doesn't charge for the group addresses. Also, Google just added support for Google Groups like functionality within Google Apps, so the groups can be more like discussion forums.
You can also create aliases for each e-mail account so that antong@ would receive e-mail for support@ and sales@. Since Google only charges you for the primary account and mailbox you get the aliases for free. However, groups are the more flexible way of handling this.


text:
Q: Magento 1.7 language switcher on category page removes store code from URL I have read a lot about the issue on stack but could not find a similar issue.
On magento 1.7
The language switcher on a my category pages removes store code from URL's.
     site.com/store/pt/vestidos
     --> site.com/store/dresses
 while it should be site.com/store/en/dresses
Strangely enough, this does not happen with products
     site.com/store/pt/product_in_portuguese.html
     --> site.com/store/en/product_in_english.html
Another maybe related issue is that on my store home I also get an error upon language switch
     www.site.com/store
     --> which through .htaccess redirects to www.site.com/store/pt
when I use the language switch there
     --> site.com/store/en/?___from_store=pt gives me
  "There was no Home CMS page configured or found"
while going to site.com/store/en/home works just fine.
My configuration
Add storecode to URL's - Yes
mod-rewrite enabled


text:
Q: How to share one method to all controllers in Laravel? How to share one method to all controllers with different DI, view and parameters? I need something like this:
public function method(Model $model)
    {
        $baseData = [
            'model' => $model,
            'route' => route('$route', [$param => $model]),
        ];

        return view($view);
    }

A: All controllers extend App\Http\Controllers\Controller so you can just place it there
<?php

namespace App\Http\Controllers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function method(Model $model, $route, $param, $view)
    {
        // Declared but not used
        $baseData = [
            'model' => $model,
            'route' => route($route, [$param => $model]),
        ];

        return view($view);
    }
}

And use it with $this->method()
For example in HomeController
<?php

namespace App\Http\Controllers;

use App\User;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $user = User::first();
        return $this->method($user, 'home', 'user', 'welcome');
    }
}

Now accessing domain.tld/home will return the welcome view

A: If you want to share function to all controller best way will make service in service folder of app.
step to make service:-
1.create service using artisan command
php artisan make:service service_name and define function that to share to all controller in your project.

*after making service your have to register this service with provider.make a provider using artisan command.
php artisan make provider:provider_name and you will see 2 function register and boot
register function is used to register your created service and boot for call already register service

register service like this

public function register()
    {
         $this->app->bind('App\Services\servicename', function( $app ){
            return new serviceclassname;
        });
    }

3.Go config folder ,open app.php where you will get providers array. In this provider you have to define you provider like App\Providers\providerclassname::class,

*call this service in controllers like use App\Services\serviceclassname;

public function functionname(serviceclassname serviceobject)
{
  serviceobject->functionname();
}