text:
Q: PropertyValuesHolder; type float not found on target class I am receiving an issue with my Proguard setup. I am animating vehicle markers using standard animator for google maps. In my test environment everything works, however, in the production environment the animations do not work. I am missing something in my proguard-rules. The error I am receiving is:
10-14 16:43:11.912 3730-3730/? W/PropertyValuesHolder: Method setAlpha() with type float not found on target class class com.google.android.gms.maps.model.e
10-14 16:43:11.912 3730-3730/? W/PropertyValuesHolder: Method setAlpha() with type float not found on target class class com.google.android.gms.maps.model.e
10-14 16:43:11.912 3730-3730/? W/PropertyValuesHolder: Method setAlpha() with type float not found on target class class com.google.android.gms.maps.model.e
10-14 16:43:11.932 273-273/? W/SurfaceFlinger: Fail to Open /sys/devices/platform/gpusysfs/fps

I tried adding the following but they did not help, however, I do believe I am on the right track for why I am receiving this conflict
#The class where I am animating my markers
-keep class com.example.VehicleMarker {
    void set*(***);
    *** get*();
}

#Keep due to ObjectAnimator using reflection to access get/sets
-keep class com.example.VehicleMarker { *; }

Here is my entire proguard-rules file
#PROGUARD DEFINITIONS
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose

-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

#Keep annotations and method signature
-keepattributes *Annotation*
-keepattributes Signature

#Keep classes that are referenced on the AndroidManifest
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class com.android.vending.licensing.ILicensingService

#Keep set and get values for VehicleMarker class
-keep class com.example.VehicleMarker {
    void set*(***);
    *** get*();
}

#Keep due to ObjectAnimator using reflection to access get/sets
-keep class com.example.VehicleMarker { *; }

#Maintain google libraries (won't be stripped)
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

#Maintain gms annotations
-dontwarn com.google.android.gms.**
-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

#Maintain twitter
-dontwarn twitter4j.**
-keep class twitter4j.conf.PropertyConfigurationFactory
-keep class twitter4j.** { *; }

#Maintain square okhttp
-dontwarn okio.**
-dontwarn com.squareup.okhttp.**
-keep class com.squareup.okhttp.** { *; }
-keep interface com.squareup.okhttp.** { *; }

#Maintain retrofit
-dontwarn rx.**
-dontwarn retrofit.**
-keep class retrofit.** { *; }
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}

#Maintain flurry
-dontwarn com.flurry.**
-keep class com.flurry.** { *; }

#Maintain facebook
-keep class com.facebook.** { *; }

#To remove debug logs:
-assumenosideeffects class android.util.Log {
    public static *** d(...);
    public static *** v(...);
}

#Maintain java native methods
-keepclasseswithmembernames class * {
    native <methods>;
}

#Maintain classes with member names
-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

#Maintain classes with member names
-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

#Maintain classes with enum
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

#Maintain parcelable objects
-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

#Maintain list resource bundles
-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

#Keep the R
-keepclassmembers class **.R$* {
    public static <fields>;
}

#To repackage classes on a single package
-repackageclasses ''

#Print mapping
-printmapping mapping.txt

Any help with this would be appreciated. Thanks in advance!


text:
Q: $A \cap B \subset (A \cap C) \cup (B \cap C')$ How do i show this?
$A \cap B \subset (A \cap C) \cup (B \cap C')$
$$ x \in A \cap B$$
$$ \implies x \in A \cap B \cup \emptyset$$
$$ \implies x \in A \cap B \cup (C \cap C')$$
$$ \implies x \in (A \cap B \cup C)\cap(A \cap B  \cup C')$$
How do i proceed?

A: NOTE: This answers the previous version of this question.
I would use a different approach.
Lemma: $P\subseteq P\cup Q$
Proof:
$$\begin{align}
x\in P & \implies x\in P \lor x\in Q \\
 & \implies x\in P\cup Q
\end{align}$$
Proof of main problem:
In the lemma, substitute $P=A\cap B$, $Q=B\cap C'$. Then we get
$$A\cap B\subseteq (A\cap B) \cup (B\cap C')$$

If you really want to continue the approach you started (which actually uses my lemma without being explicit),
$$\begin{align}
x\in A\cap B
 &\implies x\in A\cap B \lor x\in B\cap C' \\
 &\implies x\in (A\cap B) \cup (B\cap C')
\end{align}$$

A: Use the fact that
$$X \subseteq (X \cap C) \cup (X \cap C')$$
Then
$$A \cap B \subseteq (A \cap B \cap C) \cup (A \cap B \cap C')\subseteq (A  \cap C) \cup ( B \cap C')$$

A: Suppose that $x$ is in both $A$ and $B$, i.e. $x \in A \cap B$. Then either $x$ is in $C$, in which case it is then in the intersection $A \cap C$; or it's not in $C$, in which case it is in $C'$, thus it is in $B \cap C'$. In the end, $x$ is in both cases in the union $(A \cap C) \cup (B \cap C')$. Since this was true for all $x \in A \cap B$, it follows that $A \cap B \subset (A \cap C) \cup (B \cap C')$.
(This answer is here because I don't believe math should be about wildly manipulating strings of symbols using arcane rules in hopes of getting the correct sequence of symbols at the end of the implication arrow.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I sum a tensor by progressing index on specific axis? I am working with time series returns and I want to find the cumulative return by time index. Assume the last index of a given time horizon should be itself, and the 1st index of a horizon should be the sum of all timesteps.
In the following example, I have a boolean mask indicating what timesteps should be added together for a given index. I just don't know where to go from here.
import tensorflow as tf

# Shape: (samples, horizon, feature)
source = tf.constant([[[0], [1], [2], [3]], [[4], [5], [6], [7]]])
# Shape: (horizon, horizon)
mask = tf.linalg.band_part(tf.ones((source.shape[1], source.shape[1])), 0, -1)

# Result should be tf.constant([[[6], [6], [5], [3]], [[22], [18], [13], [7]]])

A: You can expand mask in the samples dimension, then use tf.matmul to get desired result
source = tf.constant([[[0], [1], [2], [3]], [[4], [5], [6], [7]]])
mask = tf.linalg.band_part(tf.ones((source.shape[1], source.shape[1])), 0, -1)
mask = tf.cast(mask, tf.int32)
ans = tf.matmul(mask[None,:,:], source)

Output
<tf.Tensor: shape=(2, 4, 1), dtype=int32, numpy=
array([[[ 6],
        [ 6],
        [ 5],
        [ 3]],

       [[22],
        [18],
        [13],
        [ 7]]])>

To do it without a mask, you can flip source on the horizon axis, perform a tf.cumsum, then flip the resultant tensor on the horizon axis again
ans = tf.reverse(tf.cumsum(tf.reverse(source, axis=[1]), axis=1), axis=[1])

Output
<tf.Tensor: shape=(2, 4, 1), dtype=int32, numpy=
array([[[ 6],
        [ 6],
        [ 5],
        [ 3]],

       [[22],
        [18],
        [13],
        [ 7]]])>


text:
Q: How to convert XML file to HL7 format in C# .Net I am facing the problem while converting the XML data into HL7 format. I am using C# .Net. I am generating the XML file but client is now expecting the data in HL7 format. I have tried a lot and seach on google but not much information is available
The same file as below .
 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<LifeCarePatientResult>
  <PatientSettings>
    <PatientSetting Name="Identity">
      <Value>11212</Value>
    </PatientSetting>
    <PatientSetting Name="FirstName">
      <Value></Value>
    </PatientSetting>
    <PatientSetting Name="LastName">
      <Value></Value>
    </PatientSetting>
  </PatientSettings>
  <Measurement Id="86351403-af11-4986-bb26-2d2efa77db8e">
    <DateTime>2017-10-24 16:00:09</DateTime>
    <NoValue>18</NoValue>
    <Mode>SixSecond</Mode>
    <Instrument>030700364</Instrument>
    <Firmware>1D1B1D03</Firmware>
    <LifeCarePanelVersion>1.1.0.32000</LifeCarePanelVersion>
    <Sensor>25691</Sensor>
    <SequenceNumber>620</SequenceNumber>
    <TemperatureWarning>false</TemperatureWarning>
    <HumidityWarning>false</HumidityWarning>
    <FailTotal>0</FailTotal>
    <FailAboveMax_A10>0</FailAboveMax_A10>
    <FailBelowMin_A11>0</FailBelowMin_A11>
    <FailTooLongCount_A12>0</FailTooLongCount_A12>
    <FailDuringAnalysisCount_A13>0</FailDuringAnalysisCount_A13>
    <FailOther>0</FailOther>
  </Measurement>
</LifeCarePatientResult>

A: As pointed out in the comments and the alternative question, the 100% .net way is to use nhapi.  But for the amount of effort you would be looking at, you really should be looking at an HL7 Tool.  They are comparatively cheap, and will save you huge amounts of time.
Here is how to do it in HL7 Soup.  It allows you to write .net code as part of the transformation, but you'll see that you probably won't need to.
The first thing you need is an HL7 message that will be your target.  Your client can probably provide this, but for the sake of demonstration, here is a simplified one from the HL7 Soup Samples.
MSH|^~\&|HL7Soup|Instance1|HL7Soup|Instance2|20060922162830|L674-200609221628310220|ORU^R01|ORU000016168|P|2.5.1|||AL |AL
PID||75675|1478895^4^M10^PA||XTEST^PATIENT^||19591123| F||||||||||||||||||||||
ORC|RE|F4334|51013174200601|||||^||||||||||||||||
OBR|1|F4334|51013174200601|80048^BASIC METABOLIC PANEL|||20060922152300||||||||^^^^^|023901^PACLAB| ||||||^|CH|F|^^|^^^20060922162659^^GHA||^|||^^^^^^ ^^^^|^^^^^^^^^^|^^^^^^^^^^|^^^^^^^^^^||||||||||
OBX|1|NM|84295^SODIUM^GH|1|145|mmol/L|||||F|||20060922152300|GH
Understanding this message is beyond the scope of this answer, but if you are unsure, google "HL7 Tutorial", there are some helpful videos out there.  HL7 Soup is also excellent at explaining what the message means.
Now that you have your Source and Destination messages, load HL7 Soup, and create a new receiver.

Then change the receiver type to a "directory scanner"

Now you just need to configure it to monitor a directory waiting for your xml file.  Notice that I have placed your xml file in as the inbound template.

Ok, so now we have configured the importation of the xml, we need to configure the outbound HL7 message.  I'll output that as a file too.
Add another activity to the workflow by clicking here.

Now change this activity to a File Writer.

Now we need to configure the File Writer activity to output the HL7 File.  I've set it to write a file with the name c:\Temp\HL7File.HL7, then also requested that it is moved to a different directory once it is written - moving it ensures a unique filename.   I've also put in the HL7 message to use as a template at the bottom.

Now all we need to do is create a mapping between the XML and the HL7 messages.  Click the Edit Transformer (yellow arrow) in the image above.
Here is what you get.  Two trees representing the source message and the destination message.

Now all you need to do is drag the source items across to their corresponding destination items one at a time to create your mapping.
This video explains it in a bit more detail - Transforming HL7 data, but ultimately you end up with a mapping between your source and destination messages.
Here's three of the fields mapped as an example, but you would do it for every value you want to map across.
Notice how the mapping is just an xpath statement that points to the Source value and an HL7 path pointing to the Destination.  You can manually edit these to make the xpath exactly what you need for your message, such as looking for the items by XML attribute name.

Once you have completed all the mappings just save the workflow and return to the main HL7 Soup screen, then start your workflow running.

Now every file you drop into your directory will be converted to HL7 and dropped into your new directory.


text:
Q: Run Time of a Process in windows XP Can I see what a process was started on windows XP?  I don't see it as column in task manager, there another way?

A: Try this on the command line.
wmic process get caption,creationdate

Refer to Windows Management Instrumentation Command-line

A: Using Microsoft/SysInternals Process Explorer, which is a much more full-featured process manager, you can add a Process Start Time column to the basic process list to see the time each process started.

A: I'm sure heavyd's answer is probably right.  But after I asked I found 'Elapsed Time' under the process counter for the particular process in perfmon.  The 'Explain' says:

"The total elapsed time, in seconds,
  that this process has been running."


text:
Q: Get UserName of existing Process C# I am trying to get a DomainName\UserName associated with a Process in a C# application. All the other data I need to collect about a application I can access via the Process.GetProcessesById() method. The object returned also contains a property for the DomainName and UserName however this always seems to be an empty string when getting an existing process.
I know I can also get this information by querying the WMI object for the user name, however is there anyway to get this by simply doing the following?
Process.GetProcessById(1234).StartInfo.UserName


text:
Q: The review sticky panel should actually be sticky Currently, the sticky review result panel is causing the page to jump up and down as I scroll. It's irritating. This is because JavaScript is changing it from position: static; to position: fixed;. It should just have position: sticky;.
Exacerbating this issue is that the close description is now displayed even if you click the (less) link, making the bar take up a considerable amount of the screen – and so rendering areas of the page literally impossible to bring into view unless I make my browser window massive. This is a usability concern.
I would like to be able to review without deleting elements from the DOM.


text:
Q: How to read Adafruit GPS Data with STM32? I'm using a STM32 Nucleo-F334R8 board and a Ultimate GPS Breakout V3 from Adafruit.
What I'm trying to do is to read the GPS data with Putty on my computer using the serial communication.
At the end I want to get the GPS data on my F334R8 board and then send it to a RaspberryPi 3 with the serial communication. I'm having a lot of trouble so far, I'm coding on Mbed Compiler Online and every time I have the feeling to find a solution it gets worse.
Does anyone have a solution for me?
EDIT :
Alright thank you! I'm also trying to send my received data to a Raspberry Pi 3 through serial communication. I have connected the D15 and D14 to the TX and RX of the Raspberry but when i'm using :
#include "mbed.h"
#include "MTK3339.h"

static int waitData = 0;
static MTK3339 gps(D8, D2);
static float latitude = 0;
static float longitude = 0;

Serial rasp(D15, D14); // D15 = RX, D14 = TX

static void dataAvailable() {
    waitData |= gps.getAvailableDataType();
}

int main(void) {

    gps.start(&dataAvailable, (MTK3339::NmeaGga|MTK3339::NmeaVtg));

    while(1) {
        while(waitData == 0);

        if ((waitData & MTK3339::NmeaGga) != 0) {
            waitData &= ~(MTK3339::NmeaGga);
            latitude = gps.getLatitudeAsDegrees();
            longitude = gps.getLongitudeAsDegrees();
            //printf("%f,%f\n", gps.getLatitudeAsDegrees(), gps.getLongitudeAsDegrees());
            //printf("lat = %f, long = %f",latitude, longitude);
            rasp.printf("%f\n", latitude);
        }

        waitData &= (MTK3339::NmeaGga|MTK3339::NmeaVtg);
    }
}

But it's not working. I'm not receiving anything on the Raspberry console.
Could someone help please?

A: Here's an example application which reads data of the GPS chip that's on the Adafruit board: https://os.mbed.com/users/embeddedartists/code/app_gps/
Hook the GPS chip to the F334R8 board over UART on pins D8/D2 (D0/D1 are not usable for UART on that board as it's used for communication with the computer). Then change line 5 in main.cpp to:
static MTK3339 gps(D8, D2);


text:
Q: ExpandableListView groupItem inside Fragment+ViewPager cuts off half of the item horizontally I have a ExpandableListView inside of a fragment inside of a ViewPager.
The issue is that the group item is being cut in half horizontally, show below in the image.
I have the same exact code for the ExpandableListView elsewhere in the application, but inside of an activity, and it works fine?
XML layout for the group item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="30dp"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/lbl_exercise_group"
        android:layout_width="fill_parent"
        android:layout_height="30dp"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textSize="20dp"
        android:textColor="@color/white"
        android:background="@color/material_blue_500"
        />

</LinearLayout>

A: I think the layout_with from The TextView should be match_parent for the full size.

A: The issue was: in my ExpandableListView XML definition layout_width was set to wrap_content, it needed to be fill_parent
I changed:
 <ExpandableListView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/exList_exercises"
        android:clickable="true"
        />

to
<ExpandableListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/exList_exercises"
        android:clickable="true"
        />


text:
Q: Feing client authentication with oauth2 Eureka load balancer Im using oath2 registered in Eureka with 2 machines, for resouce exists a parameter like loadbalanced true
spring:
  oauth2:
    resource:
      loadBalanced: true
      userInfoUri: http:// oauth2/uaa/user

Question is it possible use a load balance for client?
example
spring:
  oauth2:
    sso:
      home:
        secure: true
        path: /,/**/*.html
    client:
      accessTokenUri: http://. localhost:9999/uaa/oauth/token
      userAuthorizationUri: http://. localhost:9999/uaa/oauth/authorize
      clientId: edge
      clientSecret: secret

Today im using a resquest interceptor for gets a loadbalanced uri, will spring release something like this?


text:
Q: Eclipse Git : auto-synchronising 2 branches I am working on a project with some mates.
Yesterday I cloned the project with the intention to add a functionality.
I have 2 local branches that are develop (the main branch) and pageContent (my feature branch).
The problem I am currently encountering is when I edit something on my feature branch, it automatically edits it on my developp branch too (I did not commit anything).
I checked out on my developp branch to delete the edition and when I checked out on my feature branch, the edition was deleted too ...
The branches seem to be auto-synchronised.

A:
I checked out on my develop branch to delete the edition and when I checked out on my feature branch, the edition was deleted too ...

This is how git works.

In the following diagram you can see the 3 states.
Git has three main states that your files can reside in.

They are all shared between your branches. but when you checkout branch you change the HEAD so you end up with the staging area && working directory shared between your repository even when you checkout branches.

Since you did not commit (i assume that what happened) when you switch branches you see the changes following you to your new branch.
If you don't want the changes to follow you you need to commit (or stash)  your work before switching to the branch.
How to checkout different branch with clean working directory and stage area?
If you wish to checkout clean branch without any "leftovers" in your working directory and staging are you can create a new worktree which will result in shared view of your repository  (all the content is shared) but with a different working directory and staging area.

From git v2.5
git worktree add <new_path>

Now do whatever you want in any of your branches. It will create 2 separate working folders separated from each other while pointing to the same repository.
Using wortree you don't have to do any clear or reset in order to remove all your staged and untracked content.
Here is demo of how to do it:


text:
Q: How to connect a element matching a fullstring with the corresponding button in this case? Using Selenium/Python I have a WebElement list with notes and another WebElement list with the corresponding buttons. If  a note in the list matches the variable fullstring I want to click on the corresponding button. E.g. if note 1 holds fullstring I want to click on the first button in the list. If note three holds the list I want to click on the corresponding third button in the button list. My code looks like this:
fullstring = "monthly"

signListNoteType = WebDriverWait(driver, 40).until(
        EC.presence_of_all_elements_located((By.XPATH, xpathSignListNoteType)))

noteButtonList = WebDriverWait(driver, 40).until(
        EC.presence_of_all_elements_located((By.XPATH, xpathNoteButtonList)))

for index, noteType in enumerate(signListNoteType, start=0):   # default start of index is zero
    index = index
    noteType = noteType.text
    print("Index:", index, noteType)

for index, noteButton in enumerate(noteButtonList, start=0):   # default start of index is zero
    index = index
    noteButton = noteButton
    print("Index:", index, noteButton)

if noteType == fullstring:

But I don't know how to code the logic.

A: What about something like this?
for i in range(len(signListNoteType)):
    if signListNoteType[i].text == fullstring:
        noteButtonList[i].click()


text:
Q: Compilation error with template class I tried with the below code snippet and got the compilation error as described below
Code snippet:
#include <iostream>

using namespace std;

template <class TYPE1>
struct SDataContainer
{
    SDataContainer(TYPE1 pData)
    {
        m_pData = pData;
    }

    bool operator==(const SDataContainer<TYPE1>& pData)
    {
        return (m_pData == pData.m_pData);
    }

    TYPE1 m_pData;
};
template <class DATATYPE1>
class Comparison
{
    public:
        Comparison (const SDataContainer<DATATYPE1>& pSData)
        {
            m_SData = pSData;
        }
        bool operator==(const Comparison<DATATYPE1>& pData)
        {
            return (m_SData.m_pData == pData.m_SData.m_pData);
        }
        SDataContainer<DATATYPE1> m_SData;
};
int main()
{
    SDataContainer<float> sDCObj1 (10.0);
    SDataContainer<float> sDCObj2 (10.0);
    cout << "Verify the data: " << (sDCObj1 == sDCObj2) << endl;
    Comparison<float> sCObj1 (sDCObj1);
    Comparison<float> sCObj2 (sDCObj2);
    cout << "Verify the data: " << (sCObj1 == sCObj2) << endl;
    return 0;
}

Compialtion error:
template.cpp: In constructor âComparison::Comparison(const SDataContainer&) [with DATATYPE1 = float]â:
template.cpp:45:38:   instantiated from here
template.cpp:26:9: error: no matching function for call to âSDataContainer::SDataContainer()â
template.cpp:26:9: note: candidates are:
template.cpp:8:5: note: SDataContainer::SDataContainer(TYPE1) [with TYPE1 = float]
template.cpp:8:5: note:   candidate expects 1 argument, 0 provided
template.cpp:6:8: note: SDataContainer::SDataContainer(const SDataContainer&)
template.cpp:6:8: note:   candidate expects 1 argument, 0 provide
I could not get the reason for the compilation error.
Can somebody help me in this issue?

A: The problem is
    Comparison (const SDataContainer<DATATYPE1>& pSData)
      // <<< here
    {
        m_SData = pSData;
    }

Because you don't supply an initializer list, one is implied for you, as if you wrote:
    Comparison (const SDataContainer<DATATYPE1>& pSData)
    : m_SData()
    {
        m_SData = pSData;
    }

which wants to invoke the default constructor for SDataContainer.
The solution is to change your code like this:
    Comparison (const SDataContainer<DATATYPE1>& pSData)
    : m_SData(pSData)
    {
    }

or to add a default constructor to SDataContainer.
working demo: http://ideone.com/Z0ycCj


text:
Q: can we limit the Azure region/location of deployment in ARM createUIdefinition.json? Is it possible to allow a deployment of ARM template in only selected regions/locations of Azure. If so how we can achieve it in createUIdefinition.json ARM template?

A: I found the answer from: https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/azure-resource-manager/managed-applications/create-uidefinition-overview.md

For location, specify the properties for the location control you wish
to override. Any properties not overridden are set to their default
values. resourceTypes accepts an array of strings containing fully
qualified resource type names. The location options are restricted to
only regions that support the resource types. allowedValues accepts an
array of region strings. Only those regions appear in the
dropdown. You can set both allowedValues and resourceTypes. The result
is the intersection of both lists. Lastly, the visible property can be
used to conditionally or completely disable the location dropdown.

I tested this and it works:
 "$schema": "https://schema.management.azure.com/schemas/0.1.2-preview/CreateUIDefinition.MultiVm.json#",
  "handler": "Microsoft.Azure.CreateUIDef",
  "version": "0.1.2-preview",
  "parameters": {
    "config": {
      "isWizard": true,
      "basics": {
        "location": {
          "resourceTypes": [
            "microsoft.insights/components",
            "microsoft.insights/components/CurrentBillingFeatures",
            "Microsoft.Sql/servers",
            "Microsoft.Web/sites",
            "Microsoft.Web/serverfarms"
          ]
        }
      }
    },

"microsoft.insights/components" is not available in West Central US currently and it was removed from the Location options.

A: You can try something like this:
 {
        "$schema": "https://schema.management.azure.com/schemas/0.1.2-preview/CreateUIDefinition.MultiVm.json#",
        "handler": "Microsoft.Azure.CreateUIDef",
        "version": "0.1.2-preview",
        "parameters": {
            "config": {
                "isWizard": false,
                "basics": {
                    "location": {
                    "label": "Region",
                    "toolTip": "Choose the Azure region to deploy in. Only supported regions are listed.",
                    "resourceTypes": [
                        "Microsoft.Compute/virtualMachines"
                        ],
                    "allowedValues": [
                        "eastus",
                        "westus2"
                        ],
                    "visible": true
                    }
                }
            },
            "resourceTypes": [
                "Microsoft.Storage/storageAccounts",
                "Microsoft.Batch/batchAccounts"
            ],
            "basics": [
                {
                    "name": "resourceNamePrefix",
                    "type": "Microsoft.Common.TextBox",
                    "label": "Resource name prefix",
                    "defaultValue": "default",
                    "toolTip": "Specify a prefix...",
                    "visible": true,
                    "constraints": {
                        "regex": "...",
                        "validationMessage": "Must be...."
                    }
                }
            ],
            "steps": [
            ...
            ],
            "outputs": {
            ...
            }
        }
    }

A: I assume that I understand your question correctly. You want to deployment in a selected region.
Azure Resource Manager templates enable you to deploy and manage these resources as a group, using a JSON description of the resources and their deployment settings. When you create the template you can define the region of the resources with the "location" property. The code just like this:
{
      "condition": "<true-to-deploy-this-resource>",
      "apiVersion": "<api-version-of-resource>",
      "type": "<resource-provider-namespace/resource-type-name>",
      "name": "<name-of-the-resource>",
      "location": "<location-of-resource>",
      ...
}

If you want to create all the resources in the template in one selected region, you can set the "location" all with the same value. And then use the CLI command az group deployment create or PowerShell command New-AzureRmDeployment to deploy the template to Azure.


text:
Q: JSON format leads to .map is not a function With the current way strapi outputs a JSON I always get the error .map is not a function. It is a NEXT.JS Frontent. Could it be that this comes from the JSON not being output as an Array?
import React, { useEffect } from "react";

export default function Home({ posts }) {
  return (

      {posts &&
        posts.map((post) => (

{post.title}

        ))}

  );
}

export async function getStaticProps() {
  // get games from the api
  const res = await fetch("http://localhost:1337/api/games");
  const posts = await res.json();
  return {
    props: { posts },
  };
}

here I get: TypeError: posts.map is not a function
does anyone has a tip for a JS beginner how to fix that?
the JSON output is the following:
{"data":[{"id":1,"attributes":{"title":"Guild Wars 2","createdAt":"2022-02-04T20:14:17.254Z","updatedAt":"2022-02-05T10:52:55.696Z","publishedAt":"2022-02-05T10:52:55.693Z","url":"https://www.guildwars2.com","description":"Guild Wars 2 is an online role-playing game with fast-paced action combat, a rich and detailed universe of stories, awe-inspiring landscapes to explore, two challenging player vs. player modes—and no subscription fees!","free":false,"feature_combat":"Fast-paced combat and choose from an arsenal of professions, weapons, and playstyles. Attack on the move, dodge and roll away from enemy blows, and come to your allies' rescue midbattle.","feature_world":"A beautifull designed, rich and detailed universe of stories, awe-inspiring landscapes to explore.","feature_quests":"No questgivers but an exploartion oriented roam around quest system with housands of stories that change based on the actions of players like you.","feature_grouping":"In the open world, you can team up with every player you meet—no grouping required! Also offeres Raids and dungeons for groups.","feature_usp":"Quick, furious matches between small groups of players in organized PvP or join hundreds of other players in the grand battles of World vs. World"}},{"id":2,"attributes":{"title":"Firefly Online","createdAt":"2022-02-05T11:01:39.549Z","updatedAt":"2022-02-05T11:04:40.562Z","publishedAt":"2022-02-05T11:04:40.558Z","url":"www.keepflying.com","description":"\nFACTS\nOS:\nSetting:\nSci-Fi\nGenre:\nRPG\nRelease Year:\n2014\nPayment Model:\nfree to play\nPVP:\nPay for features:\nItem Shop:\nMonthly fee:\nLanguage: ","free":null,"feature_combat":"Seek out adventures","feature_world":"Assume the role of a ship captain – create a crew and customize a ship","feature_quests":"Online role playing game based on Firefly, Joss Whedon's cult-hit television series Firefly","feature_grouping":"Hire a crew","feature_usp":"Cross-platform player experience across devices"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":2}}}

A: This is because posts is a JSON object and not an array that you can use the map() function with. Instead, you need to give the array to the map() function before you can pull out the titles.
To access the array of the JSON object, you can use posts['data'].
export default function Home({ posts }) {
  return (

      {posts &&
        posts["data"].map((post) => (

{post.attributes.title}

        ))}

  );
}


text:
Q: Backpack crud field that displays an included filtered table I need to make a new type of field, let's call it included_table. If in Model employees I have a field of type select2 from model Departments, in Departments, I want to have a field of type included_table which displays the table of the employees from that department, in the same way as the crud does.
Is there an easy way of doing this? Or what would be the best way to start?
Thank you.

A: I don't think there's an easy way to do it. You'd have to code it yourself. You can start from the table field type, put it won't get you very far.
That's because it's a lot more complicated that it looks at first glance. Keep in mind that Backpack create/update forms work with refresh; if you put a table inside one of them, the expected behaviour might be to only "save" the information when you click the final "save" button; but you probably can't do that for the nested entity, because you'd be saving it with AJAX. Plus, you need to build that entire AJAX functionality yourself, including validation. It's not at all more difficult than using plain old Laravel - it's exactly the same. But Backpack won't help very much in this regard.
That being said, you'd probably be better off just putting a button in the list view for each Department, to go edit its employees. That's a lot easier to do, if you follow the nested resources tutorial.
Hope it helps.


text:
Q: Error when compiling with Windows DDK Forgive me for being a complete newbie with Windows DDK.
I have create a simple file named test.cpp:
#include <windows.h>

#define BAD_ADDRESS 0xBAADF00D

int __cdecl main(int argc, char* args[])
{
    char* p =(char*)BAD_ADDRESS;
    *p='A';
    return 0;
}

In the same directory I created a sources file like this:

TARGETNAME=test
TARGETTYPE=PROGRAM
TARGETPATH=obj

TARGETLIBS=$(SDK_LIB_PATH)\kernel32.lib

SOURCES= test.cpp

And a makefile like this:

#
# DO NOT EDIT THIS FILE!!!  Edit .\sources. if you want to add a new source
# file to this component.  This file merely indirects to the real make file
# that is shared by all the components of Windows
#
!INCLUDE $(NTMAKEENV)\makefile.def

After launching the Windows XP Free Build Environment I browse to the directory with the three files (test.cpp, makefile and sources) and run the following command:
F:\temp\debug\dir1>build -cZg
Which outputs:

BUILD: Adding /Y to COPYCMD so xcopy ops won't hang.
BUILD: Using 2 child processes
BUILD: Object root set to: ==> objfre_wxp_x86
BUILD: Compile and Link for i386
BUILD: Examining f:\temp\debug\dir1 directory for files to compile.
BUILD: Compiling (NoSync) f:\temp\debug\dir1 directory
1>Compiling - test.cpp for i386
BUILD: Compiling  f:\temp\debug\dir1 directory
BUILD: Linking f:\temp\debug\dir1 directory
1>Linking Executable - objfre_wxp_x86\i386\test.exe for i386
BUILD: Done

    2 files compiled
    1 executable built

The problem is that when I run the created executable test.exe it says:

F:\temp\debug\dir1\objfre_wxp_x86\i386>test
The F:\temp\debug\dir1\objfre_wxp_x86\i386\test.exe application cannot be run in Win32 mode.

What am I missing here?

A: You have compiled a 'native application' rather than a win32 one.  The TARGET_TYPE definition controls this.
See 'Inside Native Applications' for a discussion of using the DDK to generate a native application.

A: Rob Walker explains the why but Kernel Mustard explains the how.


text:
Q: How to customize a ListView like this in wpf c#? I'm new to app dev. I am now stuck in the design of my app. This item is an item like a bulletin board. Just do not know which way is the right way to design my data in this style below? I had no idea whether to use the DATAGRIDVIEW OR LISTVIEW/LISTBOX?

Hope to get some idea from you guys

A: As Nex said, you are better off making the design shown in your picture as a usercontrol and after you do that use a ListView with a data template like this:
<ListView x:Name="mylistview">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            //a Panel container (i.e stackpanel, wrappanel)
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
        <DataTemplate>
            //Your usercontrol
        </DataTemplate>
    </ListView.ItemTemplate>

and of course you will need to use data binding to show your data.


text:
Q: Убрать выделение первой ячейки в DataGridView Здравствуйте, нашёл вот такой код для запрета в DataGridView использования символов кроме цифр и запятых.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            TextBox tb = (TextBox)e.Control;
            tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
        }
    }
    void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!((e.KeyChar >= (char)48 && e.KeyChar <= (char)57) || (e.KeyChar == (char)8) || (e.KeyChar == (char)45) || (e.KeyChar == (char)44)))
            e.Handled = true;
    }

Но возникла проблема с первой ячейкой в таблице, которая автоматически выделяется при запуске программы и событие не срабатывает для неё, пока не выберешь другую ячейку. Вопрос: Как сделать, чтобы при запуске не выделялась первая ячейка, либо как сделать чтобы событие выполнялось сразу после запуска.


text:
Q: dart2js Polymer Dart Sample ClickCounter App is OK in Firefox, fails in Chrome I am trying out a Polymer Dart App under Cordova. So I started with the Dart Editor Sample App.
I use a recent version of Polymer so I had to edit the sample code. Here is my pubspec.yaml
name: cortst
description: Cordova Test Application
dependencies:
 polymer: '>=0.15.1+3 <0.16.0'
transformers:
- polymer:
    entry_points:
    - web/cortst.html

And here is the combined HTML and Dart. I think the initialization uses the new/approved technique:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample App</title>

    <link rel="import"     href="clickcounter.html">
    <link rel="stylesheet" href="cortst.css">

A Test

      <click-counter count="5"></click-counter>

To generate stand-alone JavaScript I run dart2js via the command line:
pub build --mode=debug

And these are the results:

*

*Dartium (37.0.2062.120 (292122) via Dart Editor 1.7.2) - OK

*Run as JavaScript on Chrome (38.0.2125.111 m) - OK

*Run as JavaScript on Firefox (33.0.3) - OK

*dart2js and run on Chrome - no shadow DOM.

*dart2js and run on Firefox - OK

When it fails the click counter is rendered (invisibly) as
<click-counter count="5"></click-counter>

This Chrome problem matters because the standard web host on Android is Chrome.
For brevity, I have embedded the Dart script in the HTML. I get the same results when I use a separate .dart file.
Perhaps I have overlooked something - it wouldn't be the first time...


text:
Q: Online Pop-up website message I don't know that much of PHP and javascript but I know HTML and a bit of CSS.
I'd like to make a website that receives the messages in pop-ups. So the receiver will get the message and will direct him to that tab if he's on a different tab.
Basically this is for a game on facebook and we have a clan. We need to make the clan members be aware which clan to attack so I came up with this idea.
http://i.stack.imgur.com/UUCkD.png
! (I already have a website to put the page up.)
I'd like a blank webpage with the script of the pop-up.
and another webpage that has the text box to put in the message and sent it to that website.
I don't know if you understand my explanation but I think that's the closest I can explain to you. Please help guys, Thank you

A: To put javascript in html, it's like this:
<script>
JAVASCRIPT GOES HERE
</script>


text:
Q: What is the Proper Non-blocking Algorithm for Modbus Master on Microcontroller Modbus is a a request and response type serial communication. Basically the master send out a request and one of the slave response.
I am modifing the code on a microcontroller which is a master unit on a modbus network. This unit also has a small dot-matrix LCD and some buttons for user interface. The microcontroller is running at 16MHz.
The problem is after the master unit send out a request, it does not know when the slave response, so it may need to wait for a relatively long time. However as this unit has buttons and LCD, it can not wait at a point for too long because the user will feel lag when he pressed a button. The original code is using a RTOS. It seperate  the user interface task and the serial communication tasks so it has no problem. Now I need to change it to non-RTOS code. I have implemented a system tick timer which will interrupt at each 1ms. What is the proper (or common) way to do that?

A: It is possible to do quite a lot with just a single task, especially if you have interrupts. The intermediate position between a single very simple task and an RTOS is a cyclic executive. See http://www3.nd.edu/~cpoellab/teaching/cse40463/slides10.pdf for a brief overview of the spectrum of functionality from a cyclic executive up to a fully preemptive multitasking operating system. You will find much more if you search on this phrase and related phrases, including very sophisticated schemes for making sure that the system never misses its deadlines. If you are an aircraft flight control system, forgetting to check the aircraft pitch angle every X ms can cause problems elsewhere :-)
One way to rewrite code which is naturally multi-threaded is to maintain a model of the state of the system, such as a collection of objects each representing a modbus connection, indexed by a connection id. Then write a routine for every sort of event that can happen, including the arrival of a clock interrupt. When that event happens these routines typically work out which connection is involved, retrieve it from the main collection (or create it from scratch and enter it there if necessary) do the work associated with that particular sort of event, and then return.
It is often convenient to keep a queue of future events, indexed by time, and to have a routine that creates an object representing something to be done at some future time (such as calling a method to check for the expiration of a timeout) and puts this object on the queue.
You need to worry about interrupt processing getting called halfway through an event service routine. One way to deal with this is to lock out interrupts when that could cause a problem. Another way is to have the interrupt routine do nothing more than put an object on a queue that something else will check for later, or just set a flag. Then you need only lock out interrupts when you are checking for items on the queue and removing them.
A number of communications protocols are implemented in this way. Even in a true multitasking operating system you very often don't want to have to create a new thread every time you need to create a new connection. The two main problems with this is that the code is less clear than code which has a thread per object, because stuff that naturally goes together is chopped up into loads of event service events, and if any of the event service methods burn significant amounts of cpu, the system will stall because nothing else will happen when this is going on.


text:
Q: 'System.Windows.Markup.XamlParseException' setting up a context menu in a control template I am getting this error and I really have no idea how to solve it no matter how much I google!
This is the style defined in my Theme.xaml
    <Style x:Key="RightClickCopyPasteLabel" TargetType="Label">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Label">
                <ContextMenu>
                    <ContextMenu Opened="OnMenuOpened">
                        <MenuItem x:Name="CopyMenuItem" Click="OnCopyEvent" InputGestureText="Ctrl+C" Header="Copy" IsEnabled="{Binding CanExecuteCopy}">
                        </MenuItem>
                        <MenuItem x:Name="PasteMenuItem" Click="OnPasteEvent" InputGestureText="Ctrl+P" Header="Paste" IsEnabled="{Binding CanExecutePaste}">
                        </MenuItem>
                    </ContextMenu>
                </ContextMenu>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver">
                        <Setter Property="FontWeight" Value="Bold"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And this is my control. There is very little to say really. I think it should work. I want to create a template for a right click context menu that I can apply to labels. I am not sure where I am going wrong?
<UserControl x:Class="DataForgeEditor.Controls.Expander"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                     xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
                     xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
         mc:Ignorable="d">
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Themes/DataForgeTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

<Expander Name="ExpanderControl" Margin="5,5,5,5">
    <Expander.Header>
        <Label Name="ExpanderLabel" Style="{StaticResource RightClickCopyPasteLabel}" />
    </Expander.Header>
</Expander>

EDIT:
I have just tried this a very basic style.. this doesn't even work!
<Style x:Key="TestLabel" TargetType="Label">
    <Setter Property="Template">
        <Setter.Value>
            <Border Background="AntiqueWhite"></Border>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: Cannot find libeay32.lib and ssleay32.lib files when setting up openssl on windows x64 So I am trying to use openssl inside Visual Studio for some encryption project.
These are the steps I did until now:

*

*Download Win64 OpenSSL v1.1.1b from here.

*Set Additional Include Directories to point to the oppenssl/include directory (from instalation)

*Set Additional Dependencies inside Linker to: libcrypto.lib

*Set Additional Library Directories inside Linker to point to the openssl/lib directory (from instalation)

Now when I build I still get lots of undefined references errors.
From what I read I still need to include the libeay32.lib and ssleay32.lib, but I didn't find them anywhere in my openssl instalation directory.
I followed this links for help:
How to use OpenSSL with Visual Studio
How to include openssl in Visual Studio Expres 2012 Windows 7 x64
Aparently my only issue now is that I am missing this files. Anyone know where can I find them ?

A: "How to" out of date.
Since version 1.1.0 OpenSSL have changed their library names from:
libeay32.dll -> libcrypto.dll
ssleay32.dll -> libssl.dll
https://github.com/arvidn/libtorrent/issues/1931
I see now:

*

*MD: Multi-threaded DLL

*MDd: Multi-threaded Debug DLL

*MT: Multi-threaded (static)

*MTd Multi-threaded (static) Debug


text:
Q: Cakephp Model ignores condition in belongsTo I have 2 Models that are joined but not thrue the id's but with another field.
class Post extends AppModel{
    public $useDbConfig = 'test';
    public $actsAs = array('Containable');

    public $belongsTo= array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => false,
            'type' => 'inner',
            'conditions' => array('User.field = Post.field')
    ));
}

But the cakephp is not connecting the 2 models correctly. To every Post it just gives the the first user (User with id 1). When I check the SQL-Statements the User statement is following:
SELECT `User`.`id`, `User`.`group_id`... FROM `users` AS `User` WHERE 1 = 1

Any ideas why this is not working?
I also tried joining the models manually:
$this->paginate = array(
        'limit' => '15',
        'joins' => array(
            'INNER JOIN users User ON (User.field = Post.field)'
        )
    );

    $posts= $this->paginate('Post');

Any ideas?
EDIT
I totally forgot to mention that these 2 tables are in different databases. Maybe there is the problem. But I had no problem joining tables over different databases so far.
EDIT
I was wrong about the join so I changed it from "belongsTo" to "hasOne" since a post can only be written by one user. But still no changes.

A: You can use the foreignKey parameter to any field, not necessarily the id:
Post model:
public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'some_user_field'
    )
);

User model:
public $hasMany = array (
    'Post' => array (
        'className' => 'Post',
        'foreignKey' => 'some_user_field',
        'dependent' => true
    )
);

According to the book:

It is not mandatory to follow CakePHP conventions. You can easily
  override the use of any foreignKey in your associations definitions.
  Nevertheless, sticking to conventions will make your code less
  repetitive and easier to read and maintain.

Otherwise, make joins manually:
$this->paginate = array(
    'limit' => '15',
    'joins' => array(
        array(
            'table' => 'users',
            'alias' => 'User',
            'type' => 'inner',
            'conditions' => array('User.field = Post.field')
        )
    )
);

A: I found a solution although I don't understand why the others won't work. I put
$this->Post->primaryKey = 'field';

right before
$posts= $this->paginate('Post');

and now it works. Can anyone tell me why the other ways won't work?


text:
Q: ImageResizer: Disable size limitation of resizing I am using the ImageResizer (https://imageresizing.net/) library in a Azure Function which returns resized images stored in a Azure Storage Account.
Its working fine so far, but it has the limitation of resizing to maximum 3200 pixels. (https://imageresizing.net/docs/v4/plugins/sizelimiting)
Since i'm using a Azure Function I can't access a web.config to disable this limitation. Can I disable this limitation via code (maybe ResizeSettings)?
Thanks.

A: Normally you'd remove the SizeLimiting plugin in Application_Start but we don't currently give you any hooks in Azure Functions to run startup code. We've got an issue tracking that here in our repo.
However, you can still remove the plugin in your function code before doing any image processing, e.g.:
using ImageResizer;
using ImageResizer.Plugins.Basic;

public static void Run(..., TraceWriter log)
{
    RemoveSizeLimiter(log);

    ...
}

private static void RemoveSizeLimiter(TraceWriter log)
{
    var config = ImageResizer.Configuration.Config.Current;
    var sizeLimiter = config.Plugins.Get<SizeLimiting>();
    log.Info("SizeLimiter installed: " + (sizeLimiter != null).ToString());

    if (sizeLimiter != null)
    {
        log.Info("Uninstalling SizeLimiter");
        sizeLimiter.Uninstall(config);
    }
}

If you run this function multiple times, you'll see that the plugin is removed from the static Config.PlugIns collection the first time, and stays removed for the lifetime of the App Domain.


text:
Q: How do I get string representation of jpeg EXIF tags in c#? There are a lot of examples how you can enumerate and edit EXIF tags using Bitmap class.
Here's one:
        Bitmap bJpgWithExifData = (Bitmap)Image.FromFile(@"myfile.jpg");

        foreach (var item in bJpgWithExifData.PropertyItems)
        {
            Console.WriteLine( "{0}\t{1}\t{2}",item.Type,item.Id,item.Len);
        }

However, this doesn't explain how I get the string values of those tags. The data is binary, and when I try to decode it with Encoding.ASCII.GetString(item.Value), I get some junk instead of proper properties.
How do I get the string values?
UPDATE
Here are the exif tags as shown by JPEGSnoop:
  EXIF IFD0 @ Absolute 0x00000014
    Dir Length = 0x0010
    [Model                               ] = "GT-I9500"
    [Orientation                         ] = Row 0: top, Col 0: left
    [WhiteBalance                        ] = Auto white balance
    [DateTime                            ] = "2014:07:30 13:24:28"
    [Make                                ] = "SAMSUNG"
    [ExifOffset                          ] = @ 0x010C
    Offset to Next IFD = 0x00000000

When enumerating c# properties, I see 18 different properties, 2 of which are type 2 ("2014:07:30 13:24:28" and "SAMSUNG" converted to string)
How do I get the values of the rest?
UPDATE 1
Here's the code I use to print the values:
        foreach (var item in bJpgWithExifData.PropertyItems)
        {
            Console.WriteLine("{0}\t0x{1}\t{2}\t{3}\t{4}",item.Type,item.Id.ToString("x"),item.Len,Convert.ToBase64String(item.Value),Encoding.ASCII.GetString(item.Value));

        }

And here's the output:
3       0x100   2       IBA=     >
3       0x101   2       Egk=    ¦
2       0x10f   8       U0FNU1VORwA=    SAMSUNG
3       0x112   2       AQA=    O
2       0x132   20      MjAxNDowNzozMCAxMzoyNDoyOAA=    2014:07:30 13:24:28
10      0x829a  8       PgAAAOgDAAA=    >   ?¦
10      0x829d  8       FgAAAAoAAAA=    -

4       0x201   4       KgEAAA==        *O
4       0x202   4       AAAAAA==
3       0x8822  2       AgA=    O
3       0x8827  2       MgA=    2
3       0x9207  2       AgA=    O
3       0x9208  2       AAA=
3       0x9209  2       AQA=    O
5       0x920a  8       pAEAAGQAAAA=    ?O  d
3       0xa403  2       AAA=
3       0x5091  128     BwAHAAoAEwAoACgAKAAoAAcACAAKABoAKAAoACgAKAAKAAoAFgAoACgAKAAoACgAEwAaACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAA=
 ! ( ( ( (
 > ( ( ( (

 - ( ( ( ( ( ! > ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (
3       0x5090  128     BgAEAAQABgAKABAAFAAYAAUABQAGAAgACgAXABgAFgAGAAUABgAKABAAFwAcABYABgAHAAkADAAUACMAIAAZAAcACQAPABYAGwAsACkAHwAKAA4AFgAaACAAKgAtACUAFAAaAB8AIwApADAAMAAoAB0AJQAmACcALQAoACkAKAA=    ¦ ¦ ¦ ¦
 > ¶ ^ ¦ ¦
 ¦ ^ - ¦ ¦ ¦
 > ¦ L - ¦       + ¶ #   v       0 - < , ) Ў
 d - >   * - % ¶ > Ў # ) 0 0 ( - % & ' - ( ) (

A: I had to do the same thing a while ago. There is a Type property on the PropertyItem object. You'll need to use that value to determine what you need to do with each type of object.
I found this on Code Project that did a majority of the work on how to piece together the different types of values and then modified just a very little bit in order to customize some of the results.
Unfortunately, it's a ludicrously intricate process that is far too lengthy to go into here, but the little overview I gave should give you a good enough idea to check out the project, or know where to start if that URL ever dies in the future.

A: Check this library on Code Project: http://www.codeproject.com/Articles/36342/ExifLib-A-Fast-Exif-Data-Extractor-for-NET-2-0


text:
Q: NativeBase multiple icons in InputGroup I'm trying to make an InputGroup that has two icons OR one icon and one button.
One icon should be used to check if the input field is empty or not (got that working). The other icon OR button should be used to "inject" some text into the Input field.
Currently my code looks like this:
import React, { Component } from 'react'
import { Content, List, InputGroup, Input, Icon, Button } from 'native-base'
export default class AddEquipment extends Component {
  constructor(props) {
    super(props)

    this.state = {
      parameters:  {
        one: {value:"", hint: "One"},
        two: {value:"", hint: "Two"},
        three: {value:"Valid", hint: "Three"}
      }
    }

    this.updateParameter = this.updateParameter.bind(this)
    this.validationStyle = this.validationStyle.bind(this)
  }

  componentDidMount() {

  }

  updateParameter(key, value) {
    newState = {...this.state}
    newState.parameters[key].value = value
    this.setState = newState;
  }

  validationStyle(text) {
    color = text === "" ? "#b03939" : "#649370"
    return (
      { marginRight:25, color
      }
    )
  }

  render () {
    return (
      <Content>
        { Object
          .keys(this.state.parameters)
          .map( key =>
            <InputGroup
              key={`${key}_InputGroup`}
              iconRight
              borderType='regular'
              style={{margin:5}}
              >

              <Input
                placeholder={this.state.parameters[key].hint}
                onChangeText={(text) => {
                  console.log(this.state.parameters)
                  this.updateParameter(key, text)} }
                value={key.value}
              />

              <Icon
                key={`${key}_validIcon`}
                name={ this.state.parameters[key].value === "" ? 'ios-alert' : 'ios-checkmark-circle'}
                style={ this.validationStyle(this.state.parameters[key].value) }
              />

              <Icon
                key={`${key}_injectNA`}
                name='ios-beer'
                onPress={() => this.updateParameter(key, "Cheers!") }/>

            </InputGroup>
          )
        }
      </Content>
    )
  }
}

Which gives me the following result

First issue
As you can see I have trouble getting the other icon appear - it doesn't seem to lie behind the first.
A button would be as good, but it always drops below the Input and not next to it. Styling is not my strongest style - hence why I use the awesome framework NativeBase
Second issue
Another problem I have is that the validation does not seem to change icon and color after the state is being updated. Seems like the style are loaded only once.

A: on the first issue would you consider validity icon in front? InputGroup can dispay maximum two icons: before and after text input, see code below.
on the second issue it's caused that you assign value to the state, while in React you should call this.setState(newState), see reference
another issue is accessing to the object key's value by key.value, while key is just a string (key name), while real object accessed by this.state.parameters[key]
Following code fixes all mentioned issues (but validity icon is on the left):
import React, { Component } from 'react'
import { Content, List, InputGroup, Input, Icon, Button } from 'native-base'

const errorStyle = {color: "#b03939"}
const validStyle = {color: "#649370"}

export default class AddEquipment extends Component {
  constructor(props) {
    super(props)

    this.state = {
      parameters:  {
        one: {value:"", hint: "One"},
        two: {value:"", hint: "Two"},
        three: {value:"Valid", hint: "Three"}
      }
    }

    this.updateParameter = this.updateParameter.bind(this)
  }

  componentDidMount() {

  }

  updateParameter(key, value) {
    let newState = {...this.state}
    newState.parameters[key].value = value
    this.setState(newState);
  }

  static validationStyle(text) {
    return text === "" ? errorStyle : validStyle;
  }

  render () {
    return (
      <Content>
        { Object
          .keys(this.state.parameters)
          .map( key =>
            <InputGroup
              key={`${key}_InputGroup`}
              borderType='regular'
              style={{margin:5}}
              >

              <Icon
                  key={`${key}_validIcon`}
                  name={ this.state.parameters[key].value === "" ? 'ios-alert' : 'ios-checkmark-circle'}
                  style={ AddEquipment.validationStyle(this.state.parameters[key].value) }
                />

              <Input
                placeholder={this.state.parameters[key].hint}
                onChangeText={(text) => {
                  console.log(this.state.parameters)
                  this.updateParameter(key, text)} }
                value={this.state.parameters[key].value}
              />

              <Icon
                key={`${key}_injectNA`}
                name='ios-beer'
                onPress={() => this.updateParameter(key, "Cheers!") }/>

            </InputGroup>

          )
        }
      </Content>
    )
  }
}


text:
Q: split python string every nth character (string and nth character are in lists) I need something like this for my code:
Split python string every nth character?
In my case however; n are numbers within nested lists, and the strings I want to split are also within nested lists.
myList = [["'hello''my name'"],["'is Michael'"],["'and'", "'I like''apples'"]]

nList = [[7,9],[12],[5,8,8]

I want to get something like this:
myNewList = [["'hello'","'my name'"],["'is Michael'"],["'and'", "'I like'","'apples"]]

i.e I want to split the string by lengths corresponding to the numbers in nList.
I tried using a similar solution to the link I posted above:
My attempt:
myNewList = [myList[sum(nList[:i]):sum(nList[:i+1])] for i in range(len(nList))]

but it doesn't really match my case.
EDIT:
Note, I do not want to use split after each quote, however it is acceptable to offer it as a solution.  The numbers vary and this is a simplified scenario that I am using to allude to my situation with XML data handling/writing.

A: I have a solution for the case where the structures are compatible.  Part of your original problem was a missing subscript: each element of mlList is a sub-list that contains a list of strings.  I've concatenated the final list and inserted the [0] subscript, now redundant.
Is this close enough to get you moving?  If not, I can add the necessary ''.join to finish the job, but it's even uglier than this.
I, too, recommend that you employ an xml parsing tool and regular expressions.  This has been a lovely exercise, but it's not particularly maintainable.
myList = [["'hello''my name'"], ["'is Michael'"], ["'and''I like''apples'"]]
nList = [[7, 9], [12], [5, 8, 8]]
myNewList = [[myList[phrase][0][sum(nList[phrase][:spl]):sum(nList[phrase][:spl+1])]
              for spl in range(len(nList[phrase]))]
              for phrase in range(len(myList))]

print myNewList

Never mind; it was a trivial addition to my attempt above:
myList = [["'hello''my name'"], ["'is Michael'"], ["'and'", "'I like''apples'"]]
nList = [[7, 9], [12], [5, 8, 8]]
myNewList = [[''.join(myList[phrase])[sum(nList[phrase][:spl]):sum(nList[phrase][:spl+1])]
              for spl in range(len(nList[phrase]))]
              for phrase in range(len(myList))]

print myNewList

Output:
[["'hello'", "'my name'"], ["'is Michael'"], ["'and'", "'I like'", "'apples'"]]

A: res = []
for word, nums in zip(myList, nList):
    row = []
    curr = 0
    for offset in nums:
        row.append(word[0][curr:curr+offset])
        curr += offset
    res.append(row)

print(res)

Untested though.


text:
Q: Uploading a JSON file and using it How can I upload a JSON file on some click on a button on my web page say "import", and use it to store in a variable to use and update it using JavaScript.
I have gone through the other posts but could not find any answer.
I am saving the JSON variable using this function:
function save(filename, data){

    if(!data) {
        alert('error : No data')
        return;
    }

    if(typeof data === "object"){
        data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
 }

This is working fine and it downloads the file on clicking another button say "export".
How upload this file back and make a JSON variable of this file data?

A: Basic upload File:
    <input id="contentFile" type="file" accept="application/json" />

  document.getElementById('contentFile').onchange = function(evt) {
        try {
            let files = evt.target.files;
            if (!files.length) {
                alert('No file selected!');
                return;
            }
            let file = files[0];
            let reader = new FileReader();
            const self = this;
            reader.onload = (event) => {
                console.log('FILE CONTENT', event.target.result);
            };
            reader.readAsText(file);
        } catch (err) {
            console.error(err);
        }
    }

A: Without server side code, your best approach may be to provide a textarea element for the user to copy/paste the JSON into, and then parse it using JSON.parse.
You could even go as far as to use something like Ace Editor to provide syntax highlighting for JSON - you can see it in action on the Ace Editor Kitchen Sink Demo - select JSON from the dropdown list in the top left.

Edit:
Turns out I was wrong.  Here is a fiddle demonstrating the FileReader in use, which is exactly what you need:
https://jsfiddle.net/Ln37kqc0/
Here is the code:
Javascript:
document.getElementById('import').onclick = function() {
    var files = document.getElementById('selectFiles').files;
  console.log(files);
  if (files.length <= 0) {
    return false;
  }

  var fr = new FileReader();

  fr.onload = function(e) {
  console.log(e);
    var result = JSON.parse(e.target.result);
    var formatted = JSON.stringify(result, null, 2);
        document.getElementById('result').value = formatted;
  }

  fr.readAsText(files.item(0));
};

HTML:
<input type="file" id="selectFiles" value="Import" />

<button id="import">Import</button>
<textarea id="result"></textarea>

A: [2021] Promise based approach
As mentioned here, you can make use of the newer blob api to easily get the file's value via:
await blob.text()

const getJsonUpload = () =>
  new Promise(resolve => {
    const inputFileElement = document.createElement('input')
    inputFileElement.setAttribute('type', 'file')
    inputFileElement.setAttribute('multiple', 'true')
    inputFileElement.setAttribute('accept', '.json')

    inputFileElement.addEventListener(
      'change',
      async (event) => {
        const { files } = event.target
        if (!files) {
          return
        }

        const filePromises = [...files].map(file => file.text())

        resolve(await Promise.all(filePromises))
      },
      false,
    )
    inputFileElement.click()
  })

document.getElementById('upload-button').onclick = async () => {
    const jsonFiles = await getJsonUpload()
  console.log({jsonFiles})
}
<button id="upload-button">
Upload
</button>

A: Try this, works perfect
handleUploadFile = async(doc) => {
  let file = doc.target.files[0]
  let reader = new FileReader(file)

  // await reader.readAsDataURL(file)

  reader.readAsText(file)

  reader.onload = async(e) => {

    let aaa = e.target.result

    let content = await JSON.parse(aaa)
    console.log(content)

  }
}

A: I have got a way to use the uploaded json file, here is the way i found.
$("#inputFile").change(function(e) {
    onChange(e);
});

function onChange(event) {
    var reader = new FileReader();
    reader.onload = onReaderLoad;
    reader.readAsText(event.target.files[0]);
}

function onReaderLoad(event){
    //alert(event.target.result);
    var obj = JSON.parse(event.target.result);
    alert(obj);
}

A: With the newer Blob API, the current top answer can be simplified by skipping the FileReader:
document.getElementById('import').onclick = function() {
  var files = document.getElementById('selectFiles').files;
  console.log(files);
  if (files.length <= 0) {
    return false;
  }
  files[0].text().then(function(text) {
    console.log(text);
    var result = JSON.parse(text);
    var formatted = JSON.stringify(result, null, 2);
    document.getElementById('result').value = formatted;
  })
};

To explain the code a little: files[0] itself is a File object, which inherits from Blob, so files[0].text() is an asynchronous function that reads the content of the file into a string.

A: You may want to add the draggable option
Firs create your HTML

        <input class="box_file disabled" type="file" name="files[]" id="file" data-multiple-caption="{count} files selected" multiple />
        Choose save file or drag it here.

Than write out your JS
$("#drag_area").on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
    e.preventDefault();
    e.stopPropagation();
})
.on('dragover dragenter', function () {
    $("#drag_area").addClass('dr_active');
    // this is needed if you wish to style your drag area on drag events
})
.on('dragleave dragend drop', function () {
    $("#drag_area").removeClass('dr_active');
    // this is needed if you wish to style your drag area on drag events
})
.on('drop', function (e) {
    let droppedFiles = e.originalEvent.dataTransfer.files;
    let reader = new FileReader()
    reader.readAsDataURL(droppedFiles[0])
    reader.onloadend = function () {
    $.ajax({
        url: reader.result,
        success: function (data) {
          console.log(JSON.parse(data)); // This is your JSON
        },
        error: function (request, error) {
            cliLog(2, "Upload", "Cant upload save file")
        }
    });
}
}),

A: I'd made a more general approach with support to customize upload button title and callback when load is done:
function uploadJson(id, callback) {
    document.getElementById(id).onchange = function(evt) {
        try {
            let files = evt.target.files;
            if (!files.length) {
                alert('No file selected!');
                return;
            }
            let file = files[0];
            let reader = new FileReader();
            const self = this;
            reader.onload = (event) => {
                callback(event.target.result);
            };
            reader.readAsText(file);
        } catch (err) {
            console.error(err);
        }
    }
}

uploadJson('importJson', function (json) {
    console.log(json);
});

<button onclick="document.getElementById('importJson').click()">import json</button>
<input id="importJson" value="import json" type="file" accept="application/json" style="display:none" />


text:
Q: Is closeness in total variation preserved in conditioning? If we have two joint distributions on $(X,Y)$, $P_{X,Y}$ and $Q_{X,Y}$ that are close in $L^1$ or "total variation" with $\|P_{X,Y}-Q_{X,Y}\|_1<\varepsilon$ then:

*

*Are the distributions on the conditional expectations $P_{E[X|Y]}, Q_{E[X|Y]}$ also close in $L^1$, e.g. $\|P_{E[X|Y]}-Q_{E[X|Y]}\|_1<N\varepsilon$?

*In particular, what about the case where $Y=X+Z$ with $X\perp Z$?

*If $X,Y$ are finite mean and variance, then are the means and variances of $E[X|Y]$ under the two distributions close?

Assuming they are all continuous RVs, the difference is:
\begin{align}
\left|P_{E[X|Y]}(w)-Q_{E[X|Y]}(w)\right| &= \left|\int_{y\in A_P} P_Y(y) dy -\int_{y\in A_Q } Q_Y(y) dy\right|
\end{align}
with $A_P=\left\{y:\int x P(X=x|Y=y) dx = w\right\},\ A_Q=\left\{y:\int x Q(X=x|Y=y) dx = w\right\}.$
I can't figure out how to make the difference between the two sets small, which makes me suspicious that conditional expectation is unfortunately not continuous in this sense.

A:
For a counterexample for your first two cases, let $X,Z$ be independent Rademacher random variables and $Y = X+Z$.  Under $P$, suppose $X$ is Rademacher($p$) for some $p$ (i.e. $P(X=1) = p$, $P(X=-1)=1-p$), and $Z$ is Rademacher(1/2).  Under $Q$, suppose $X,Z$ are both Rademacher(1/2).  In each case, take $Y=X+Z$ as you suggest.
Now you can check that $$P_{X,Y} = \frac{p}{2} (\delta_{(1,2)} + \delta_{(1,0)})  + \frac{1-p}{2} (\delta_{(-1,0)} +\delta_{(-1,-2)})$$
and $Q_{X,Y}$ is the same with $p=1/2$.  You may compute directly that the total variation distance between $P_{X,Y}$ and $Q_{X,Y}$ is $|1-2p|$ and in particular it goes to zero as $p \to 1/2$.
Next, under $P$, note that
$$E[X \mid Y] = \begin{cases} 1, & Y=2 \\ -1, & Y = -2 \\ p - \frac{1}{2}, & Y=0 \end{cases}$$
where these events have probabilities $p/2$, $(1-p)/2$, $1/2$ respectively.  Hence
$$P_{E[X \mid Y]} = \frac{p}{2} \delta_1 + \frac{1-p}{2} \delta_{-1} + \frac{1}{2} \delta_{p - \frac{1}{2}}$$
and $Q_{E[X \mid Y]}$ is the same with $p=1/2$.  In particular, for $p \ne 1/2$ the total variation distance between $P_{E[X \mid Y]}$ and $Q_{E[X \mid Y]}$ is always at least 1.
For the third question, as far as means, the "conditional" part is really irrelevant, so we can take $Y=0$ in all cases.  Fix $n$ and suppose that $P(X=n) = 1/n$, $P(X=0) = 1-1/n$, and $Q(X=0)=1$.  Then the total variation distance between $P_X$ and $Q_X$ (and likewise $P_{X,Y}, Q_{X,Y}$) is $2/n$, which goes to 0 as $n \to \infty$.  But under $P$, we have $E[X \mid Y] = E[X] = 1$ for any $n$, while under $Q$ it is 0.
The basic problem is that for any state space $E$, the total variation topology on the space $\mathcal{P}(E)$ of probability measures on $E$ is not able to detect the topology of $E$, but only its measurable structure.  So it cannot tell whether two points of $E$ are close together or far away, but only whether or not they are the same point.  This is why the weak topology is more useful for most purposes.


text:
Q: Python Command Program I am currently trying to make a program that will run commands. I want to have it so there is a list of commands and the program will take my input command, check to see if its in the list, and then run the command if it does. and if not I want it to print out Invalid Command.
    while 1 == 1:
    command = input("Daisy: ")
    commands = ['cmd', 'google']
    if command == 'cmd' or 'google':
        if command == 'cmd':
            os.system("start")
        elif command == 'google':
            webbrowser.open_new('google.ca')

this is currently what i have. I already made the list but youll notice in my if statement i want it to check to see if it equals cmd or google. I am going to have a lot more commands then this so in the nature of making things look pretty, i wanted to know if there was a way i could have the command check the list, run the command if its in the list, and if its not, print invalid command.

A: You can create a function per command, and store the name for command and function to be executed in a dictionary. Like this:
def open_google():
    webbrowser.open('google.ca')

commands = {'open_google': open_google}

while True:
    # Get input here
    if command in commands:
        commands[command]()

This way you only have to create new functions, and add them to the dictionary. The logic in the main loop remains the same.

A: I think the most versatile way would be using a dictionary and the exec funktion
commands = dict()
commands['google'] = "webbrowser.open_new(\"google.ca\")"
commands['cmd'] = "os.system(\"start\")"

if key in commands:
    exec(commands[key])

Can't test this right now but it should work

A: I did a similar program, a little console, to help me on the developments.
the solution is a if-elif-else statement because every command is different to the other. So:
 while 1 == 1:
    command = input("Daisy: ")
    if command == 'cmd':
        os.system("start")
    elif command == 'google':
        webbrowser.open_new('google.ca')
    elif command == 'new command':
        # put here a new command
    else:
        print('Invalid Command')

Array commands and the first if statement aren't necessary because now there is "else" that intercept all invalid commands.
if you want see my code there is a link:  DevUtils at line 38 i manage commands.


text:
Q: Position image on top of another html element I have the following:

here is the html code:

    Select Roles

        <select name="RolesSelect" id="dualSelectRoles1" multiple="multiple" size="10">
            <option value="2">Avaliable Roles</option>
        </select>

            «
            »

        <select name="select4" multiple="multiple" id="dualSelectRoles2" size="10">
            <option value="1">Users Roles</option>
        </select>

    <button class="submit radius2" type="submit">Save</button>

how can I position each image so that it is in the middle (and ontop) of the box?

A: You need to place a wrapper around the select & loader image, like this:
HTML

    <select name="select4" multiple="multiple" size="10">
        <option value="1">Users Roles</option>
    </select>

...and then absolutely position it inside the box, like this:
CSS
img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -8px; // half the loader width
    margin-top: -8px; // half the loader height
}

div, select {
    position: relative;
    width: 500px;
}

Fiddle

A: You can apply position:fixed; style.
Assign your image a class:

Now style it using CSS:
.loading{
    position: fixed;
    top: 100px;
    right: 500px;
}


text:
Q: Function of handsontable only when the page is loaded I have a function which locks my cells in handsontable but I want to lock them only when the page is loaded.
cells:function(row,col,prop){ //Fonctions pour bloquer les cellules
                    var cellProperties = {};

                    if ([0].indexOf(row) !== -1 && col >= 0)
                    {
                        cellProperties.readOnly = true;
                        cellProperties.renderer = firstRowRenderer;
                    }

                    if(([0].indexOf(col) == 0) && (data_itk_pro_update[row][0]) && flag==true) //Here is the function to block the first column
                    {
                        cellProperties.readOnly = true;
                    }

                    if(([1].indexOf(col) == 0) && (data_itk_pro_update[row][1]) && flag==true)
                    {
                        cellProperties.readOnly = true;
                    }

                    if (readOnlyCellsITKPROU[[row,col]]) {
                        cellProperties.readOnly = true;
                    }

                    return cellProperties;
                    },

When the user insert data in a new row, I don't want the new cells to be blocked. So I think about a condition like :

If the page is loading

But I don't know how to do. And I don't know the utility of prop.
Can someone help me please ?
EDIT : I tried several thing :
if (document.readyState === "complete")  {

..
 $(window).load(function () {

..
window.onload = function () {

..
if(window.onload){

EDIT2 :
The entire initialization of my element :
var container = document.getElementById('tab_itk_pro_modif');
            var hotITKPROU = new Handsontable(container, {
                data: data_itk_pro_update,
                minSpareRows: 1,
                fixedRowsTop : 1,
                rowHeaders: false,
                colHeaders: false,
                contextMenu: {
                    items: {
                        "remove_row": {
                              name: 'Supprimer la ligne',
                              disabled: function () {
                                return hotITKPROU.getSelected()[0] === 0
                              }
                         }
                    }
                },
                cells:function(row,col,prop){ //Fonctions pour bloquer les cellules

                    var cellProperties = {};

                    if ([0].indexOf(row) !== -1 && col >= 0)  //Pour bloquer la première ligne
                    {
                        cellProperties.readOnly = true;
                        cellProperties.renderer = firstRowRenderer;
                    }

                    if(([0].indexOf(col) == 0) && (data_itk_pro_update[row][0]) && flag==true)
                    {
                        cellProperties.readOnly = true;
                    }

                    if(([1].indexOf(col) == 0) && (data_itk_pro_update[row][1]) && flag==true)
                    {
                        cellProperties.readOnly = true;
                    }

                    if (readOnlyCellsITKPROU[[row,col]]) { //Pour bloquer les composants des id concaténés
                        cellProperties.readOnly = true;
                    }

                    return cellProperties;
                    },

A: This appears to be a very basic question in JavaScript. I suggest you googling "load event js", "Javascript executes after page load", etc.
Unless you are looking for a specific way of doing it in handsontable, in which case it probably has to do with their hooks. For more information, look it up in the documentation.

A: If what you want to do is change the cells definition after the page is loaded, you could always update it using
hotInstance.updateSettings({
    cells: newCells // where newCells is a new set of conditionals
})

You could trigger this inside
$(docuemnt).ready(function(){ // updateSettings });


text:
Q: Generating c++ classes without a precompiler One of our projects involves generating boilerplate code for classes.
For example, given a text file with multiple definitions like:
STRUCT Foo
{
    int i;
    float f;
    string s;
}

a Perl script will create a header file with multiple declarations like:
struct Type_Foo : BaseType
{
    int i;
    float f;
    string s;

    Generated_Foo();
    void clear();
    bool equals(Generated_Foo const&) const;
    string const* toTraceString() const;
    string const* toXmlString() const;
    string const* toJsonString() const;
    bool fromXmlString(char const*);
    bool fromJsonString(char const*);
};

and a corresponding cpp file with the implementations.
My question is:
Is it possible to achieve a similar result (modulo syntax differences) without the precompiler stage?
Thank you!

A: Boost.Preprocessor can do this, just by (ab)using the C/C++ preprocessor.  It could look something like this.
#include <boost/preprocessor/seq/for_each.hpp>

#define STRUCT_MEMBER(r, data, elem) elem;

#define STRUCT(structname, seq) \
    struct Type_ ## structname : BaseType { \
        BOOST_PP_SEQ_FOR_EACH(STRUCT_MEMBER, _, seq) \
        Generated_ ## structname(); \
        void clear(); \
        bool equals(Generated_Foo const&) const; \
        string const* toTraceString() const; \
        string const* toXmlString() const; \
        string const* toJsonString() const; \
        bool fromXmlString(char const*); \
        bool fromJsonString(char const*); \
    }

STRUCT(Foo, (int i)(float f)(string s));

Having worked with Boost.Preprocessor, my opinion is that, although it's very cool and can be useful to do everything within C++, it can quickly get complicated for nontrivial uses.  If you already have a good, working external code generator (like your Perl scripts), there's nothing wrong with continuing to use it.


text:
Q: How can I capture the URL which a user first visits in my Angular application I am trying to capture the url that a user of my website first visits and use the query params for analytics purposes.
I have an Auth guard set up which protects some routes and redirects users to the /login route.
In my app-component.ts, I have the following code
  ngOnInit() {

    this.route.queryParams
      .subscribe((params) => {
        if (params.myparam) {
          // do stuff here with myparam
        }
      });

  }

If a user were to visit the url http://localhost:4200/someurl which is protected by my guard, how can I evaluate the url before the guard has ran, to capture the url. I have added the code above in the ngOnInit of my app-component.ts file however this only executes after the guard has finished, by this point it has redirected me to the login screen, and now from my analytics point of view, it looks like the user landed on the login screen rather than the page 'someurl'


text:
Q: Enable display_errors in .htaccess using `php-fpm` execution mode? When PHP is executing in cgi or mod_php mode, we can disable error reporting in php.ini and enable it on a per-directory basis using a .htaccess file in any directory we want.
php_flag display_startup_errors 1
php_flag display_errors 1
php_flag html_errors 1
php_value error_reporting -1

Doing it in the php script script itself is useless because it breaks on php parse errors which are very common.
How can I do the same thing when running php-fpm execution mode? Is it possible?

A: When using fpm PHP scans for a ini file in each directory
http://php.net/manual/en/configuration.file.per-user.php
Default is .user.ini
You should be able to put the same config in there but with the same syntax as php.ini:
display_errors = On
display_startup_errors = On
html_errors = 1
error_reporting = -1


text:
Q: SQL Server stored procedure to insert with check from multiple tables I have 2 tables
Table 1
userid int
username varchar(25)
password varchar(25)
siteid int (foreign key)

Table 2
siteid int
siteurl varchar(200)

I want to fire an insert with a stored procedure
I am getting username, password and siteurl as parameters.
Now when I want to insert the data, I need to check conditions

*

*no duplicate usernames allowed per siteurl

*if username exists and site url also matches then it should not allow to insert

*if username exists but different siteurl then it will allow to insert

At present I am fetching first site id and then passing site id as param, but this means traffic between site and database will be double.
But if same happens with single stored procedure then there will be difference

A: Are you looking for something like this?
CREATE PROCEDURE addnewuser
  @username VARCHAR(25),
  @password VARCHAR(25),
  @siteurl  VARCHAR(200)
AS
SET NOCOUNT ON;
IF NOT EXISTS(SELECT *
                FROM userlogin u JOIN sites s
                  ON u.siteid = s.siteid
               WHERE u.username = @username
                 AND s.siteurl = @siteurl)
BEGIN
  INSERT INTO sites (siteurl)
    VALUES (@siteurl);
  INSERT INTO userlogin (username, password, siteid)
    VALUES (@username, @password, SCOPE_IDENTITY());
END
ELSE
  RAISERROR ('User already exists', 16, 1);
GO

Here is SQLFiddle demo. Uncomment last EXEC and click Build Schema to see that it won't let you insert the same user again


text:
Q: Замена текста с копированием PHP Подскажите пожалуйста можно ли сделать такое - есть например текст со строками:
aaaa 11111 bbbb
aaaa 22222 bbbb
aaaa 33333 bbbb
aaaa 44444 bbbb
aaaa 55555 bbbb
нужно чтобы получилось так:
aaaa 11111 (11111) bbbb
aaaa 22222 (22222) bbbb
aaaa 33333 (33333) bbbb
aaaa 44444 (44444) bbbb
aaaa 55555 (55555) bbbb
Чтобы часть значения каждой строки как бы копировалось рядом с добавлением символов - скобок. Как сделать такое?

A: Для поиска с подстановкой используются подмаски (теги <pre> добавлены для визуального форматирования, их можно удалить):
$str = 'aaaa 11111 bbbb
aaaa 22222 bbbb
aaaa 33333 bbbb
aaaa 44444 bbbb
aaaa 55555 bbbb';

echo '<pre>';
echo preg_replace('~\d+~', '$0 ($0)', $str);
echo '</pre>';

Результат:
aaaa 11111 (11111) bbbb
aaaa 22222 (22222) bbbb
aaaa 33333 (33333) bbbb
aaaa 44444 (44444) bbbb
aaaa 55555 (55555) bbbb


text:
Q: Prove which application is used for opening log files: assoc and ftype seem unreliable on Windows-10 My customer has a problem with logfiles, which become too large: on their PC (windows-Server 2016) Notepad.exe is used as the application for opening such files. I've altered this to Notepad++.exe, solving the issue.
Now I would like to inform them about this, using simple commandlines for supporting what I did. So, as I have the same settings on my computer (Windows-10), I decided to use assoc and ftype for this. To my surprise, this is what I get (on my Windows-10 computer):
Prompt>C:\Users\DDM>assoc | findstr /I "log"
...
.log=txtfile
...

Prompt>ftype | findstr /I "txtfile"
txtfile=%SystemRoot%\system32\NOTEPAD.EXE %1

Although my computer uses Notepad++ for opening such files (just like the customer's PC) => to the command's result seems to be wrong!
Which commandline commands can I use for proving to the customer that Notepad.exe has been replaced by Notepad++.exe for opening "*.log" files?
Thanks
Edit
I just realised that I only modified the file extension association for my own user, not for all users, while assoc/ftype gives that association for the entire PC. So my question becomes, does such a command exist per user?

A: I've just found following registry entry:
Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\...
...\CurrentVersion\Explorer\FileExts\.log\UserChoice

(split over two lines for readability reasons, the correct syntax contains Windows\CurrentVersion)
So this would mean that, in order to show the file association for the current user, I can use this commandline command:
Prompt>reg query "HKCU\SOFTWARE\Microsoft\Windows\...
...\CurrentVersion\Explorer\FileExts\.log\UserChoice"

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\...
...\CurrentVersion\Explorer\FileExts\.log\UserChoice
    ProgId    REG_SZ    Applications\notepad++.exe
    Hash      REG_SZ    d0CsAhT8BLU=

Can anybody confirm this is correct?


text:
Q: Calling Php Variables to use it in Python Script So I'm trying to figure out if i can get the variables that i make in Php file and use it in my Python file.
I've read that you can use this.
Php file:
$data='12';
$output=shell_exec("python pythonfile.py $data");
echo $output;

Python file:
import sys
print sys.argv[1]

And if i run the Php it will display 12
But what i want is to run it in Python, it's like I'll call $data in python and manipulate it like make it float number. Is this possible?

A: You should call your PHP script from your Python script, you can use subprocess module, and many other ways
import subprocess

subprocess.call("php /path/to/your/script.php")

Here have good example, and many others have in Google.

A: A common and easy way to share data accross multiple process using different languages is to use sharable system resources. By exemple you could serialize data in a file and read the file from the other process. You can also use networks via sockets but it is more complicated.


text:
Q: javascript error during loading of latitude and longitude I'm trying to load latitude and longitude value using this code but I receive back this error:
Uncaught ReferenceError: position is not defined
(anonymous function)

here is the code I used in the head of html:
 <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">

    $(document).ready(function(){
        get_location();
    });

    function get_location()
    {
        if(navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(function(position){

                    var latitude = position.coords.latitude;
                    var longitude = position.coords.longitude;

            });
        }
    }

    console.log(position.coords);
</script>

I forgot something ?

A: navigator.geolocation.getCurrentPosition(function(){...}

must be
navigator.geolocation.getCurrentPosition(function(position){...}

You can add callback errorHandle to get errorCode
More info http://dev.w3.org/geo/api/spec-source.html#geolocation


text:
Q: Autoloading a particular driver, based on a detected specific kernel I need  to write a script and determining its placement within Debian 7.9 filesystem. The script needs to be executed automatically on startup and, after checking what kernel is currently loaded (2.6.x vs. 3.2.x), unload the incorrect network driver, if loaded, and load the correct one. This question is the follow-up for my prior question and represents the only missing piece of that puzzle, as I've already figured out cross-kernel compiling of network driver by myself.
In terms of the location, I think that the script should be placed into "/etc/rcX.d" directories.

A: The location you guessed is nearly correct. But /etc/rcX.d directories usually contain only links to scripts in /etc/init.d/, so that a script only has to exist once but can be called at different runlevels.


text:
Q: Delphi REST and No mapping for the Unicode character exists I am trying to get PDF from via API but when in command restrequest.Execute happens then program crashes with error: No mapping for the Unicode character exists in the target multi-byte code page.
Does anybody have any idea what is wrong it?
Here is my code:
 RESTClientx := TRESTClient.Create(nil);
 restclientx.AcceptCharset  := 'uft-8, *;q=0.8';
 restclientx.ContentType    := 'application/x-www-form-urlencoded';
 restclientx.FallbackCharsetEncoding := 'raw';
 restclientx.BaseURL := 'https://ee.integration.dpd.eo.pl/ws-mapper-rest/parcelPrint_';

 RESTResponsex := TRESTResponse.Create(nil);
 RESTRequestx:= TRESTRequest.Create(nil);

 restrequestx.Client   := RESTClientx;

 RESTRequestx.Method   := rmpost;
 RESTRequestx.Params.Clear;
 RESTRequestx.ClearBody;

 RESTRequestx.Params.AddItem;
 RESTRequestx.Params.Items[0].Kind := pkHTTPHEADER;
 RESTRequestx.Params.Items[0].name := 'username';
 RESTRequestx.Params.Items[0].Value := 'xxxxxxx';
 RESTRequestx.Params.Items[0].Options := [poDoNotEncode];

 RESTRequestx.Params.AddItem;
 RESTRequestx.Params.Items[1].Kind := pkHTTPHEADER;
 RESTRequestx.Params.Items[1].name := 'password';
 RESTRequestx.Params.Items[1].Value := 'xxxxxxxx';
 RESTRequestx.Params.Items[1].Options := [poDoNotEncode];

 RESTRequestx.Params.AddItem;
 RESTRequestx.Params.Items[2].Kind := pkHTTPHEADER;
 RESTRequestx.Params.Items[2].name := 'parcels';
 RESTRequestx.Params.Items[2].Value := '01234567890';
 RESTRequestx.Params.Items[2].Options := [poDoNotEncode];

 RESTRequestx.Params.AddItem;
 RESTRequestx.Params.Items[3].Kind := pkHTTPHEADER;
 RESTRequestx.Params.Items[3].name := 'printType';
 RESTRequestx.Params.Items[3].Value := 'pdf';
 RESTRequestx.Params.Items[3].Options := [poDoNotEncode];

 restrequestx.Execute; <- this will cause error

.