text:
Q: Replacing double backslash and brackets in Python I am trying to write a script that could convert things like \\[ or \\] to $$ in order to convert a MultiMarkdown document to Pandoc markdown document that could display equations in HTML. I am using Python to find all instances of these characters using
 matchstring=r'\\['
 re.sub(matchstring,'$$',content)

However I run into the following error:
unexpected end of regular expression:line 15:matchstring=re.compile(r'\\[')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 190:
return _compile(pattern, flags)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 245:
raise error, v # invalid expression

most likely because of the last [ I have in there. Does anyone know a way to get around this?

A: Escape the [:
matchstring=re.compile(r'//\[')

Or better yet, use:
content.replace("//[", "$$")

and don't involve regex at all.

A: pandoc -f markdown_mmd -t markdown

will do this for you!  (For pandoc >= 1.11)

A: Your problem is that you write r'//[', not r'\\[',
but anyway try better this:
matchstring.replace(r'\\[', '$$').replace(r'\\]', '$$')

A: if you are using a "[" within your regex, I would assume it would be required to have an escape for it as it is used within regular expression.
try one of the following:
content = "testing123//]testing456"
matchstring = "//]"
result = content.replace(matchstring, "$$")
print result

or
content = "testing123//]testing456"
matchstring = '(//\])'
result = re.sub(matchstring,'$$',content)
print result

Either should work for your purpose.


text:
Q: How can I populate content from a facebook page using Opengraph without using a facebook app ? is that possible? So I'm told to do this not so clear  project where I am supposed to create a facebook page and populate it with content from another facebook page using opengraph . For this project , I do not have to use a facebook app... How can I achieve this in PHP using Opengraph ??
    1.     Create a Facebook fan page and populate content from Facebook.com/TomClancyAuthor (six pieces will be sufficient for this exercise)

    2.       Set the 'Age Restriction' to 'people 17 and over'

    3.       Using Open Graph, consume and display the content of the age restricted Facebook fan page on a website

Note: Do NOT use a Facebook app for this project

A: Your question is a contradiction, you can't use the 'Open Graph' without a 'Facebook App', as you need an app ID to access anything via Facebook's API unless that information is completely public and needs no authentication.
A page which is restricted by age or geographic location can only be accessed using an access token from a user that meets those requirements, which means you need such a user to grant your app ID access to access the API on their behalf.
I suspect whoever used the phrase 'Facebook App' in the question doesn't understand how the Facebook API works, or is asking you to avoid a specific way of implementing this without clarifying what that method is

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple math, not sure what it is accomplishing (line segment intersection) The problem of line segment intersection seems simple enough using orientation, but the explanation in this blog leading up to formula used says one thing, and the math used is doing another.

The solution involves determining if three points are listed in a
  counterclockwise order. So say you have three points A, B and C. If
  the slope of the line AB is less than the slope of the line AC then
  the three points are listed in a counterclockwise order.

http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
If you look at the function, that is not using slopes to compare as was just stated, I am not sure what he is doing. Regardless, I plugged in some test values and it does indeed work, but it is not "slope" as is described in the blog.
Am I missing something simple here?

A: if you have two points $A=(a_x, a_y)$ and $B=(b_x, b_y)$ then the slope $m_{AB}$ of the line from $A$ to $B$ is  $$ \frac{\Delta y}{\Delta x} = \frac{b_y-a_y}{b_x - a_x}$$
Similarly for $m_{AC}$. So $AC$ is steeper than $AB$ if
$$\frac{c_y-a_y}{c_x - a_x} =m_{AC}> m_{AB} = \frac{b_y-a_y}{b_x - a_x}$$
Now just multiply by the denominators.

A: To compare two ratios, it is more efficient to remove the denominators:
$$\frac ab<\frac cd\iff ad<bc.$$
This avoids divisions.


text:
Q: Nullpointer exception while Creating records and inserting values in database- also using SQL-cipher Cipher for my database , i am trying to insert the record values but i am getting nullpointer exception while creating the record and inserting the values, below is my Databasehelper code
public class DatabaseHelper extends SQLiteOpenHelper {
             public static final String KEY_ROWID = "_id";
             public static final String KEY_CODE = "code";
             public static final String KEY_NAME = "name";
             public static final String KEY_CONTINENT = "continent";
             public static final String KEY_REGION = "region";
             public static final String KEY_AREA = "area";

             private static final String TAG = "CountriesDbAdapter";
             private DatabaseHelper mDbHelper;
             private SQLiteDatabase mDb;
             String password = "foo123";

             private static final String DATABASE_NAME = "salesreports";
             private static final String SQLITE_TABLE = "salesandreports";
             private static final String SQLITE_TABLE1 = "salescharts";
             private static final int DATABASE_VERSION = 1;

             private static final String DATABASE_CREATE =
              "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
              KEY_ROWID + " integer PRIMARY KEY autoincrement," +
              KEY_CODE + " INTEGER," +
              KEY_NAME + " INTEGER," +
              KEY_CONTINENT + " INTEGER," +
              KEY_REGION + " INTEGER," +
              KEY_AREA + " INTEGER" +
             ")";

        @Override
        public void onCreate(SQLiteDatabase db) {
             db.execSQL(DATABASE_CREATE);

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);

               onCreate(db);

        }

         public long createsalesCountry(String code, String name,
           String continent, String region,String area) {

          ContentValues initialValues = new ContentValues();
          initialValues.put(KEY_CODE, code);
          initialValues.put(KEY_NAME, name);
          initialValues.put(KEY_CONTINENT, continent);
          initialValues.put(KEY_REGION, region);
          initialValues.put(KEY_AREA, area);

          return mDb.insert(SQLITE_TABLE, null, initialValues);

         }

         public boolean deleteAllCountries() {

          int doneDelete = 0;
          doneDelete = mDb.delete(SQLITE_TABLE, null , null);
          Log.w(TAG, Integer.toString(doneDelete));
          return doneDelete > 0;

         }

         public Cursor fetchCountriesByName(String inputText) throws SQLException {
          Log.w(TAG, inputText);
          Cursor mCursor = null;
          if (inputText == null  ||  inputText.length () == 0)  {
           mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
             KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION,KEY_AREA},
             null, null, null, null, null,null);

          }
          else {
           mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
             KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION,KEY_AREA},
             KEY_NAME + " like '%" + inputText + "%'", null,
             null, null, null, null);
          }
          if (mCursor != null) {
           mCursor.moveToFirst();
          }
          return mCursor;

         }

         public Cursor fetchAllCountries() {

          Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
            KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION,KEY_AREA},
            null, null, null, null, null,null);

          if (mCursor != null) {
           mCursor.moveToFirst();
          }
          return mCursor;
         }

         public void insertsalesvalues() {

          createCountry("1","1","1","1","1");}}

and below is my activity
 public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            LayoutToDisplayChart=(LinearLayout)findViewById(R.id.relative_layout1);
            SQLiteDatabase.loadLibs(this);

            String password = "foo123";
            dbHelper = new DatabaseHelper(this);
            SQLiteDatabase db = dbHelper.getWritableDatabase(password);
            //dbHelper.insertsalesvalues();
            dbHelper.insertSomeCountries();
            Intent achartIntent = new aChart_Example().execute(MainActivity.this,LayoutToDisplayChart);

Below is my trace
Caused by: java.lang.NullPointerException
09-17 11:02:01.500: E/AndroidRuntime(27757):    at com.example.mychartapp.DatabaseHelper.createsalesCountry(DatabaseHelper.java:113)
09-17 11:02:01.500: E/AndroidRuntime(27757):    at com.example.mychartapp.DatabaseHelper.insertsalesvalues(DatabaseHelper.java:198)
09-17 11:02:01.500: E/AndroidRuntime(27757):    at com.example.mychartapp.MainActivity.onCreate(MainActivity.java:26)

A: Adding this line solved my problem   **SQLiteDatabase mDb = this.getWritableDatabase(password);**
  public long createsalesCountry(String code, String name,
               String continent, String region,String area) {
                 **SQLiteDatabase mDb = this.getWritableDatabase(password);**
              ContentValues initialValues = new ContentValues();
              initialValues.put(KEY_CODE, code);
              initialValues.put(KEY_NAME, name);
              initialValues.put(KEY_CONTINENT, continent);
              initialValues.put(KEY_REGION, region);
              initialValues.put(KEY_AREA, area);

              return mDb.insert(SQLITE_TABLE, null, initialValues);

             }

    public void insertSalesvalues() {
                 **SQLiteDatabase mDb = this.getWritableDatabase(password);**
              createCountry("1","1","1","1","1");

             }

A: First thing you have to do is, check where you have your database file, whether in your assets, or /data/data/your package name/your_application_name. If it is in your assets, you have to copy it to your /data/data/your package name/ folder. Then, after copying your DB file, save that DB file to your PC, check the structure of the database file, the data present in it(if any). You are telling that, you could not insert or retrieve any data right? By checking your database file in this way, you can understand your mistake in the back-end. But, to my knowledge, I did not find any mistake in your code.


text:
Q: Triple even-sized windows in Emacs on startup I would like to set up Emacs to maximize (or specific size) and split my window horizontally into three equally sized frames on start up.
I have found other questions that are similar but not quite, Q1 and Q2.
Thank you.
EDIT: Maximize, not fullscreen.

A: To have equally sized windows you can use the command balance-windows (bound to C-x + for interactive use).

A: Okay here is what I come up, There will be more elegant way to it. Nonetheless this does you want.
  (defun split-windows-even-3 ()
    "split into 3 evenly"
    (interactive)
    (save-excursion
      (let ((ps (window-width)))
        (split-window-horizontally (/ ps 3))
        (other-window 1)
        (split-window-horizontally (/ ps 3)))))

  ;;; ADD HOOKS to startup
  ;;  split three
  (add-hook 'emacs-startup-hook 'split-windows-even-3)

  ;; Fullscreen
  (add-hook 'emacs-startup-hook (lambda ()
                                  (set-frame-parameter nil 'fullscreen 'fullboth)))

UPDATE: now its working emacs23 and emacs24


text:
Q: How to solve dependecies for CEGUI on Ubuntu I've downloaded CEGUI source from official site. I tried to compile it. First I installed cegui-mk2* packages, because I read that it's necessary dependencies. After that compilation complited successfully.
But README.md says that in build folder should be bin folder, but in my case there is only lib folder. It also says that if I install (make install) cegui system wide I should be able to run samples just by typeing sample name in terminal. But I can't, and I suppose thats because samples are not even compiled, they should be in bin folder, I suppose.
cmake gives me this output:
-- Could NOT find MINIZIP (missing: MINIZIP_LIB MINIZIP_H_PATH)
-- Could NOT find OpenGL (missing: OPENGL_gl_LIBRARY)
-- Could NOT find GLEW (missing: GLEW_LIB GLEW_H_PATH)
-- Could NOT find GLM (missing: GLM_H_PATH)
-- Could NOT find GLFW (missing: GLFW_LIB GLFW_H_PATH)
-- Could NOT find DIRECTXSDK (missing: DIRECTXSDK_LIB_PATH DIRECTXSDK_H_PATH DIRECTXSDK_MAX_D3D)
-- Could NOT find D3DX11EFFECTS (missing: D3DX11EFFECTS_LIB D3DX11EFFECTS_H_PATH)
-- Could NOT find IRRLICHT (missing: IRRLICHT_LIB IRRLICHT_H_PATH)
-- Could NOT find OGRE (missing: OGRE_LIB OGRE_H_PATH OGRE_H_BUILD_SETTINGS_PATH)
-- Could NOT find OIS (missing: OIS_LIB OIS_H_PATH)
-- Could NOT find DIRECTFB (missing: DIRECTFB_LIB DIRECTFB_H_PATH)
-- Could NOT find OPENGLES (missing: OPENGLES_LIB OPENGLES_H_PATH)
-- Could NOT find EXPAT (missing: EXPAT_LIB EXPAT_H_PATH)
-- Could NOT find XERCESC (missing: XERCESC_LIB XERCESC_H_PATH)
-- Could NOT find LibXml2 (missing: LIBXML2_LIBRARIES LIBXML2_INCLUDE_DIR)
-- Could NOT find TINYXML (missing: TINYXML_LIB TINYXML_H_PATH)
-- Could NOT find RAPIDXML (missing: RAPIDXML_H_PATH)
-- Could NOT find SILLY (missing: SILLY_LIB SILLY_H_PATH)
-- Could NOT find CORONA (missing: CORONA_LIB CORONA_H_PATH)
-- Could NOT find PVRTOOLS (missing: PVRTOOLS_LIB PVRTOOLS_H_PATH)
-- Could NOT find PythonLibs (missing: PYTHON_INCLUDE_DIRS)
-- Could NOT find Boost
-- Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
-- Some or all of the gtk libraries were not found. (missing: GTK2_GTK_LIBRARY GTK2_GTK_INCLUDE_DIR GTK2_GLIB_INCLUDE_DIR GTK2_GLIBCONFIG_INCLUDE_DIR GTK2_GLIB_LIBRARY GTK2_GDK_INCLUDE_DIR GTK2_GDKCONFIG_INCLUDE_DIR GTK2_GDK_LIBRARY)
CMake Warning at CMakeLists.txt:340 (message):
None of the XML parser modules are going to be built.

You should ensure that CEGUI_OPTION_DEFAULT_XMLPARSER is set to something

appropriate.

-- Configuring done
-- Generating done
-- Build files have been written to:

But I need EXPAT, and ogre and and lua (and maybe opengl) with cegui. So I installed expat package via apt-get. But still it says that EXPAT is not found. I suppose that I didn't get samples because they depend on some of this packages.
There is no expat-dev package. Should I get source for other source than and compile it, and than include it some how to make cmake and CEGUI aware of that.
I don't know how to do it really.
What I would like the most is to get source for all dependencies, so I can cross compile it for other linux machines.
How to solve this problem?
Thank you.
Please help.


text:
Q: Is there a workaround to outdated VMWare certificate? Last time I set up VMWare I did this workaround due to the outdated certificate. How can I make my installed client not care? It should work as I have done it before.
Klient version is 5.1.1. Does anyone know?


text:
Q: Skip DataMember via DataContractSerializer I have a class:
[DataContract]
public class Result
{
  [DataMember] public String Log {get; set;}
  [DataMember] public String Data {get; set;}
}

I send this class via WCF and it works fine. But I want to save this class to a xml file after receiving. I try to write:
var serializer = new DataContractSerializer(typeof (T),null,int.MaxValue,
    false,true,null,new SharedTypeXmlResolver());
var settings = new XmlWriterSettings { Indent = true };
using (var backing = new StringWriter(CultureInfo.InvariantCulture))
{
    using (var writer = XmlWriter.Create(backing, settings))
    {
        serializer.WriteObject(writer, result);
    }
    return backing.ToString();
}

But I want to save "Log" property to an XML file and don't want to save "Data" property. How I do this?

A: XmlIgnore does not work with DataContract serialization. This contract is opt-in, as opposed to Serializable being opt-out.

A: Make Data optional:
[DataMember(EmitDefaultValue = false)] public String Data {get; set;}

Then erase Data:
result.Data = null;


text:
Q: Word frequency in a string without spaces and with special characters? Let's say I have the following string:
"hello&^uevfehello!`.<hellohow*howdhAreyou"

How would I go about counting the frequency of english words that are substrings of it? In this case I would want a result such as:
{'hello': 3, 'how': 2, 'are': 1, 'you': 1}

I searched previous question which were similar to this one but I couldn't really find anything that works. A close solution seemed to be using regular expressions, but it didn't work either. It might be because I was implementing it wrong since I'm not familiar with how it actually works.
How to find the count of a word in a string?
it's the last answer
from collections import *
import re

Counter(re.findall(r"[\w']+", text.lower()))

I also tried creating a very bad function that iterates through every single possible arrangement of consecutive letters in the string (up to a max of 8 letters or so). The problem with doing that is
1) it's way longer than it should be and
2) it adds extra words. ex: if "hello" was in the string, "hell" would also be found.
I'm not very familiar with regex which is probably the right way to do this.

A: d, w = "hello&^uevfehello!`.<hellohow*howdhAreyou", ["hello","how","are","you"]
import re, collections
pattern = re.compile("|".join(w), flags = re.IGNORECASE)
print collections.Counter(pattern.findall(d))

Output
Counter({'hello': 3, 'how': 2, 'you': 1, 'Are': 1})

A: from collections import defaultdict

s = 'hello&^uevfehello!`.<hellohow*howdhAreyou'
word_counts = defaultdict(lambda: 0)

i = 0
while i < len(s):
    j = len(s)
    while j > i:
        if is_english_word(s[i:j]):
            word_counts[s[i:j]] += 1
            break
        j -= 1

    if j == i:
        i += 1
    else:
        i = j

print word_counts

A: You need to extract all words from the string, then for each word you need to find substrings and then check if any of the substring is english word. I have used english dictionary from answer in How to check if a word is an English word with Python?
There are some false positives in the result however so you may want to use better dictionary or have a custom method to check for desired words.
import re
import enchant
from collections import defaultdict

# Get all substrings in given string.
def get_substrings(string):
    for i in range(0, len(string)):
        for j in range(i, len(string)):
            yield s[i:j+1]

text = "hello&^uevfehello!`.<hellohow*howdhAreyou"

strings = re.split(r"[^\w']+", text.lower())

# Use english dictionary to check if a word exists.
dictionary = enchant.Dict("en_US")
counts = defaultdict(int)
for s in strings:
  for word in get_substrings(s):
      if (len(word) > 1 and dictionary.check(word)):
          counts[word] += 1

print counts

Output:

defaultdict(, {'are': 1, 'oho': 1, 'eh': 1, 'ell': 3,
  'oh': 1, 'lo': 3, 'll': 3, 'yo': 1, 'how': 2, 'hare': 1, 'ho': 2,
  'ow': 2, 'hell': 3, 'you': 1, 'ha': 1, 'hello': 3, 're': 1, 'he': 3})


text:
Q: WPF integrate Windows live authentication for Microsoft health vault I'm just wondering if there's any way for WPF application integrated with windows live ID?
and it's actually for windows health vault [www.healthvault.com]
so health vault is using windows live id or open id to login into their system.
and what i gonna do is, creating wpf application (instead of web application) for health vault, so all of the login form username pass and everything is handled inside the wpf application without showing/using any internet browser.
so since this's quite new for me, i hope if there's somebody ever did this before especially for health vault system that run on standalone wpf app.
alright, so that's it,
thank you in advance!

A: You need to use "offline" authentication, instead of "online" authentication.
Online authentication requires the user to login every time through a web browser.  This is good for web applications, but not good for applications like your's.
Offline authentication lets your application access the user's HealthVault record any time it wants to.  The user never has to login.  To use this, the user must go through a one time connection process.  This is done using a connect-request.  After the user goes through this process, your application is given two authentication tokens: a person-id and a record-id.  These are what your application uses to connect to the user's HealthVault record, so they should be saved to a database or somewhere similar.
This MSDN page should help: http://msdn.microsoft.com/en-us/healthvault/cc507205.aspx


text:
Q: Why we have introduced linear algebra? I am new to linear algebra and am trying to find the motivation behind defining it in such a way and need for defining it.  To study $2$-D,$3$-D space we have geometry, so why do we need linear algebra then?
Why did they choose the exact properties which a vector space should have? I haven't found any satisfactory answer. The text books directly starts with the theory.
Can anyone explain please?
Edit: "Why we study linear algebra?" is different from my question. That question need the applications of linear algebra, I already know that and there are many source to answer that question. What I need is background of introduction to linear algebra, not only the history, also the motivation behind choosing the properties that need to be satisfied to be a vector space - why not extra why not less? Will taking extra or less condition give something which is not very useful? Please explain it.

A: In addition to other answers and comments:

*

*linear algebra affords having a geometric intuition with things that are not naturally geometric. For instance, with linear algebra, you can deal with spaces of polynomials, of functions... and you can apply the same reasonings with polynomials, functions... in these spaces more or less as if you were dealing with vectors in $\Bbb R^n$. That explains the first difficulty in linear algebra: the definition of a vector space is quite abstract at first sight. But it's precisely that abstraction which explains the great power of linear algebra (and it's often the case in maths in general) because it's that abstraction which affords applying the same language and the same theorems to so different mathematical objects.

*consequently, linear algebra is part of the common language of all mathematicians. It's quite frequent to hear, at a higher level, that something "is simply linear algebra" to say that what remains to do should be easy for every mathematician listening to this conversation.
Moreover, and simpler than the other points I mentioned: we need more than 2 or 3 dimensions! Many examples:

*

*in physics when they add time as a 4th dimension and some advanced theories like string theory use at least 10 dimensions (!) to describe reality

*in functional analysis, the goal is to study spaces of functions (e.g. spaces of continuous functions on an interval, or differentiable, or integrable, or being the solutions of a particular differential equation or PDE) which can even have infinitely many dimensions!

*in statistics, you may need more to study than 2 or 3 variables because in real life, a same phenomenon may depend on lot more than 2 or 3 parameters (e.g. weather can depend on temperature, wind speed, pressure, precipitations, humidity...) or you may want to compare more than 2 or 3 parameters (for instance, compare unemployment rate in 20 different countries).

A: This part from the Wikipedia article on linear algebra is nice:

*

*From the study of determinants and matrices to modern linear algebra
It is mostly about starting with the study of solutions of systems of linear equations and continues with the development of matrix notation up to the axiomatic definition of vector spaces.
Another line is analytic geometry, or vector geometry, combining algebra and geometry. See for example:

*

*Analytische Geometrie - Geschichte

Nicolas Bourbaki went a step further: he omitted geometric terms like point, line, etc. and thought with the treatment of linear algebra everything necessary was said.

Combined with calculus one arrives at vector calculus, for example, see:

*

*Vector calculus
One important extension going toward infinite many dimensions are:

*

*Hilbert spaces
An extension with linear inequalities leads to the economic important

*

*Linear programming

A: Textbooks about linear algebra are trying to introduce a subject which is the result of many years of deep understanding of many branches of mathematics, in the sense that linear algebra is the natural common bed for mathematical constructions that were before unrelated. A book could never cover such a huge area in an introductory chapter. A wild and bold analogy in another field could be asking: why did people invented grammar, while we already had an informal understanding of eachother?
I guess some could trace linear algebra back to the invention of infinitesimal calculus by Leibniz and Newton. When you derive a function at some point, you get the slope of the tangent of the curve at this point: this tangent line is an approximation of the function around the point. This approximation is useful because it is easy to compute. But what if I want to do the same thing for a multivariable function? Then I have partial derivatives, but they are only approximation "in one direction" taken separately. I you want an approximation of your multivariable function "in all directions at one", you need to find a way to put all of these partial approximation together. That is what formalize linear algebra, and more precisely linear maps between linear vector spaces.


text:
Q: python csv DictReader reset position to second line I have the python code below that reads two csv files and finds matching rows.  The csv files have a header row so I need to reset file2/reader2 to the second row on each iteration of reader1.
How do I reset the position of file2/reader2 to the first data row to search for a match?
import csv

# Read in the data from the two CSV files
with open('file1.csv') as file1, open('file2.csv') as file2:
  reader1 = csv.DictReader(file1)
  reader2 = csv.DictReader(file2)

  # Create an empty list to store the merged data
  merged_rows = []

  # Iterate over the rows in the first file
  for row1 in reader1:
    # Get the contact number from the current row
    contact_no = row1['contact_no']

    ### file2 seek to start of second line to find matches again

    # Iterate over the rows in the second file
    for row2 in reader2:
      # Check if the contact number in the current row
      # of the second file matches the contact number
      # from the current row of the first file
      if row2['contact_no'] == contact_no:
        # If the contact numbers match, merge the rows
        # by adding the data from the second row to the
        # first row
        row1.update(row2)

        # Add the merged row to the list of merged rows
        merged_rows.append(row1)

  # Write the merged rows to a new CSV file
  with open('merged_file.csv', 'w') as out_file:
    # Create a writer object and write the header row
    writer = csv.DictWriter(out_file, fieldnames=row1.keys())
    writer.writeheader()

    # Write each of the merged rows to the output file
    for row in merged_rows:
      writer.writerow(row)

A: Unless file2.csv is very large, I would load it in memory and keep it there.
  ...
  reader2 = csv.DictReader(file2)
  reader2_rows = list(reader2)
  ...
  for row1 in reader1:
    ...
    for row2 in reader2_rows:
      ...

Putting this into your code, it becomes:
import csv

# Read in the data from the two CSV files
with open('file1.csv') as file1, open('file2.csv') as file2:
  reader1 = csv.DictReader(file1)
  reader2 = csv.DictReader(file2)

  # load reader2 rows into memory since we reuse them multiple times
  reader2_rows = list(reader2)

  # Create an empty list to store the merged data
  merged_rows = []

  # Iterate over the rows in the first file
  for row1 in reader1:
    # Get the contact number from the current row
    contact_no = row1['contact_no']

    ### file2 seek to start of second line to find matches again

    # Iterate over the rows in the second file
    for row2 in reader2_rows:
      # Check if the contact number in the current row
      # of the second file matches the contact number
      # from the current row of the first file
      if row2['contact_no'] == contact_no:
        # If the contact numbers match, merge the rows
        # by adding the data from the second row to the
        # first row
        row1.update(row2)

        # Add the merged row to the list of merged rows
        merged_rows.append(row1)

  # Write the merged rows to a new CSV file
  with open('merged_file.csv', 'w') as out_file:
    # Create a writer object and write the header row
    writer = csv.DictWriter(out_file, fieldnames=row1.keys())
    writer.writeheader()

    # Write each of the merged rows to the output file
    for row in merged_rows:
      writer.writerow(row)


text:
Q: In Lua, how can you print the name of the current function, like the C99 __func__ identifier? Something like this:
function foo()
    print( __func__ )
   ...
end

How can it be done?

A: function __FILE__() return debug.getinfo(2, 'S').source end
function __LINE__() return debug.getinfo(2, 'l').currentline end
function __FUNC__() return debug.getinfo(2, 'n').name end

function printlinefilefunc()
    print("Line at "..__LINE__()..", FILE at "..__FILE__()..", in func: "..__FUNC__())
end

Output:

Line at 8, FILE at @./andydebug.lua, in func: printlinefilefunc

A: While I agree with Ephraim's answer, that code will not always report the same name as pointed out by Chris Becke. When the function is assigned to another variable, the "name" would be changed.
Here is another alternative. It just uses a string to identify the function. This method solves the changing name problem, but introduces a maintenance issue. The string would need to be kept in sync with the function name with future refactorization.
function foo()
  local __func__ = "foo"
  print( __func__ )
  --...
end

Alternatively, if the location of the function is more important than the name, the following may be better. It will give a name to the function that is based on the source and line number.
function getfunctionlocation()
  local w = debug.getinfo(2, "S")
  return w.short_src..":"..w.linedefined
end

function foo()
  print(getfunctionlocation()) --> foo.lua:6
  --...
end

If the __func__ still seems better, and standard Lua is not important, then the Lua parser can be modified as it is in this example for __FILE__ and __LINE__.

A: #!/usr/bin/lua

local function myFunc()
 print(debug.getinfo(1, "n").name);
end
myFunc()

A: Use the Debug Library. It provides a getinfo(func) function that returns a table with information about the function.

A: Functions don't necessarily have them. It's perfectly legal in Lua to create anonymous functions with no name- and call it, without assigning it one.
(function()
    print("in anonymous function!")
end)()

Is perfectly valid Lua. What name do you want to give that function?

A: You can't. In lua, functions are values. So they don't have names. You might as well ask "what the name of 2" is. Just because some variable was assigned the value '2' doesn't make that variable the name of 2. Likewise "someFunc" is a variable - potentially one of many - that holds a particular function.

As per @Orouborus in the comments:
function f() end is just syntactical sugar for f = function () end
Whatever you are doing, whatever the other posts are helping you do, you can print out the name of the thing on the left, "f", but not the name of the thing on the right.

A: You can try:
local dbFunc = debug.getinfo(1) and debug.getinfo(1).name or ""

Info
Info["currentline"] = 1376
Info["source"] = "@.\mymod.lua"
Info["short_src"] = ".\mymod.lua"
Info["nups"] = 13
Info["isvararg"] = false
Info["what"] = "Lua"
Info["lastlinedefined"] = 1570
Info["func"] = function: 000000000030B440
Info["istailcall"] = false
Info["linedefined"] = 1375
Info["namewhat"] = "field"
Info["name"] = "ExportDB" <<--- See here the function name
Info["nparams"] = 4

debug.getinfo(1) Returns this structure of the current execution state of the active function in the stack.
If n is larger than the number of active functions in the stack, debug.getinfo() returns nil.
That's why you have to check if it exists before taking *.name and return an empty string if the information is not available
A it is called inside the ExportDB() function, it return its name


text:
Q: Reset a string variable to print multitple user inputs in a loop (NASM Assembly) I'm using a 64 bits Linux system, and I'm trying to use NASM to build a program that asks the user for input, and then prints it. Afterwards, the user can choose to do the same again, or exit.
My issue is that the variable 'text', which is used to store the user's input, is not reset at the end of each execution, so something like this happens:

*

*User enters text the 1st time: Helloooooooooooooooooooooooooooooo

*Output: Helloooooooooooooooooooooooooooooo

*User enters text the 2nd time: Boom!

*Output: Boom!
oooooooooooooooooooooooooooo
Part of the "Helloooooo" from the first execution is showing up, and I don't know how to prevent that from happening.
I'd appreciate any help, as I'm just starting to learn about this.
Thanks
This is what I've done:
section .data
prompt db "Type your text here.", 0h

retry db "Wanna try again? If yes, enter y. If not, enter anything else to close the program", 0h

section .bss
text resb 255
choice resb 2

section .text
    global _start

_start:

    mov rax, 1      ;Just asking the user to enter input
    mov rdi, 1
    mov rsi, prompt
    mov rdx, 21
    syscall

    mov rax, 0      ;Getting input and saving it on var text
    mov rdi, 0
    mov rsi, text
    mov rdx, 255
    syscall

    mov rax, 1      ;Printing the user input
    mov rdi, 1
    mov rsi, text
    mov rdx, 255
    syscall

    mov rax, 1      ;Asking if user wants to try again
    mov rdi, 1
    mov rsi, retry
    mov rdx, 83
    syscall

    mov rax, 0      ;Getting input and saving it on var choice
    mov rdi, 0
    mov rsi, choice
    mov rdx, 2
    syscall

    mov r8b, [choice] ;If choice is different from y, go to end and close the program. Otherwhise, go back to start.
    cmp byte r8b, 'y'
    jne end
    jmp _start

    end:
    mov rax, 60
    mov rdi, 0
    syscall

A:     mov rax, 1      ;Printing the user input
    mov rdi, 1
    mov rsi, text
    mov rdx, 255
    syscall

You always write 255 characters, no matter how many were input.  If the user input fewer than 255, you'll write whatever else happens to be in your text buffer, possibly data left over from a previous iteration.
When you issue the read system call (i.e. syscall with rax=0), it will return in rax a value indicating the number of characters read (or 0 on end-of-file, or a negative number on error).  Only that many characters have been written into the buffer; the rest of it is unchanged.
It's not necessary to "reset" the remaining contents of the buffer, and even if you write zeros over it or something, it will only result in you outputting a bunch of unwanted zero bytes - which in fact you already do.  You may not see them on a terminal, but if you redirect your output to a file, they'll be there.
So you should pass the value returned from read , if it's positive, in rdx to write (syscall with rax=1) instead of always using 255.  Then you will only write what was read, and the remaining contents of the buffer are irrelevant as they will not be used.


text:
Q: RMAN decrypted backup of Oracle TDE encrypted table I have a Database with Transparent Data Encryption enabled across tablespaces. We have a storage appliance we're using RMAN to backup to which has native encryption, deduplication and compression enabled by default. Since the backup sets are currently encrypted, we lose out on the compression and dedup features of the appliance, costing us MUCH more in disk than expected.
Is it possible to create a non-encrypted backup a TDE-encrypted tablespace using RMAN?
I've been reading through the RMAN docs, Oracle support site, and as many other web articles I have been able to find but have yet to find anything helpful.
Thanks for any assistance or advice!

A: RMAN makes binary copies of the files, so you can't really not include the TDE, though you can do incremental backups with block change tracking to keep them as small as possible. See here: https://docs.oracle.com/en/database/oracle/oracle-database/19/bradv/rman-backup-concepts.html#GUID-16069217-F44A-45BF-BAE6-774B99155E3A
Also note that TDE provides a different level of protection than the device-level encryption and deduplication on your storage device. The device-level encryption only prevents someone from stealing the device, since files would be decrypted transparently as they are presented to the server OS. By comparison, TDE prevents someone from stealing and decrypting an individual file from the device through a server OS, using a conventional file transfer method like sftp.
If you have a reason - or more likely a requirement - to encrypt at the file level and not just at the device level, then disabling TDE on your backups - even if it could be done - would be a complete abandonment of your data protection policy. Best practice says that your backups should receive at least the same level of protection as your live data files, since backups are often moved off site or to non-production environments and considered easier to steal.


text:
Q: Print SQL query of ORM query builder in cakephp3 How to print ORM query
$query = $articles->find('all')->contain(['Comments']);

For example print =>
SELECT * FROM comments WHERE article_id IN (comments);

A: I prefer this:
public function __debugInfo()
    {
        return [
            'query' => $this->_query,
            'items' => $this->toArray(),
        ];
    }

// Print the query
debug($query->__debugInfo()['sql']);

// Prints this
SELECT * FROM comments WHERE article_id IN (comments);

A: Wrapping your ORM query result with the debug function will show the SQL and bound params:
debug($query);

You can also similarly look at the query results with the debug function.See CakePHP 3: retrieving data and result sets — Debugging Queries and ResultSets

A: what about $query->sql()?
$qb = $this->Person->find()->select(["id", "text" => "concat(Name,' ',Family)"])
            ->where(['id >' => 0])
            ->where($query ? ["OR" => $filters] : null)
            ->limit(10);
dd($qb->sql());

and result:
.../src/Controller/ClientController.php (line 86)
'SELECT Person.id AS `Person__id`, concat(Name,' ',Family) AS `text` FROM person Person WHERE (id > :c0 AND (Family like '%sam%' OR Name like '%sam%' OR Family like '%sam%' OR Name like '%sam%')) LIMIT 10'


text:
Q: Как выводить каждое N-ое значение в графике? Имеется файл CSV:
Отсчеты;Канал 0, В;
0;-0,273;
1;-0,039;
2;0,049;
3;0,264;
4;0,000;
5;-0,059;
6;-0,254;
7;0,039;
8;0,039;
9;0,234;
10;-0,020;

Список продолжается вплоть до нескольких тысяч. При построении графика возникает проблема, слишком много шумов, и всё похоже на кашу.

Вот моя функция:
def grafic():
    try:
        plt.style.use('ggplot')  # графики
        plt.rcParams['figure.figsize'] = (15, 5)  # размер картинок
        file_name = fd.askopenfilename()
        f = open(file_name)
        fixed_df = pd.read_csv(file_name, sep=';', decimal=",", encoding='cp1251')
        fixed_df["Канал 0, В"].plot(figsize=(15, 10))
        f.close()
        plt.show()
    except FileNotFoundError:
        mb.showinfo("Внимание", "Файл не загружен")

Не могу разобраться, как в этом случае использовать метод скользящей средней?

A: Как уже посоветовал уважаемый @CrazyElf, можно воспользоваться скользящим средним.
Пример:
df["Канал 0, В"].plot(figsize=(15, 10))
df["Канал 0, В"].rolling(50).mean().plot(figsize=(15, 10), linewidth=4)

Результат:


text:
Q: Record not insert in table, INNODB table is full in MySql Database I Created a table  with engine InnoDB enginge
OS is Ubuntu.
Table Structure :
#ID int(11),
userID int(11),
Tokens varchar(100),
created_date Datetime

Current table detail
Data Rows
42180773
Data Free
661651456
Data Length
2578464768
Index Length
3842785280
Auto Increments
72437133
I remove some old rows then able to insert new records.
What is the issue with this table?


text:
Q: Why my variable's value change when page refresh in service.ts? Here my Angular service.ts file code. That use to store the login status
 import { Injectable } from '@angular/core';
 import { BehaviorSubject } from 'rxjs';

    @Injectable({
      providedIn: 'root'
    })
    export class CurdService {

      private subject = new BehaviorSubject<any>(true);
      constructor() { }

      sendMessage(message: boolean) {
        this.subject.next(message);
    }

    getMessage() {
        return this.subject.asObservable();
    }

    }

Using the below code I change that's value. Why this 'subject' value change when I page refresh. How I store that value permanently.
 login(){
    this.curdService.sendMessage(true);
  }

 logout(){
    this.curdService.sendMessage(false);
  }

A: To permanently store and retrieve data even after a page refresh, use localStorage:
Any value you need to store permanently, for example, declare a variable:
var token = "message";

Set the item in the localStorage, note that you need a key (here it is id) to be able to retrieve it:
localStorage.setItem("id", token);

The below line will return the value message:
  const message =  localStorage.getItem("id");

A: That is because Angular Services maintains your data throughout the life of your application. When you refresh the page, the previous communication between services will be refreshed/reset and will not be saved. In every page reload, angular services maintain a new fresh instance of the application.
If you want to save or preserve your data, you can uselocalStorage, cookies, or sessionStorage and other similar.


text:
Q: Core Image face detection broken on 64 bit iOS? So, I have an app that uses the face detection feature of Core Image ( https://itunes.apple.com/us/app/ace-freakyface-cartoon-mask/id454513332?mt=8 ) and I just got the new iPhone 5s and the app no longer detects a face. I'm also receiving an error in the console while debugging:

/System/Library/PrivateFrameworks/FaceCore.framework/fcl-fc-3.dat: mach-o, but wrong architecture
  2013-09-25 20:17:22.861 faceMaker[474:a16b] Face detection finding face error: Error Domain=FCRFaceDetectorErrorDomain Code=2 "dlopen(/System/Library/PrivateFrameworks/FaceCore.framework/fcl-fc-3.dat, 2): no suitable image found.  Did find:

I've update my iPhone 4s(non-64 bit) with iOS 7 and the app works as it should. I think I need to update the valid architectures but when I do that I break the AdMob library. there may be a way around this but not that I'm aware of. Anyway I'm going to keep trying stuff but was wondering if anyone else had similar problems. I also downloaded what looked to be other apps in the app store using the face detector api and the same result, i.e. no joy on 64 bit.
Thanks,
Nick

A: I also had this issue with our face morphing app.  I wrote a stand alone testing program, that only does face recognition software. If I compiled it as a 64 bit app and ran it on the iPhone 5S with iOS 7, it worked. If I compiled it as a 32 bit app ran it on the iPhone 5S with iOS 7, it failed. I received similar log. It appears when in 32 bit mode, a private library named FaceCore is not available.  A 64 bit version of the library is available.  We need to have more people complain to Apple about this, since it sounds like a OS bug!

A: A solution just appeared in the latest xCode update. You can now build for arm64 and target 6.0 and above (compared to 7.0 and above on previous releases). If you do that, the problem is fixed.
On other notes, Apple has responded to my bug report and said that they will be fixing this issue in the next iOS update. Fingers crossed!

A: I wish I could thumbs up the last post.  I have libraries that are not updated for 64 bit and going into build setting and showing all gives the option to turn off the 64 bit build.

A: For me, I changed architectures in build setting to "including 64 bit, arm 64" and it work fine. But somehow my google admob is not working as it is not 64 bit calculation.


text:
Q: Creating string permutations Why doesn't this produce the correct number of string permutations? For
perm("ABC", 3)

it should print 27 different permutations.
private static List<string> permutated = new List<string>(30000);

public static List<string> perm(string s, int k) { return comb(s, "", k); }

private static List<string> perm(string s, string prefix, int k)
{
    if (k == 0)
    {
        permutated.Add(prefix);
    }
    else
    {
        for (int i = 0; i < s.Length; i++)
        {
            perm( s.Substring( i + 1 ), prefix + s[i], k - 1 );
        }
    }
    return permutated;
}

A: You are already calculating combinations in your program. For comb("ABC", 3) there should be one result.
If you want permutations instead (six results), replace s.Substring( i + 1 ) in the recursive function call with s.Substring(0, i) + s.Substring(i+1).
If you want 27 results, simply pass s instead of s.Substring( i + 1 ).


text:
Q: Detect screen size with jQuery and apply a CSS style I searched and found many examples on web, and even here in stackoverflow, but none of them is 100% explained. For those who wants to place a answer with CSS media screen, please don't do that I know about it. But this question is more for IE7+. since it doesn't support "CSS media screen".
This is the example i found:
$(document).ready(function() {

if (screen.width>=800) {
    $("link[rel=stylesheet]:not(:first)").attr({href : "style1.css"});
    } else {
    $("link[rel=stylesheet]:not(:first)").attr({href : "style.css"});
    }
});

I am new to jquery, so how to change this script in case if I have 4 different styles for 4 different screen resolutions.
So I would liek to have something like this:

*

*if screen > 1 && screen < 600

*if screen > 601 && screen < 1280

*if screen > 1281 && screen < 1600

*if screen > 1 1601

Please help me!

A: You don't need jQuery for this, using CSS3 media queries instead:
@media only screen and (max-width : 600px) {
   /* Styles for 1*/
}

@media only screen and (min-width : 601px) and (max-width : 1280px) {
   /* Styles for 2 */
}

@media only screen and (min-width : 1281px) and (max-width : 1600px) {
   /* Styles for 3 */
}

@media only screen and (min-width : 1601px) {
   /* Styles for 4 */
}

Ok, as @RaduChelariu mention, to support older browser like IE7 you can use a custom plugin to make CSS3 media queries compatible with.

A: Actually, media queries are the answer. Just use this shiv to add media query support to IE7 and 8 and you're good to go. No need for messy javascript.


text:
Q: How to add a Custom Fields in Woocommerce 3.1 i've tried many methods to make a custom fields
in woocommerce 3.1 but this code didnt work for me.
can any one help me to figure out how to add a custom fields like this on the link below
http://www.remicorson.com/mastering-woocommerce-products-custom-fields/
Best regards

A: Add Custom fields in Product General tab used woocommerce_product_options_general_product_data  action hook
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {

  global $woocommerce, $post;

    woocommerce_wp_text_input(
        array(
            'id'          => '_text_field',
            'label'       => __( 'My Text Field', 'woocommerce' ),
            'placeholder' => 'http://',
            'desc_tip'    => 'true',
            'description' => __( 'Enter the custom value here.', 'woocommerce' )
        )
    );

}

Now For Saving this fields to data based using woocommerce_process_product_meta
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){
    $woocommerce_text_field = $_POST['_text_field'];
    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_text_field', esc_attr( $woocommerce_text_field ) );

}

i hop now you understand. it working with WooCommerce 3.1


text:
Q: Handle Time Zone difference with Java and Angular Development is in one place and deployment is in another location for a web -application.
During development, I used my own location timezone to fetch and persist the date values in the DB(Oracle).
But after deployment, to another location time zone are totally different and date seems to cause a major issue in the course of testing.
This is a simple application wherein I use Java for Backend and Angular 5 for front-end. Data persist is done with Oracle DB.
I am not sure how to handle this time zone difference. Is there any specific way to handle this difference? Any inputs are most welcome.
[EDIT]: So, the requirement is simple - wherever the user logs in the application, he must be able to view the Date and time as per his timezone. Even if the user Creates/Modifies an item, he must be able to view the time as per his timezone.
For Ex: If I am posting a post/status, then the time at my end must show the timezone for my location. Similarly, If I see the same post/status in another geography, then I must see the time respective to that time zone.

A: Anything with timezones is not fun at all. My suggestion would be to make sure you're converting your dates to UTC on the server and persisting them that way, then converting them back on the client.
I don't know how you're passing dates to the server, but something like
Determine TimeZone from a JSON String? could be useful.
For a better discussion, see:
Should the Server or the Client handle timezone when sending/receiving dates?
How to properly work with Timezone?
Good luck!
Edit:
As noted by Jon Skeet below, this is not necessarily a good idea. A conversion to UTC without a timezone is "lossy". If timezones change (and they do from time to time), then your UTC timestamp no longer represents what it was originally intended to.
Take a look at this page and make some decisions about your datatypes (TIMESTAMP WITH TIME ZONE will preserve the timezone entered by the user, if this is required).
https://docs.oracle.com/cd/B19306_01/server.102/b14225/ch4datetime.htm
Just about everything you do with dates/times is going to be full of caveats, and this question doesn't give a lot of information about what the application's requirements are for storing/displaying date and time information.

A: I'm guessing that you are using Java Date objects correct?  If you are using Java 8 you should consider these two:
OffsetDateTime
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
OffsetTime
A time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 10:15:30+01:00.
https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
If you are saving it to Oracle and all you need is a DATE then I would suggest you save it as a String and format it using "YYYY-MM-DD".
By default the Java JVM ALWAYS adds the local JVM TZ (TimeZone) values to any date object.
So let's look at a business case.  If you have customers in 4 different regions of the USA and you need to report on date/time events in their LOCAL TIME then you MUST save to the DB in GMT time.  By default the local TZ will adjust this accordingly.  Oracle's built in Date/Time objects do this by default as does EVERY major Operating System.  So create a DIR, notice the current time and then go into your regional settings for your OS and change your timezone.  The DIR creation date will automatically be translated.
At it's simplest form this is a perfect case of Model-View-Controller.  Where the TZ change is the Controller.  The Model is the GMT value and the View is translated to the current user's TimeZone.
I hope this helps you.  PLEASE use GMT and don't over think it.  Saving to a DB NOT using GMT is asking for trouble in my humble opinion.
Cheers


text:
Q: C# Regex replace url I have a bunch of links in a document which has to be replaced by a javascript call. All the links looks the same:
Document naam 1
Document naam 2
Document naam 3

Now I want all this links to be replaced to:
Document naam 1
Document naam 2
Document naam 3

So the Id=3D in the url is the first parameter in the function and the doc parameter is the second parameter in the function call.
I want to do this using Regex because I think this is the quickest way. But the problem is my regex knowledge is too limited

A: Regex regex = new Regex(@"http://domain/ViewDocument.aspx\?id=3D(\d+)&doc=(\w+)");
Match match = regex.Match(link.Href);
if (match.Success)
{
    link.Href = string.Format("javascript:loadDocument('{0}','{1}')", match.Groups[1].Value, match.Groups[2].Value);
}

A: You could use Html Agility Pack to help parse the HTML. Here's how you could do it:
//Regex regex = new Regex(@"^http://domain/ViewDocument\.aspx\?id=3D(\d+)&doc=(\w+)$");
Regex regex = new Regex(@"^http://domain/ViewDocument\.aspx\?id=3D(\d+)&doc=(\w+)$");
HtmlDocument doc = new HtmlDocument();
doc.Load("input.html");
var nodes = doc.DocumentNode
               .Descendants("a")
               .Where(node => regex.IsMatch(node.Attributes["href"].Value));

foreach (HtmlNode node in nodes)
{
    var href = node.Attributes["href"];
    href.Value = regex.Replace(href.Value, "javascript:loadDocument('$1','$2')");
    node.Attributes["target"].Remove();
}

doc.Save(Console.Out);

Result:

Document naam 1
Document naam 2
Document naam 3

A: Polygenelubricants has pointed me in the very right way, but has removed his answer :(
He gave me this link. Thanks to him I found my solution:
string replaced = "";

string regex = "";
Regex regEx = new Regex(regex);

replaced = regEx.Replace(mhtFile, "");

Response.Write(replaced);

For those who are interested, this links are inside a .mht file. That's why the 3D are placed after the = sign. The variable mhtFile contains the whole mht file in plain mht text.


text:
Q: Typescript properties array of class I'm trying to loop on each properties of class from a new object, without any property set. Object.keys() return an empty array. Maybe because none of properties are set. Do you know a way to loop on properties of a class or a fresh new object of this class ?
export class Perimeter {
  Id: string;
  Name: string;
  Description: string;
  Typapp: string;
}

 var tmp = new Perimeter();
 console.log('Object keys tmp', Object.keys(tmp)); //Object keys tmp []

Result that I expect is ['Id', 'Name', 'Description', 'Typapp']
Thank you in advance

A: The problem is you're not initializing those properties, so they only exist on the type, not at runtime. TypeScript will be warning you about that, saying that they've never been definitely assigned. For example:

Property 'Id' has no initializer and is not definitely assigned in the constructor. (2564)

Example
You need to initialize the properties for them to exist on the instance you're passing to Object.keys. You might do that in a couple of different ways. One of them is to use the public modifier on constructor parameters, which both creates a public property and automatically assigns the parameter's value to that property:
/*export*/ class Perimeter {
    constructor(
        public Id = "",
        public Name = "",
        public Description = "",
        public Typapp = ""
    ) {
    }
}

const tmp = new Perimeter();
console.log('Object keys tmp', Object.keys(tmp)); //Object keys tmp []

Live Example
(I've included default values there because you've shown a call to the constructor that doesn't provide any arguments.)
But you can also write it explicitly:
/*export*/ class Perimeter {
    Id: string;
    Name: string;
    Description: string;
    Typapp: string;
    constructor(id = "", name = "", description = "", typapp = "") {
        this.Id = id;
        this.Name = name;
        this.Description = description;
        this.Typapp = typapp;
    }
}

const tmp = new Perimeter();
console.log('Object keys tmp', Object.keys(tmp)); //Object keys tmp []

Live Example
For a class that has both properties with fixed initial values and ones that are assigned in the constructor, I prefer to both declare them and then assign the ones that need it in the constructor, but for ones where all of the properties are constructor parameters, it makes for a handy shorthand. Either way, it's a matter of style.


text:
Q: How to export array data through node addon I'm using node 0.12.x, I want to return some array data from node addon written by c++
Isolate* isolate = args.GetIsolate();
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
obj->value_ += 1;
args.GetReturnValue().Set(Number::New(isolate, obj->value_));

This is a sample for returning Number data.

A: using namespace v8;

Create an array:
Local<Array> myArray = Array::New(isolate);

You can then create objects with properties (or just integers) and push them into the array:
 for (int i = 0; i < n; i++) {
    Local<Object> obj = Object::New(isolate);
    obj->Set(String::NewFromUtf8(isolate, "tag1"), "test");
    myArray->Set(i, obj);
 }

 args.GetReturnValue().Set(myArray);

If you're writing native code for node.js I highly recommend using nan:
https://github.com/nodejs/nan


text:
Q: How to access data from mongoose model with three schemas Hello I am needing assistance with accessing certain data from my mongoose schema in my route to render it on the UI. I have 3 json files with objects like so,
{
  "name": "1_test_spec.rb",
  "folder": "working_1",
  "test": "Test 1 TC 134389 Add to Autopay with Visa"
}

I imported the json files to my local mongoDB with each file having its own collection. The name format is test_working1/2/3. I than created the following schema.
const mongoose = require("mongoose");

//SCHEMA SETUP
const test_working1Schema = new mongoose.Schema({
  name: String,
  folder: String,
  test: String
});

const test_working2Schema = new mongoose.Schema({
  name: String,
  folder: String,
  test: String
});

const test_working3Schema = new mongoose.Schema({
  name: String,
  folder: String,
  test: String
});

module.exports = mongoose.model("Test_working1", test_working1Schema);
module.exports = mongoose.model("Test_working2", test_working2Schema);
module.exports = mongoose.model("Test_working3", test_working2Schema);

Than at the top of my .js file I require the schema Test = require("../models/test"),I have my routes set up like so,
router.get("/", (req, res) => {
  Test.find({}, (err, allTests) => {
    if(err){
        console.log(err);
    }  else {
      res.render("automation/index", { test: allTests, username: req.user });
    }
  });
});

router.get("/:id/test", (req, res) =>{
  Test.findById(req.params.id, (err, foundTest) => {
    let folder = foundTest.folder;
    let name = foundTest.name;
    let test = foundTest.test;

      if(err){
          console.log(err);
      } else {
        ChildProcess.exec(`cd ${path} & cd ../../ & cd ./automation/WSS_Automation & rspec ./spec/tests/` + folder + "/" + name, (error, stdout, stderr) => {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        console.log('error: ' + error);
        });
        req.flash("added", test + " " + "is running!" );
        res.redirect("/QAApplicationHub/Automation/");
        // res.send("WSS " + test + ' ' + "is running!");
      }
  });
});

The above route handles comparing the name of the folder that each test is in and which test the user selects to run by comparing the ID. I than call to the data from the UI using EJS,
<select class="form-control col-md-4 slct001">
        <option value="">Choose one...</option>
        <% test.forEach(function(test){ %>
        <option value="/QAApplicationHub/Automation/<%= test._id %>/test"><%= test.test %></option>
        <% }); %>
      </select>

The issue here is that it is only displaying the test files from test_working3. The goal is to have three separate select drop downs. Each select element will contain the test from each folder. The user will select the test they want to run and select a button to run the automation test script.
Im sure there is a more efficient way of doing this. Im only familiar with working with one schema and route pair at a time so this is a little bit more than I have exposure too. Any assistance is appreciated. Thanks.
Update:
I updated my schema to this,
const mongoose = require("mongoose");

//SCHEMA SETUP
const test_working1Schema = new mongoose.Schema({
  name: String,
  folder: String,
  test: String
});

const test_working2Schema = new mongoose.Schema({
  name: String,
  folder: String,
  test: String
});

const test_working3Schema = new mongoose.Schema({
  name: String,
  folder: String,
  test: String
});

const Test1 = mongoose.model("Test_working1", test_working1Schema);
const Test2 = mongoose.model("Test_working2", test_working2Schema);
const Test3 = mongoose.model("Test_working3", test_working3Schema);

module.exports = { Test1, Test2, Test3 }

I than included it on my .js file like this,
const Test1          = require("../models/test").Test1,
      Test2          = require("../models/test").Test2,
      Test3          = require("../models/test").Test3;

And my route looks like this,
router.get("/", (req, res) => {
  Test1.find({}, (err, allTests) => {
    if(err){
        console.log(err);
    }
      else {
      res.render("automation/index", { test1: allTests, username: req.user
     });
    }
  });
});

Is there a way to pass in each model from the one route similar to how I use Test1.find({}.....or that should be handled inside of the schema instead?
Alright so to make things easier I hope I changed the structure of the json file and schema to the correct format. So now my Json file is like this
{"working1": [{

  "name": "1_test_spec.rb",
  "folder": "working_1",
  "test": "Test 1 TC 134389 Add to Autopay with Visa"
},
  {
  "name": "2_test_spec.rb",
  "folder": "working_1",
  "test": "Test 2 TC 134389 Add to Autopay with Master Card"
  }
  ]}

  {"working2": [{

    "name": "11_test_spec.rb",
    "folder": "working_2",
    "test": "Test 11 TC 149627 Create a Confirmed Reservation"
  },
    {
      "name": "12_test_spec.rb",
      "folder": "working_2",
      "test": "Test 12 TC 149630 Create Online Reservation"
    }
    ]}

    {"working3": [{
        "name": "21_test_spec.rb",
        "folder": "working_3",
        "test": "Test 21 TC 161117 Move Out with visa Card Refund"
      },
      {
        "name": "22_test_spec.rb",
        "folder": "working_3",
        "test": "Test 22 TC 161117 Move Out with Cash Refund"
      }
      ]}

And I than updated the schema to this,
const mongoose = require("mongoose");

//SCHEMA SETUP
const testSchema = new mongoose.Schema({
  working1: [{ name: String, folder: String, test: String}],
  working2: [{ name: String, folder: String, test: String}],
  working3: [{ name: String, folder: String, test: String}]

});

module.exports = mongoose.model("Test", testSchema);

That should make it easier to get the data I want into each select element drop down?

A: It happens because in your file with the schema, only the last line is effective. i.e,
module.exports = mongoose.model("Test_working3", test_working2Schema);

overwrites the earlier exports.
One file can only export one model in the way you are doing, and is the standard way of doing this.
If you really want to export all three models from the same file, you can do something like:
module.exports = {
    test1 : mongoose.model("Test_working1", test_working1Schema),
    test2 : mongoose.model("Test_working2", test_working2Schema);
    test3 : mongoose.model("Test_working3", test_working2Schema);
}

And require all 3 schemas, using
var Test1 = require("../models/test").test1
var Test2 = require("../models/test").test2
var Test3 = require("../models/test").test3

and then, render the data from each 3 of these separately. Something like this:
var async = require('async')
router.get("/", (req, res) => {
    async.parallel({
        test1: function (callback1) {
            Test1.findOne({}, callback1)
        },
        test2: function (callback2) {
            Test2.findOne({}, callback2)
        },
        test3: function (callback3) {
            Test3.findOne({}, callback3)
        },

    }, function (err, results) {
        if(err){
            console.log(err);
        } else {
            var tests = test1.concat(test2).concat(test3);
            res.render("automation/index", { test1: tests, username: req.user });
        }
    })
});

A: Doing this:
module.exports = mongoose.model("Test_working1", test_working1Schema);
module.exports = mongoose.model("Test_working2", test_working2Schema);
module.exports = mongoose.model("Test_working3", test_working2Schema);

I think you are exporting only the last one, because you are overwriting exports with different values, and only last one "survives". Probably that makes you only get results from the 3rd schema.
Whay I suggest you to do is to export the methods you need, for example a find method and a findById method, and implement each method into the db file searching in the 3 models for results and returning all of them. Something like this:
const model1 = mongoose.model("Test_working1", test_working1Schema);
const model2 = mongoose.model("Test_working2", test_working2Schema);
const model3 = mongoose.model("Test_working3", test_working2Schema);

exports.find = async query => {
    let result1 = await model1.find(query).toArray();
    let result2 = await model2.find(query).toArray();
    let result3 = await model3.find(query).toArray();
    return [...result1, ...result2, ...result3];
}

exports.findById = async id => {
    // something similar
}


text:
Q: Potential energy on a spherical capacitor I have been having some trouble understanding the storage of energy
inside a spherical capacitor composed of two concentric spherical
shells where the inside shell has radius $a$ and charge $2q$, while
the outside shell has radius $b$ and charge $q$. We know that
$$\Delta V=-\int\vec{E}.d\vec{r}$$
and that $U=q\Delta V$, hence we can define
$$U=-\intop_{0}^{2q}\intop_{b}^{a}\vec{E}.d\vec{r}.dq$$
Or at least I hope so. But how should we think about it? The potential
difference between $a$ and $b$ is defined as the work per unit charge
that an external agent has to exert in order to bring a chunk of charge,
say $dq$ from $b$ to $a$. And what we are doing here I only see
it as summing all of the work needed to transport the $dq$'s individually
but not counting with the interaction between them.
What I'm asking
is the intuition to link the previous expression and:
$$\frac{1}{4\pi\epsilon_{0}}\sum_{i=1}\sum_{j>i}\frac{q_{i}q_{j}}{r_{ij}}$$
Plus if someone could give me a hint on where this comes from I would
be very appreciated
$$U=\frac{1}{2}\epsilon_{0}\int E^{2}dV$$


text:
Q: To Add huge set of secs.milllisec to given time in hh:mm:ss.millisecs Start time is  10:48:00.000
(10 - hr
48 - min
00 - secs
000 - milli secs).
Requirement to add huge set of secs.milli secs to the start time
Eg: 01.408
(01 - secs
408 - milli secs).
(Start time) 10:48:00.000 + 01.408 (secs.milli secs) = 10:48:01.408.
To Take care:
1. 60 secs  is  1 min, so minutes needs to get incremented accordingly,
Eg:(Start time) 10:48:00.000 + 61.523 (secs.milli secs) = 10:49:01.523
2. 60 minutes is  1 hr, so hours needs to get incremented accordingly,
Eg:(Start time) 10:48:00.000 + 3600.478 (secs.milli secs) = 11:48:00.478
Need help to derive the formula  / steps  to achieve in Microsoft excel.

A: If C1 contains a time like:
02:57:46.667

and D1 contains an integer like 123, representing 123 milliseconds.  Then in E1 enter:
=C1+D1/(24*60*60*1000)

to sum them:

A: Added h:mm:ss.000 + secs.millisecs(set as number in Format cells) to solve


text:
Q: How can I without the 'allow filtering' to have the conditional query in CQL? I am the new leaner in CQL.
I have the (restaurants) table.
By implemented 'desc restaurants', it shows the information in
restaurants table information
How can I run the following query without using 'allow filtering',
select name from restaurants where borough = 'brooklyn';
What are the necessary steps in order to be able to run the query without 'allow filtering'?
Thanks so much.

A: With Cassandra (CQL) you need to take a query-based modeling approach.  This means that you'll need a table specifically-designed to serve queries by borough.
A good question to start with, is why (in your current table design) is id your sole primary key?  Do you have to support a query by id?  If not, then you shouldn't need that table.  However, as borough is not unique, it makes sense to cluster an additional column(s) into your primary key definition.
I'd go with something like this:
CREATE TABLE stackoverflow.restaurants_by_borough (
    borough text,
    name text,
    id int,
    buildingnum text,
    cuisinetype text,
    phone text,
    street text,
    zipcode int,
    PRIMARY KEY (borough, name, id)
) WITH CLUSTERING ORDER BY (name ASC, id ASC);

Now this query will work:
select name from restaurants_by_borough
where borough = 'brooklyn';

It will return data for each borough, sorted by name.  Also, if any two restaurants have the same name (there's probably more than one McDonalds in Brooklyn) id is added to the end of the key to ensure uniqueness.


text:
Q: Cannot convert string to uint in c# i am pretty new to c# and for some reason my number wont convert for the life of me. My code is:
foreach(var descriptionid in test.items)
{
    ulong description = Convert.ToUInt32(descriptionid.Value.descriptionid);
    Console.WriteLine(description);
}

Any help is really appreciated!
Edit: This is the error message: http://gyazo.com/ed87941f4c8226ad6ebfd60879a5f173

A: Fisrt of all you need to get rid of the "_0" that exist at the end of the number, like that:
string number =  descriptionid.Value.descriptionid.ToString();
string[] nums = number.Split ('_');

And than to write the following code:
 ulong description = Convert.ToUInt64(nums[0]);

A: I don't know what's your problem and error (whats descriptionid.Value.descriptionid ?????), but you can change your code like this:
foreach(var descriptionid in test.items)
{
    //var description = Convert.ToUInt64(descriptionid.Value.descriptionid);
    var description = Convert.ToUInt64(descriptionid.Value.descriptionid.Split(new char[]{'_'})[0]);

    Console.WriteLine(description);
}


text:
Q: Odoo timesheet that overlap I'm using odoo 10... Current timesheet (hr_timesheet_sheet) structure is like that it can not overlap, because there is almost zero connection between analytic line and hr_timesheet_sheet except dates...
I have tried following method:
I have created a new field in hr_timesheet_sheet named 'editing' and whole idea was to set it to the 1 when user edited the timesheet (there was a 3rd party button to start custom 'edit mode') and in analytic line i have checked where user_id == uid and editing = 1 -> get id from hr_timesheet_sheet and paste in sheet_id, once user saved the timesheet it would update to 0 again...
But following practice has failed, because after page reload, it would refused to set 'editing' to 1 while i was clicking button.
My code looks like this:
def xtr(self):

        self.env.cr.execute(""" UPDATE hr_timesheet_sheet_sheet SET editing = %s WHERE id = %s""" %(1,self.id))

this is a button code where user starts 'edit_mode'
def _compute_sheet(self):

        """Links the timesheet line to the corresponding sheet

        """

        for ts_line in self:

            if not ts_line.project_id:

                continue

            sheets = self.env['hr_timesheet_sheet.sheet'].search(

                [('editing', '=', 1),

                 ('employee_id.user_id.id', '=', ts_line.user_id.id),

                 ('state', 'in', ['draft', 'new'])])

            if sheets:

                # [0] because only one sheet possible for an employee between 2 dates

                ts_line.sheet_id_computed = sheets[0]

                ts_line.sheet_id = sheets[0]

        self.env.cr.execute(""" UPDATE hr_timesheet_sheet_sheet SET editing = %s WHERE user_id = %s AND editing = %s""" %(0,self._context.get('uid'),1))

this is the code for sheet_id calculation...
p.s when user created a new timesheet after page reload (that would overlap) old sheet_ids which was belonged to previous sheet erased.
Simply, question is how to make 2 timesheet overlap... or how to fix m


text:
Q: Play a sound when mutt has new mail? I'm using mutt for my mail, usually put on the 2nd monitor with some other windows. Because I'm not monitoring that monitor I often miss the new mails.
I want mutt to play a sound (or use Growl) to notify me on new mails. Anyone know about a hook or a command or maybe a procmail filter for that?

A: procmail is an appropriate tool for playing a sound when new mail arrives.
I used to use this procmail recipe ...
:0c
| /usr/local/bin/wavp full_path_name_to_wav_file >/dev/null

Choose an appropriate command line player for the sound file that you wish to play.

A: You'd have to modify or patch mutt to have this functionality as it's not built in. There are other great mail notifiers available though such as biff, which will do this for you, if you don't mind using a separate program.


text:
Q: How to convert line to a list I used the following code to get the difference between each element in the list En. But answer comes as a line
En = [1,2,3,4,5]
for x in En:
    for y in En:
        if x !=y and x > y:
            z = x-y
            print(z)

The answer I got is in a line (Vertical)
I want the answer as a list: [1,2,1,3,2,1,4,3,2,1]
What should I change?
And can I get the list of items in ascending order?

A: You need to add values of z in a seperate list using .append() method and then print that list.
En = [1, 2, 3, 4, 5]

values_of_z = []

for x in En:
    for y in En:
        if x != y and x > y:
            z = x - y
            values_of_z.append(z)

print(values_of_z)

Output:
[1, 2, 1, 3, 2, 1, 4, 3, 2, 1]

You can sort values_of_z by using sorted() function.
print(sorted(values_of_z))

Output:
[1, 1, 1, 1, 2, 2, 2, 3, 3, 4]


text:
Q: TextBox not resetting focus when reopening the dropdown in a ComboBox I have a customized ComboBox to handle the text input and filter the itemsource. The problem I'm having is when I open the ComboBox the textBox is focused and let me write in it, then if I close and open it again, the TextBox is not focused and I cant write anything inside. I've discovered that the first time the comboBox is opening it is setting the focus on the TextBox but when I close it the TextBox keeps its IsFocused property true so when reopening the problem happens. It's just when opening and reopening clicking the comboBox because if I click outside the ComboBox to close it and then open it again everything works nice.
Here is the customized style I wrote and the ComboBox I'm using.
<Style x:Key="FilteringComboBox" TargetType="ComboBox">
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible" />
    <Setter Property="ScrollViewer.CanContentScroll" Value="true" />
    <Setter Property="IsEditable" Value="True"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="FontFamily" Value="Coves"/>
    <Setter Property="FontWeight" Value="Normal"/>
    <Setter Property="FontSize" Value="12"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ComboBox">
                <Border x:Name="TopBorder"
                        CornerRadius="8"
                        BorderBrush="Grey"
                        BorderThickness="1"
                        Padding="10,0,1,0">
                    <Border.Background>
                        <LinearGradientBrush EndPoint="0.504,1.5" StartPoint="0.504,0.03">
                            <GradientStop Color="White" Offset="0"/>
                            <GradientStop Color="#e3e3e5" Offset="0.65"/>
                        </LinearGradientBrush>
                    </Border.Background>
                    <Grid>
                        <ToggleButton
                        Name="ToggleButton"
                        Template="{DynamicResource FilteringComboBoxToggleButton}"
                        Grid.Column="2"
                        Focusable="false"
                        IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
                        ClickMode="Press">
                        </ToggleButton>

                        <TextBlock Name="ContentSite" IsHitTestVisible="False"
                                        Text="{Binding Source={StaticResource Proxy}, Path=Data.Name, UpdateSourceTrigger=PropertyChanged}"
                                        Visibility="Visible" Foreground="#37465c"
                                        Padding="3,3,23,3" VerticalAlignment="Center"
                                        HorizontalAlignment="Left" />

                        <TextBox x:Name="PART_EditableTextBox" MaxWidth="215" MinWidth="100"
                                Text="{Binding Source={StaticResource Proxy}, Path=Data.FilterText, UpdateSourceTrigger=PropertyChanged}"
                                Foreground="#37465c"
                                HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3,3,23,3" Focusable="True" Background="Transparent"
                                Visibility="Collapsed"/>

                        <Popup x:Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True"
                                Focusable="False" PopupAnimation="Fade">
                            <StackPanel Orientation="Vertical" Width="215">
                                <Grid Name="DropDown" SnapsToDevicePixels="True"
                                    MaxHeight="{TemplateBinding MaxDropDownHeight}">
                                    <Border x:Name="DropDownBorder" BorderThickness="1"
                                            BorderBrush="#888">
                                        <Border.Background>
                                            <LinearGradientBrush EndPoint="0.504,1.5" StartPoint="0.504,0.03">
                                                <GradientStop Color="White" Offset="0"/>
                                                <GradientStop Color="#e3e3e5" Offset="0.65"/>
                                            </LinearGradientBrush>
                                        </Border.Background>
                                        <ScrollViewer Margin="0" SnapsToDevicePixels="True">
                                            <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained"/>
                                        </ScrollViewer>
                                    </Border>
                                </Grid>
                            </StackPanel>
                        </Popup>
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Cursor" Value="Hand"/>
                    </Trigger>
                    <Trigger Property="IsKeyboardFocusWithin" Value="True">
                        <Setter Property="IsDropDownOpen" Value="True"/>
                        <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" />
                        <Setter TargetName="ContentSite" Property="Visibility" Value="Collapsed" />
                        <Setter Property="IsEditable" Value="True"/>
                    </Trigger>
                    <Trigger Property="IsMouseCaptured" Value="False">
                        <Setter Property="IsDropDownOpen" Value="False"/>
                        <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Collapsed" />
                        <Setter TargetName="ContentSite" Property="Visibility" Value="Visible" />
                        <Setter Property="Text" Value=""/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I tried adding this event handler to remove the focus but it isn't working
private static void QuantityBox_IsMouseCapturedWithin(object sender, DependencyPropertyChangedEventArgs e)
{
    var qBox = sender as ComboBox;

    if (qBox.IsDropDownOpen == false)
    {
        Keyboard.ClearFocus();
        flag = true;
    }
}

A: Hope that this helps someone, the erratic behaviour was happening because I was using these triggers:
<Trigger Property="IsKeyboardFocusWithin" Value="True">
    <Setter Property="IsDropDownOpen" Value="True"/>
    <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" />
    <Setter TargetName="ContentSite" Property="Visibility" Value="Collapsed" />
    <Setter Property="IsEditable" Value="True"/>
</Trigger>
<Trigger Property="IsMouseCaptured" Value="False">
    <Setter Property="IsDropDownOpen" Value="False"/>
    <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Collapsed" />
    <Setter TargetName="ContentSite" Property="Visibility" Value="Visible" />
    <Setter Property="Text" Value=""/>
</Trigger>

The triggers were ment to handle the visibility toggle between the TexBlock and the TextBox (showing the TextBlock when the ComboBox was inactive and the TextBox when it is focused so the user can type and filter).
So I removed the triggers and handled that behaviour in a dependency property:
public static readonly DependencyProperty MouseCapturedProperty = DependencyProperty.RegisterAttached("MouseCaptured",
        typeof(bool), typeof(QuantitiesBoxBehaviours),
        new UIPropertyMetadata(false, MouseCapturedPropertyChangedCallback));

public static bool GetMouseCaptured(UIElement element)
{
    return (bool)element.GetValue(MouseCapturedProperty);
}

public static void SetMouseCaptured(UIElement element, bool command)
{
    element.SetValue(MouseCapturedProperty, command);
}

private static void MouseCapturedPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var qBox = d as ComboBox;
    bool value = GetMouseCaptured(qBox);
    if (qBox != null && value)
    {
        qBox.IsMouseCaptureWithinChanged += QBox_IsMouseCaptureWithinChanged;
        qBox.DropDownOpened += QBox_DropDownOpened;
    }
}

private static void QBox_DropDownOpened(object sender, EventArgs e)
{
    var qBox = sender as ComboBox;
    var template = qBox.Template;
    var txtBox = template.FindName("PART_EditableTextBox", qBox) as TextBox;
    var txtBlock = template.FindName("ContentSite", qBox) as TextBlock;
    txtBlock.Visibility = Visibility.Collapsed;
    txtBox.Visibility = Visibility.Visible;
}

private static void QBox_IsMouseCaptureWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    var qBox = sender as ComboBox;
    var template = qBox.Template;
    var txtBox = template.FindName("PART_EditableTextBox", qBox) as TextBox;
    var txtBlock = template.FindName("ContentSite", qBox) as TextBlock;

    if (qBox.IsDropDownOpen == false)
    {
        Keyboard.ClearFocus();
        txtBox.Visibility = Visibility.Collapsed;
        txtBlock.Visibility = Visibility.Visible;
        qBox.ItemsSource = _presentationQuantities;
        flag = true;
    }
}

That solved the problem and now it's working great, that property was set to the ComboBox.


text:
Q: Renaming Rows in gtsummary, tbl_regression/tbl_stack I am using gtsummary and have stacked tables for the outputs of 11 different models on top of one another using the tbl_regression and tbl_stack functions. I am looking to see how the odds ratios of one consistent independent variable change across different dependent variables of interest. When I print out the tbl_stack output, it gives me 11 repeated rows of the independent variable name of interest, instead of the name of the unique dependent variables I am interested in. Does anyone know how to rename rows in tbl_stack (either manually or automatically) to put the dependent variable names in the rows?
Thank you.

A: You can use the tbl_regression(label=) argument to change the labels for the repeating variable to match the outcome for each model before you stack them.
There is, however, a shortcut using tbl_uvregerssion().
library(gtsummary)
packageVersion("gtsummary")
#> '1.3.6'

trial %>%
  select(response, death, age) %>%
  tbl_uvregression(
    x = age,
    method = glm,
    method.args = list(family = binomial),
    exponentiate = TRUE
  ) %>%
  modify_header(label ~ "**Outcome**")


text:
Q: Injecting custom batches of a Tank I have my own batch objects flowing into a tank. Now, based on some logic, I would like to create some batches at the output different than the input ones. For example, assume my tank is empty, and say I have batch A (volume 5000.0) flowing in the tank, followed by batch B (volume 6000.0). Then, when 5000.0 of B is landed in the tank, I would like to create a batch C with volume 10000.0 and let it flow out of the tank.
I do not think that Output batch for the tank can do this. It has to be a more complicated logic. My idea is to dispense the 10000.0 on one hand from the tank, reinject the 10000.0 with a fluidSource while synchronizing the dispense/reinject rate. Any other approach?


text:
Q: Conditional expectation of a vector Suppose we have two random vectors $X=(X_1,X_2)^T$ and $Y=(Y_1,\dots,Y_n)^T$. I wish to find a simple definition or formula for
$$
E_{X|Y=y}[X]
$$
Intuitively, I think the following is correct:
$$
E_{X|Y=y}[X]=\begin{pmatrix}E_{X_1|Y=y}[X_1]\\E_{X_2|Y=y}[X_2]\end{pmatrix}
\tag{1}
$$
Is this right? I imagine another possible definition could be
$$
E_{X|Y=y}[X]=\begin{pmatrix}E_{X|Y=y}[X_1]\\E_{X|Y=y}[X_2]\end{pmatrix}
\tag{2}
$$
But I don't think (2) is correct. I say this because, in the case of discrete $X$, (3) is more intuitive to me than (4):
$$
\big[E_{X|Y=y}[X]\big]_1=\sum_{x_1}x_1p_{X_1|Y}(x_1|y)=\sum_{x_1}x_1P(X_1=x_1|Y=y)
\tag{3}
$$
$$
\big[E_{X|Y=y}[X]\big]_1=\sum_{x}x_1p_{X|Y}(x|y)=\sum_{x}x_1P(X=x|Y=y)
\tag{4}
$$

A: (1) is correct and intuitive; while (2) is also correct because you can calculate $E[X_1]$ using the density of $X_1$ or the joint density of $X_1$ and $X_2$, e.g. (in your notation)
$$\begin{align}
E_{X|Y=y}[X_1] &= \sum_x{x_1P(X=x|Y=y)} \\
 &= \sum_{x_1}\sum_{x_2}{x_1P(X_1=x_1,X_2=x_2|Y=y)} \\
 &= \sum_{x_1}x_1\sum_{x_2}{P(X_1=x_1,X_2=x_2|Y=y)} \\
 &= \sum_{x_1}{x_1}P(X_1=x_1|Y=y) \\
 &= E_{X_1|Y=y}[X_1]
\end{align}$$


text:
Q: textField:shouldChangeCharactersInRange:replacementString vs. UITextFieldTextDidChangeNotification I'm building a Passcode Lock view, and I want to set the text to a dot on one of the four box labels when a user enters a new character into the text field.
Should I use textField:shouldChangeCharactersInRange:replacementString or UITextFieldTextDidChangeNotification?
Using textField:shouldChangeCharactersInRange:replacementString seems easier, but shouldChangeCharactersInRange seems more correct.

A: I'd recommend using the delegate method, rather than the notification.
Another option: set the text fields' secureTextEntry property to YES. (See the documentation for the UITextInputTraits protocol, which UITextField conforms to).


text:
Q: Problems with glossaries after miktex update I recently updated my Miktex distribution.
After that the makeglossaries command did not work anymore. I'm using WinEdt 9.1 to call makeglossaries.
I reinstalled the whole Miktex distribution and reinstalled active perl.
I tried to use makeglossaries from the command prompt with the same result.
I used xindy from the command prompt. This worked, so I think it's not a problem with perl.
I tried to compile this MWE:
\documentclass{scrartcl}
\usepackage[nomain,acronym,xindy,style=long]{glossaries}
\makeglossaries
\newacronym{a}{a}{a}

\begin{document}

\glsaddallunused[\acronymtype]
\printglossary[type=\acronymtype,]
\end{document}

Here is the message in the log file:
makeglossaries.exe: The script is not registered.
makeglossaries.exe: Data: scriptInterpreter="perl.exe", name="makeglossaries"

MakeGlossary failed to create a gls file.
For possible explanations start the command from the Command Prompt...

Has anybody an idea what I can try next?

A: It was a bug from Miktex. Problem solved with the latest update.


text:
Q: which xcode application for pre filling a database I am still learning xcode and objective-c. I use to build app for iphone environment only.
However I am in need of realizing an application with an existing prefilled sql database.
For prefilling the database I wouldn't like to use code in the ditributed app, but I would rather prefer to have a separate app for doing that.
The reason is that, the app could only download the updated database, rather than a whole code update .
So, questions are:

*

*is this a possible scenario

*if yes, what kind of application
should I build in xcode for
prefilling database ?

thanks

A: There's no reason that you can't have one app that both uses the database and downloads updates. Keeping the database updated without downloading the whole thing is pretty simple.
If you record the creation and modification timestamps of rows in the database on the server and keep track of those same modification timestamps on the device, updating the database works like this:

*

*The device determines latest modification timestamp it has for a given table. We'll call it latestTimestamp. It sends the latestTimestamp to the server.

*The server compares the latestTimestamp to the creation and modification timestamps in the database. The server sends back data based on the comparison result:

*

*If the modification timestamp is earlier than latestTimestamp it doesn't need to send the record, the device already has it;

*If the modification timestamp is later than latestTimestamp and the creation timestamp is earlier than latestTimestamp, it sends the record back noting that it is to be updated in the device database;

*If the modification timestamp is later than latestTimestamp and the creation timestamp is later than latestTimestamp, it sends the record back noting that it is to be added in the device database.

*Lastly, the server database needs to keep track of deleted records and a deletion timestamp for every record recorded. If latestTimestamp is later than the deletion timestamp, it sends back that the record needs to be deleted.
Obviously it gets a bit more complicated when you have a variety of connected tables, but as long as things are sent back in the correct order, it works great.
Use asynchronous data requests (the ASIHTTPRequest library makes it a breeze) and update the data in the background while the user uses the app. If it's essential that the data be updated prior to any interaction with it you can display an activity indicator and have the user wait.
No need at all for a separate app.

A: I would discourage you from doing that. No matter it is a pre-filled-database-purpose app, or a normal-purpose app, Apple Review Team would treat them with the same procedure, leaving the developer waiting for weeks before that app is finally available on App Store.
Besides, as far as I know, communication between apps is still strictly limited. If the data you would like to transfer between your main app and your db app is larger than a few lines of, let's say, NSString, it might be technically un-plausible.


text:
Q: Injective Holomorphic Functions that are not Conformal? Is it possible for a holomorphic function on a connected domain to be conformal but not injective? Also, is it possible for a holomorphic function to be injective but not conformal?

A: Example. The exponential function is conformal but not injective: its derivative is nowhere vanishing (so conformal) but $\exp 0 = \exp 2 \pi i$ (so not injective).
Proposition. The derivative of an injective holomorphic function $f : D \to \mathbb{C}$, where $D$ is an open subset in $\mathbb{C}$, is nowhere vanishing. In particular, $f$ is conformal.
Proof. We prove the a stronger statement, which will imply the contrapositive of the above proposition. Let $z_0 \in D$. By a change of coordinates if necessary, we may assume that $f(z_0) = 0$ and $z_0 = 0$ without loss of generality. Then, there is a positive integer $n$ and a holomorphic function $h : D \to \mathbb{C}$ such that $f(z) = z^n h(z)$ for all $z$ in $D$ and $h(0) \ne 0$. So in particular there is an open neighbourhood $U$ such that $0 \in U \subseteq D$ and $h$ is nowhere vanishing on $U$. That implies that there is a holomorphic function $g : U \to \mathbb{C}$ such that $g(z)^n = h(z)$ for all $z$ in $U$. (Take a holomorphic branch of the map $w \mapsto w^{1/n}$.) So $f(z) = (z \, g(z))^n$ for all $z$ in $U$.
Note that $z \mapsto z \, g(z)$ has non-zero derivative at $0$ (since $g(0) \ne 0$), so by the inverse function theorem, if $U$ is small enough, $z \mapsto z \, g(z)$ is an invertible holomorphic function on $U$. This implies $f$ is an $n$-to-$1$ function on $U \setminus \{ 0 \}$. But if $f'(0) = 0$, by considering the power series of $f$, we must have $n \ge 2$.
We conclude that a holomorphic function $f : D \to \mathbb{C}$ has derivative vanishing at $z_0$ if and only if it fails to be locally injective at $z_0$.
(This is probably my favourite result in complex analysis.)

A: It is not possible for a holomorphic function to be injective but not conformal; for a holomorphic f to be injective, its derivative must be non-zero, and conformality of f is precisely equivalent to having $f'(z)\neq 0$.
On the other hand, it is possible for f to be conformal but not injective: $expz:=e^z$ is one example.Conformality follows from the fact that f(z) is analytic , and $\frac{de^z}{dz}=e^z$, and $e^z\neq 0$;
(use the identity $e^ze^{-z}=1$ to show $e^z\neq 0$)
EDIT:  Conformality follows from the Cauchy-Riemann equations , which show that the effect of f'(z) is that of stretching and rotating. If f'(z) is not zero, then any  tangent vector forming an angle $\theta$ will be rotated, under f'(z) by an agle $\theta$, so that two vectors $v,w$ forming an angle $\gamma$ between them, will each be rotated by the same amount, with the effect that the net difference in the angles of the vectors v,w, and their respective images f(v),f(w) is $\theta -\theta=0$


text:
Q: Python variables not sent as values to batch file I have a python script where I am extracting values from a dataframe and trying to send them to a batch file. However, the values of the variables are not sent - the batch file is receiving them as variable names.
Assuming all imports are in place.
for i,row in ftp_df.iterrows():
                if row['client_name']==client_name:
                    a_ftp_host=row['ftp_host']
                    a_ftp_user=row['ftp_username']
                    a_ftp_pass=row['ftp_password']
                    print(a_ftp_host)
                    print(a_ftp_user)
                    print(a_ftp_pass)
                    os.system("C:\\Temp\\ftp_test.bat a_ftp_user a_ftp_pass filename")

the batch file ftp_test.bat is as follows.
Echo "****----****----****"
Echo "Uploading test.txt"
Echo "****----****----****"
Echo %1%
Echo %2%
Echo %3%
user="%1%"
pass="%2%"
file="%file%"

"WinSCP.com" ^
 /log="C:\temp\WinSCP.log" /ini=nul ^
 /command ^
"open sftp://%user%:%pass%@xx.xx.xxx/ -hostkey=""ssh-
 xxxxxxxxxxxxxxxxxxxxxxxxxx""" ^
"put -nopermissions -nopreservetime %file%" ^
"exit"

When executing this, it fails with error:
   C:>Searching for host...
   Host does not exist
   No session.
   Host does not exist
   No session.
it looks like the username and password being sent are handles not the values.
 independently, when executing the batch file with hard-coded credentials, it works.
what am i doing wrong?

A: You are passing literal strings of a_ftp_user, a_ftp_pass
and filename.
Examples below will double quote the arguments even if not needed
as I do not know if spaces exist in the arguments.
You can concatenate the variables with the string parts of the command.
os.system('"C:\\Temp\\ftp_test.bat" "' + a_ftp_user + '" "' + a_ftp_pass + '" "' + filename + '"')

Or, you could format the string to avoid + concatenation and
use {} placeholders instead.
os.system('"C:\\Temp\\ftp_test.bat" "{}" "{}" "{}"'.format(a_ftp_user, a_ftp_pass, filename))

Or if you are using Python 3.6+, you can use f-strings to replace
variable names in a string with the values. Note the f before the string.
os.system(f'"C:\\Temp\\ftp_test.bat" "a_ftp_user" "a_ftp_pass" "filename"')

View string - Common string operations about string formatting.
Finally, your batch syntax require the set to be altered i.e.:
set "user=%~1"

which gets the 1st argument.


text:
Q: How to build a query in order to get not expired records in Yii2 I have a model in my project which has several fields like id, name, due_year, due_quarter, etc. Here is my table
The issue is that I want to get that records where the field "due_year" is greater than 2017 and at the same time, the field "due_quarter" must be less than 4. In simple words, I am trying to get unexpired records. I tried to build a query like this:
$rows = Model::find()
    ->andFilterWhere(['>=', 'due_year', date('Y')])
    ->andFilterWhere(['<', 'due_quarter', 4])
    ->all();

but unfortunately i got expired rows as well.
Thank you in advance