text:
Q: Motional Emf and Faraday's Law
How can there be an induced emf? According to Faraday's Law change in the magnetic flux produces an induced emf but B (magnetic field), A (area) and the angle between them (area vector and the magnetic field) is constant then how come there is an induced emf?
Please help me with this. I am already so confused in electromagnetism. Consider like I don't know nothing about motional emf and faraday's law and then answer the question because I know that I've developed so many misconceptions.

A: This should have been explained in the course or a textbook that gave you the exercise. You have found a well-known example where the standard formulation of Faraday's law using flux through a loop isn't directly applicable - a motional EMF for a path with open endpoints. Motional EMF for any open path in a conductive body is not due to induced electric field, but due to motion in magnetic field(magnetic force pushes on charge carriers, they push on the conductor and the conductor pushes back on the carriers, giving them energy for current and thus slowing down its motion).
This is not described by standard Faraday's law for loops, as you correctly observe, because for any stationary loop, magnetic flux is constant and induced emf for such stationary circuit is zero (as it should be, since there is no induced electric field).
The question is asking about motional emf for a path $\gamma$ joining point A to point B, which is a little different thing than the induced emf in a loop that Faraday's law talks about.
We can find it however from definition of this motional EMF: it was found that this is simply integral of magnetic force per unit charge along the given path from A to B:
$$
emf_{\gamma} = \int_{\gamma} \mathbf v \times \mathbf B \cdot d\mathbf s~~(*)
$$
where $\mathbf v$ is velocity vector of the conductor (not that of charge carriers!). You have to take this as independent law for motional EMF at this point, there is a way to derive it from other knowledge but it gets tricky.
There is a way to formulate Faraday's law for moving closed paths and then apply this to the situation in the exercise (when the path is completed outside the wheel into a closed loop). But this is a little confusing if you do not know about (*) and when you know about it, it is pointless complication.
If your book did not explain this, get a better book (Feynman's lectures and some older american, british and german textbooks are nice).
So for your example of rotating disk, the vector product $\mathbf v \times \mathbf B $ on all points of the path $\gamma$ points in radial direction away from the center, so dot product with $d\mathbf s$ is trivial. We get the integral
$$
emf_\gamma = \int_0^{R} \omega r B dr = \omega B \frac{R^2}{2}.
$$


text:
Q: 'Bad Request' when inner class instance from Apex to LWC I'm working on a Lightning Web Component which calls an API from Apex and display the response in the component with the help of a wrapper class.
The response is displaying correctly in the apex method. But once it is returned to the LWC's JavaScript method, it throws the following error:-
"{"ok":false,"status":400,"statusText":"Bad Request","body":{}}"

LWC
myMethod(event) {
    myMethod({ accountId: this.recordId, name: event.detail.value })
    .then((result) => {
        console.log(result); // NEVER EXECUTED
    })
    .catch((error) => {
        console.log('error = ' + JSON.stringify(error)); // EXECUTED
    });
}

Apex
@AuraEnabled
public static Api.ResultWrapper myMethod(Id accountId, String name) {
    Api.ResultWrapper  result = doThing(accountId, name);
    System.debug('result = ' + result); // CORRECT RESULT
    return result;
}

Api.ResultWrapper
public with sharing class Api {

    // INNER

    public class ResultWrapper {
        private String hiddenProperty;
        private Map<String, String> attributes;

        @AuraEnabled
        public String getProperty() {
            return hiddenProperty;
        }

        @AuraEnabled
        public String getAccountName() {
            return attributes.get('name');
        }

    }
}

It works fine when I serialize the response in apex and return it as a JSON string to the javascript.
I would like to know if there is a better solution for this issue other than the serialization workaround.

A: You need to annotate @AuraEnabled the properties of wrapper class
@AuraEnabled
public static Api.ResultWrapper myMethod(Id accountId, String name) {

Here you are returning Api.ResultWrapper, meaning this is the data type that you want to read in javascript(lightning). If the properties of this data type are not Aura Enabled, it cannot be sent in the response. If you were using getProperty or getAccountName method and returning String, you will get it BUT if you want to return wrapper, you need aura enabled properties in that wrapper class and properties need to be public or global
public class ResultWrapper {
    @AuraEnabled private String hiddenProperty;
    @AuraEnabled private Map<String, String> attributes;

Also, you are getting "{"ok":false,"status":400,"statusText":"Bad Request","body":{}}" because you are using attributes.get('name') but actually not setting proper attributes value before returning. Remove method getAccountName or pass proper value (through ResultWrapper constructor) to attributes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add a line of code in multiples python files I have to add from constants import MY_CONSTANT to 100 python files.
Is there a simple and efficient way to do it?

A: You can just treat python files like any other text files and write to them. Assuming they are all in the same folder (if not just adapt the loop to go through the relevant folders):
for file in os.listdir(folderpath):
    if file.endswith('.py'):
        with open(file,'r+') as f:
            content = f.read()
            f.seek(0, 0)
            f.write('from constants import MY_CONSTANT' + '\n' + content)


text:
Q: Qgis problem clipping a raster .asc file, the output is unreadable I am currently using QGIS (1.8.0) to prepare files for use in MaxEnt to predict species distribution in a new territory in Argentina. I need to
a) cut the raster files (bioclim, and others) to a single province, and
b) create a .asc file from a .shp file (not sure if this is possible in QGIS)
My problem is with point 'a'. I have read the various questions on this site regarding raster clipping which were very useful. I have set the CRS for each file (WGS84 EPSG4326), and the Raster/Extractions/Clipper tool using a mask does create a file.
However, when I open this file using TextPad (with which I can view the original larger file) the text is in an unknown language/script and does not open in MaxEnt.
I was worried the problem my lay in the fact that my .shp mask did not fully fall within my original raster, so I tried clipping by extent, so I clipped only within the extent of the raster, but got the same results.
Has anyone any suggestions as to what might be the problem?

A: Clipping of raster files only works when the raster file has the same CRS as the vector file. The clipping is not done within Qgis, but with gdal. So it is not helful to set the CRS within Qgis, but you have to transform your asc file to a geotiff file, which has the CRS information stored within the file.
So first step is Raster -> Projections -> Warp, set the desired CRS and save as Geotiff, then do the clipping on the Geotiff file.
If you can not handle Geotiff files with your application,  you can reconvert the file again after clipping with Raster -> Convert -> Translate.


text:
Q: scikit learn: train_test_split, can I ensure same splits on different datasets I understand that the train_test_split method splits a dataset into random train and test subsets. And using random_state=int can ensure we have the same splits on this dataset for each time the method is called.
My problem is slightly different.
I have two datasets, A and B, they contain identical sets of examples and the order of these examples appear in each dataset is also identical. But they key difference is that exmaples in each dataset uses a different sets of features.
I would like to test to see if the features used in A leads to better performance than features used in B. So I would like to ensure that when I call train_test_split on A and B, I can get the same splits on both datasets so that the comparison is meaningful.
Is this possible? Do I simply need to ensure the random_state in both method calls for both datasets are the same?
Thanks

A: Looking at the code for the train_test_split function, it sets the random seed inside the function at every call. So it will result in the same split every time. We can check that this works pretty simply
X1 = np.random.random((200, 5))
X2 = np.random.random((200, 5))
y = np.arange(200)

X1_train, X1_test, y1_train, y1_test = model_selection.train_test_split(X1, y,
                                                                        test_size=0.1,
                                                                        random_state=42)
X2_train, X2_test, y2_train, y2_test = model_selection.train_test_split(X1, y,
                                                                        test_size=0.1,
                                                                        random_state=42)

print np.all(y1_train == y2_train)
print np.all(y1_test == y2_test)

Which outputs:
True
True

Which is good! Another way of doing this problem is to create one training and test split on all your features and then split your features up before training. However if you're in a weird situation where you need to do both at once (sometimes with similarity matrices you don't want test features in your training set), then you can use the StratifiedShuffleSplit function to return the indices of the data that belongs to each set. For example:
n_splits = 1
sss = model_selection.StratifiedShuffleSplit(n_splits=n_splits,
                                             test_size=0.1,
                                             random_state=42)
train_idx, test_idx = list(sss.split(X, y))[0]

A: Since sklearn.model_selection.train_test_split(*arrays, **options) accepts a variable number of arguments, you can just do like this:
A_train, A_test, B_train, B_test, _, _ =  train_test_split(A, B, y,
                                                           test_size=0.33,
                                                           random_state=42)

A: Yes, random state is enough.
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X2 = np.hstack((X,X))
>>> X_train, X_test, _, _ = train_test_split(X,y, test_size=0.33, random_state=42)
>>> X_train2, X_test2, _, _ = train_test_split(X2,y, test_size=0.33, random_state=42)
>>> X_train
array([[4, 5],
       [0, 1],
       [6, 7]])
>>> X_train2
array([[4, 5, 4, 5],
       [0, 1, 0, 1],
       [6, 7, 6, 7]])
>>> X_test
array([[2, 3],
       [8, 9]])
>>> X_test2
array([[2, 3, 2, 3],
       [8, 9, 8, 9]])

A: As mentioned above you can use Random state parameter.
But if you want to globally generate the same results means setting the random state for all future calls u can use.
np.random.seed('Any random number ')


text:
Q: Using sql lite database in another android app hello i have a problem with android. In my app i get data from a webservice  and i read it into a sql lite database . In my activity i have multiple spinners who are filled with data from the DB. After selecting all the spinners and clicking the button i go to an other activty where i click a link and the data is written into another table.
I will explain what the  app is like a form where a student can choose with school , study area,.. till you have the tuition you want. You can subscribe than for the course(that data is written to another table).
In the other app you can see the tuition whit the number of subscribers.
the first app works but my problem is that i need the table of subscibers used in app 1 for app2
i have read about COntent providers ,shared user id but none of it works.
Can somebody help me?
 public class SchemaHelper extends SQLiteOpenHelper {
    private final static String DATABASE_NAAM ="av_helpdesk.be.db";
    private static final int DATABASE_VERSIE = 10;

public SchemaHelper(Context context) {
    super(context, DATABASE_NAAM, null, DATABASE_VERSIE);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "
            + GegevensTabel.TABEL_NAAM
            + " (" + GegevensTabel.ID
            + " INTEGER PRIMARY KEY,"
                    + GegevensTabel.INSTELLING
            + " TEXT,"

            + GegevensTabel.OPLEIDINGSTYPE
            + " TEXT,"
            + GegevensTabel.OPLEIDINGSGEBIED
            + " TEXT,"+ GegevensTabel.OPLEIDING+" TEXT,"
           + GegevensTabel.MODULE+" TEXT,"
           +  GegevensTabel.LESPLAATS_ADRES+" TEXT,"
            + GegevensTabel.AAVANGS_DATUM+" TEXT"+");"
    );

    db.execSQL("CREATE TABLE "
            + InschrijvingTabel.TABEL_NAAM
            + " (" + InschrijvingTabel.ID
            + " INTEGER PRIMARY KEY,"
            + InschrijvingTabel.LESPLAATS
            + " TEXT, "
            + InschrijvingTabel.OPLEIDING
            + " TEXT, "
            + InschrijvingTabel.Module
            + " TEXT, "+ InschrijvingTabel.AANTAL+" INTEGER"+");"

    );

}

 public interface InschrijvingTabel {

    String ID="_id";
    String Module = "_module";
    String TABEL_NAAM = "TBL_INSCHRIJVING1";
    String AANTAL="_aantal";
    String OPLEIDING="_opleiding";
    String LESPLAATS="_lesplaats";
}

    public class InschrijvingDB extends  SchemaHelper {
    public InschrijvingDB(Context context) {
        super(context);

    }

    public void  adVakken()
    {

        SQLiteDatabase sd=getWritableDatabase();
      //  String xx=x.getModule();
    // sd.rawQuery("insert into "+InschrijvingTabel.TABEL_NAAM+"("+ InschrijvingTabel.Module+") values("+xx+")",null);
   //  sd.rawQuery("insert into "+InschrijvingTabel.TABEL_NAAM+"(_module) values('cc')",null);

    }

public class contentPV extends ContentProvider {
    static final String PROVIDER_NAME = "com.example.derae.lessenrooster.databank.contentPV";
    static final String URL = "content://" + PROVIDER_NAME + "/*";
    static final Uri CONTENT_URI = Uri.parse(URL);
    @Override
    public boolean onCreate() {
        Context context = getContext();
InschrijvingDB x= new InschrijvingDB(context);
    return false;
}

@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    return null;
}

@Nullable
@Override
public String getType(Uri uri) {
    return null;
}

@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
    return null;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    return 0;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    return 0;
}

}

A: If you're using 1 database that has all the tables you want to use and you're logging in to that database from app 2, then you should be able to access every table there.
Try debugging techniques to see what's going wrong with app 2, like print debugging.
If you can connect to your database normally from app2, then check if there's anything wrong with your Queries to get data from the desired table. Break your problem down into parts.
-I'm sorry if this is not helpful enough, I'm no expert myself, but I hope my tips help you discover the problem yourself.


text:
Q: Why do we use nichrome if heat is inversely proportional to resistance at constant voltage? Why do we use nichrome in heating appliances? I've been listening that it offers higher resistance and hence, should generate more heat; as governed by $H=i^2Rt$. But, shouldn't we be using heating appliances at constant potential difference (like 220V or whatever the mains voltage is in your region) rather than constant current? Shouldn't we be applying $H=V^2/Rt$ instead?
If so, then what is the real reason of using nichrome wires? I've been searching about this for a while and couldn't find anything satisfactory. What am I missing?


text:
Q: Don't move project outside workspace while creating a EGit repo in Eclipse I am working on a project which I want keep in my workspace.
Also I want to create a repo from this project using EGit.
It's a normal behavior of EGit that it moves my files to GitRepos directory while creating a repo.
I want to know if there is any way through which I can keep my project files inside Workspace and also keep a copy these files into GitRepos folder so that each time do changes/commit into GitRepos folder.
Because I want to separate my development environment with Production/Live environment as as I am using this GitRepo as my default live code on server.


text:
Q: androidTest with external mocked ContentProvider My application combines 3 ContentProvider data sources into one UI.
I want to be sure everything is laid out correctly, hence I am trying to provide mock content providers with predefined data (and later take screenshots of that, but that's step 2).
The project structure is:
/app
/app/homeapp
/app/sourceapp

My main activity is in /app/homeapp and reads data from /app/sourceapp via a ContentProvider. It also reads some data from its own ContentProvider.
I want to be in control of the data during the test. A sample test looks like this:
@RunWith(AndroidJUnit4.class)
@MediumTest
public class MainAppActivityTest {
    @Rule
    public ActivityTestRule<MusicHomeActivity_> activityRule = new ActivityTestRule<>(MusicHomeActivity_.class);

    @Test
    public void testDataDisplayed() throws Exception {
        // Check view in target.
        // Ensure items are displayed properly.
        // Take screenshot, compare.
    }
}

(It is based on the new AndroidJUnit4 class).
Within src/androidTest/AndroidManifest.xml I'm actually able to create a new stubbed ContentProvider like this:
<manifest
    package="com.company.app"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <application>

        <provider
            android:name="com.company.app.DataContentProviderStubbed"
            android:authorities="com.company.app.data.stubbed"
            android:exported="true"/>

    </application>
</manifest>

Now my key problem is how to set that DataContentProviderStubbed as default provider.
I can not override the authority or give it an higher priority, the system will refuse this (only one ContentProvider can exist for a given authority).
For reference, I'm trying inject it into a Fragment which uses LoaderManager:
// onViewCreated
getLoaderManager().restartLoader(LOADER_DEVICES, null, new LoaderManager.LoaderCallbacks<Cursor>() {
    @Override
    public Loader<Cursor> onCreateLoader(final int id, final Bundle args) {
        return new CursorLoader(context, CONTENT_URI, PROJECTION,
                DataContentDescriptor.Device.DEVICE_TYPE + " = ? AND " + DataContentDescriptor.Device.UDN + " != ?",
                new String[]{TYPE_SERVER, myUdn}, null);
    }

    @Override
    public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
        deviceAdapter.setDevicesCursor(data);
    }

    @Override
    public void onLoaderReset(final Loader<Cursor> loader) {
        deviceAdapter.setDevicesCursor(null);
    }
});

Some thinking so far:

*

*Control how the activity is instantiated and configure it with a public static flag to control the field. Please no, very hard to maintain.

*Within the activity, find a way to implement "isRunningInAndroidTest()" and choose a different ContentProvider authority. Better, but still a maintenance nightmare.

*Bytecode manipulation, but not sure this is even in the cards as the com.company.app is running from another APK.

*Make selection of the content provider URL part of the App design and hide it behind a ContentProviderUrlProvider (;-)) class - but this class still needs to make decisions based on the first 2 points. Frankly speaking I don't want to change SW design solely because of testing issues.

Which way could work to ensure the stubbed ContentProvider is used?

A: As you noted, you need different authority strings for the providers. Therefore, you need your client-side code to seamlessly use the right authority string for your build (main versus androidTest).
If your authority string is derived from the application ID, then you can synthesize the right authority string to use in your code from BuildConfig.APPLICATION_ID.
If your authority strings are not readily generated from the APPLICATION_ID, you can try to add your own buildConfigField or resValue to define them in build.gradle, so you can reference them in your Java.
If you want to minimize code duplication, you can use manifest placeholders to define the authority strings in the manifest from values in Gradle. You can then use a common source of knowledge (e.g., gradle.properties) to populate both the manifest placeholder and the buildConfigField/resValue.
Now, the catch for the above paragraph is that I know it works for product flavors. I have not tried it for androidTest, and so it's possible that you cannot set up a different buildConfigField and such for androidTest.


text:
Q: Find the matrix of the transformation with respect to the bases of V. Let the sets $Y = \{1, x, x^2\}$ and $X = \{1, 1 + x, 1 + x + x^2\}$ be bases of $V$.
Let $D: \ V \to V$ be defined such that $D(f)$ is the derivative of $f$, for any $f {\in}  V$. Find the matrix of $D$ with respect to the bases $Y$ and $X$.
I know the answer but I am not quite sure how to get there.
Answer:$$\begin{bmatrix} 0 & 1 & -2\\ 0 & 0 & 2\\ 0 & 0 & 0 \end{bmatrix}$$

A: We need to check how the linear transformation "acts" on the elements of $Y$, and then represent them with respect to $X$:
$D(1)=0=0\cdot 1+0\cdot (1+x)+0\cdot (1+x+x^2)$
$D(x)=1=1\cdot 1+0\cdot (1+x)+0\cdot (1+x+x^2)$
$D(x^2)=2x=-2\cdot 1+2\cdot (1+x)+0\cdot (1+x+x^2)$
Placing the coordinates in columns of a matrix and we get the result.

A: $D(x)=1$
Now  $a.1+b(1+x)+c(1+x+x^2)=1$
Implies that $a=1,b=0,c=0$
Also $D(x^2)= 2x$
Now $a.1+b(1+x)+c(1+x+x^2)=2x$
Implies $a+b+c=0,b+c=2,c=0$
Implies $a=-2,B=2,c=0$
Similarly for $D(1)$
Put them in columns nd get the required matrix


text:
Q: Response to MediaBttuon not working when Trying to play sound over BluetoothSco I have implemented  handling MediaButton event according to developers guide Both in UI Activity and Active Media Session. When I try to play sound over bluetoothSco it starts to miss MediaButton events. this are the lines of  code I added to play sound over BluetoothSCO
AudioManager localAudioManager;
            localAudioManager = (AudioManager) CallFrameGUIActivity.this.getSystemService(AUDIO_SERVICE);
            localAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            localAudioManager.setBluetoothScoOn(true);
            localAudioManager.startBluetoothSco();

A: Because you use mode_in_communication.
localAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION)


text:
Q: Inversion with of? Could the prepositional verb "of" be used with inversion?
As so:
" Of the apple there was nothing left, for the worm had found it's way inside and it could only be thrown away."
Is the emboldened part grammatical with regard to fronting prepositions?


text:
Q: Set of limit points of Riemann Integrable functions I've looked around for answers to this question. It seems like perhaps I don't have enough knowledge of functional analysis to figure out the answer (or even understand the answer), but I'm intrigued.
Consider the set of Riemann Integrable functions over a closed real interval [a,b]. I know that there exists a sequence of Riemann Integrable functions who's limit is not Riemann Integrable. However his begs the question, what is the set of limit points of Riemann Integrable functions?
The question arises from my essay on Daniell Integrals. First we define a lattice of real valued functions L such that
\begin{equation*}
(f \lor g)  := \max(f,g)
\end{equation*}
\begin{equation*}
(f \land g) := \min(f,g)
\end{equation*}
We then define the completion of a lattice $L$, denoted by by $L^{*}$, is defined to be the intersection of all sets $L'$ of real valued functions such that
\begin{equation*} L \subset L'
\end{equation*}
\begin{equation*}
f_{n} \in L', f_{n}\uparrow f \implies f \in L'
\end{equation*}
\begin{equation*}
g_{n} \in L', g_{n}\downarrow g \implies g \in L'
\end{equation*}
So essentially it is a larger lattice (I have proven it is a lattice) such that we have closure under monotone limits.


text:
Q: How can you mock a DOM window event? In my ng4 app, I have a service that exposes an Observable over the window focus event. How would you go about testing this (I am using Jasmine, but that's not very important)?
constructor(@Inject('Window') private window: Window) {

    this.window.onfocus = () => {
        this.onFocusSubject.next();
    };
}

// how can I test that the onFocus Observable is triggered
// when window.onfocus is fired?
public onFocus(): Observable<any> {
    return this.onFocusSubject.asObservable();
}

My approach is to mock the window object and to trigger fire the onfocus event, but am unsure of how to trigger the event...

A: Just mock the service using a BehaviorSubject and trigger a next call to ensure your listeners are invoked.
Like this:

const serviceStub = {
  windowEvent: new BehaviorSubject(null);
}

// in your test:

it('should trigger an event listener: ', () => {
  const service = componentInstance.injector.get(Service);
  service.windowEvent.next(new FocusEvent('focus'));
  // write your test logic here
})


text:
Q: How to set a new field with a referenced value from another collection In MongoDB, I have a document as the following:
{
    "_id": ObjectId("sdsfsdgsfdgfghdhg454"),
    "some_field": {
                      "$ref": "SomeOtherCollection",
                       "$id": ObjectId("asdfgeghhnjgfgf")
    }
}

The problem:
I need to create a new field that stores the String value of reference's "$id" field, like
{
    "_id": ObjectId("sdsfsdgsfdgfghdhg454"),
    "some_field": {
                      "$ref": "SomeOtherCollection",
                       "$id": ObjectId("asdfgeghhnjgfgf")
    },
    "new_field": "asdfgeghhnjgfgf"
}

Is there a way in MongoDB to do this? the version of MongoDB that I'm using is 3.6.20.
Thanks in advance for your help.
Regards.


text:
Q: Problem reading data from serial port in python I have a python program that is trying to read 14 bytes from a serial port that
are arriving very slowly.  I want want to capture all of the bytes in a
bytearray[14].  I understand there are new byte array features in python 3.0, but
I'm only running python 2.6.6.  Upgrading may have unexpected consequences so I have to
stick with 2.6.6.
Data only intermittently flows over the serial port. I get one message on the
port maybe every 2 minutes or so.  This data flows very slowly.  The problem I am seeing is
that my code does not relaibly read the data one byte at a time.   I want to frame this
data at exactly 14 bytes, then process the data and start fresh with a new 14
bytes.
Am I taking the wrong approach here? Advice?
    ser = serial.Serial('/dev/ttyUSB1', 1200, timeout=0)
    ser.open()
    print "connected to: " + ser.portstr
    count=0
    while True:
        line =ser.readline(size=14) # should block, not take anything less than 14 bytes
        if line:
            # Here I want to process 14 bytes worth of data and have
            # the data be consistent.
            print "line(" + str(count) + ")=" + line
            count=count+1
    ser.close()

Here's what I'm expecting: line(1)=� 0~ 888.ABC�    /ends in carriage return
----------begin output------
line(0)=0
line(1)=~ ??1. ABC �    # here get some multiple bytes and stuff gets out of synch

�ine(2)=
line(3)=0
line(4)=~
line(5)=
line(6)=8
line(7)=8
line(8)=8
line(9)=.
line(10)=
line(11)=A
line(12)=B
line(13)=C
line(14)=
line(15)=�
line(16)=

#...
line(48)=
line(49)=�
line(50)=0
line(51)=~
line(52)=
line(53)=8
line(54)=8
line(55)=8
line(56)=.
line(57)=
line(58)=A
line(59)=B
line(60)=C
line(61)=
line(62)=�
line(63)=

line(64)=

----------end output------

A: The API documentation for PySerial says readline() reads until \n, or until size is reached. However, the read() function says it will block until size is reached. Both of these functions say they will return early if a timeout is set.
Possible values for the parameter timeout:

timeout = None: wait forever
timeout = 0: non-blocking mode (return immediately on read)
timeout = x: set timeout to x seconds (float allowed)

Maybe try timeout=None instead of timeout=0

A: Try this:
ser = Serial('/dev/ttyUSB1', 1200, timeout=0)
print "connected to: " + ser.portstr
count=0
while True:
     for line in ser.readlines()
          print "line(" + str(count) + ")=" + line
          count=count+1

ser.close()

You might also be interested in the line.strip() function if you haven't used it. Also, emphasis on the s in ser.readlines(), different from .readline().

A: Change the baudrate.
ser = serial.Serial('/dev/ttyUSB1', 9600, timeout=0)

to a compatible baudrate.
For getting 14 byte data :
data = ser.read(size=14)


text:
Q: count banner impressions using java or javascript I want to count banner impressions in my web page. For Example I have a image slider and I need to count how many times each image displayed in my page, And each individual image count  should have to save in the database.
I want write this in java or javascript
Can anyone Help me please.
Thanks

A: How about
$(function(){
   $('img').load(function(){
        $.post('update.php', {img: $(this).attr("id")});
   });
});

And in update.php you will get a post request with $_POST['img'] = Image-Id. Use it to update the count record in your database with +1.
Keep in mind this will create a new request to update.php for each image that is loaded.
PS: You need jQuery.


text:
Q: Gradle tasks are not visible in new version of Android Studio I have a project made with Android Studio 3.0 with coworkers. There are so many Tasks for installing the application. After I finished updating the Android Studio from 3.0 to 3.3.2, almost tasks in project(root)>tasks are not visible. Checkout my gradle project below.
3.0 :
my-project
ㄴmy-project (root)
  ㄴTasks
    ㄴandroid
    ㄴbuild
    ㄴbuild setup
    ㄴhelp
    ㄴinstall
    ㄴother
    ㄴverification
ㄴmy-module-one
  ㄴTasks
    ㄴandroid
    ㄴbuild
    ㄴhelp
    ㄴinstall
    ㄴother
    ㄴverification
ㄴmy-module-two
...

3.3.2 :
my-project
ㄴmy-project (root)
  ㄴTasks
    ㄴbuild setup
    ㄴhelp
    ㄴother
ㄴmy-module-one
  ㄴTasks
    ㄴandroid
    ㄴbuild
    ㄴcleanup
    ㄴhelp
    ㄴinstall
    ㄴother
    ㄴverification
ㄴmy-module-two
...

I can check some tasks are not visible and suddenly the "cleanup" thing appears in every modules. How can i solve it and What's the reason of these problems.

A: Android Studio 4.2 has a new experimental feature for Gradle, which is Do not build Gradle task list during Gradle sync. Unfortunately, it comes checked (on) by default, and results in the Gradle task list not being visible in the Gradle view. This because the Gradle task list is not even being generated. However, it leaves many of us wondering what happened to the Gradle task list.
You can go to Settings (e.g., File -> Settings on windows, Preferences -> Settings on mac) and go to Experimental. There you can uncheck the new option.

Then just click on Sync Project with Gradle Files and the Gradle task list will be generated and visible again.

A: Accroding to this link
Behavior changes:

*

*Lazy task configuration: The plugin now uses Gradle's new task creation API to avoid initializing and configuring tasks that are not required to complete the current build (or tasks not on the execution task graph). For example, if you have multiple build variants, such as "release" and "debug" build variants, and you're building the "debug" version of your app, the plugin avoids initializing and configuring tasks for the "release" version of your app.
Calling certain older methods in the Variants API, such as variant.getJavaCompile(), might still force task configuration. To make sure that your build is optimized for lazy task configuration, invoke new methods that instead return a TaskProvider object, such as variant.getJavaCompileProvider().
If you execute custom build tasks, learn how to adapt to Gradle's new task-creation API.

A: Had the same problem: after import from GitHub there weren't any Gradle tasks in Android Studio. Spent hours on solving this issue but nothing helped. Only these steps solved problem in my case:

*

*In Android Studio go to File -> Settings... -> Experimental and uncheck the Do not build Gradle task list during Gradle build checkbox.

*Delete cloned project and clone it again (if some of required files like keystore properties are not present, add them and do File -> Invalidate Caches / Restart).


text:
Q: Showing that the difference of two variance matrices should be positive semi-definite... or not I am trying to prove a result: intuitively, the GMM estimator should have a larger variance under homoskedasticity than LS and vice versa under heteroskedasticity. We are working with various probability (VP) sampling with $b(X_i)$ being the probability of $i$th observation to be retained in the sample, so, in order to account for stratification, we do inverse probability weighting:
$
\mathbb{E}\frac{X(Y-X'\theta)}{b(X)} = 0
$
The asymptotic variances of the two estimators are the following:
$
\mathrm{asVar}(LS) = (\mathbb{E}XX')^{-1}(\mathbb{E}XX'\sigma^2(X))(\mathbb{E}XX')^{-1}
$
$
\mathrm{asVar}(GMM) = \left(\mathbb{E}\frac{XX'}{b(X)}\right)^{-1}
\left(\mathbb{E}\frac{XX'\sigma^2(X)}{b^2(X)}\right)
\left(\mathbb{E}\frac{XX'}{b(X)}\right)^{-1}
$
I have run multiple simulations with various parameters, and since we are working in heteroskedastic conditions, it seems that the variance of the GMM estimator should beat that of the LS one, but (1) in the simulations, the variance of GMM estimator remained larger even under heteroskedasticity, and (2) so far I could not prove that any ranking should exist. This is the idea of the proof.
Let $\Omega = \mathbb{E}XX'\frac{\sigma^2(X)}{b^2(X)} -
\left(\mathbb{E}\frac{XX'}{b(X)}\right)
(\mathbb{E}XX')^{-1}(\mathbb{E}XX'\sigma^2(X))(\mathbb{E}XX')^{-1} \left(\mathbb{E}\frac{XX'}{b(X)}\right)$. Then
$
\mathrm{asVar}(GMM) - \mathrm{asVar}(LS) = \left(\mathbb{E}\frac{XX'}{b(X)}\right)^{-1} \Omega \left(\mathbb{E}\frac{XX'}{b(X)}\right)^{-1},
$
so we focus our attention on $\Omega$. It can be decomposed into a sum of two matrices.
Let $a_1 = X \frac{\sigma(X)}{b(X)}$ and $a_2 = (EXX')^{-1} \frac{X}{\sigma(X)}$. Then $\mathbb{E} a_1 a_1' = \mathbb{E} XX' \frac{\sigma^2(X)}{b^2(X)}$, $\mathbb{E} a_1 a_2' = \mathbb{E} \frac{XX'}{b(X)} (\mathbb{E}XX')^{-1}$ and $\mathbb{E} a_2 a_2' = (\mathbb{E}XX')^{-1} \mathbb{E}\frac{XX'}{\sigma^2(X)} (\mathbb{E}XX')^{-1}$.
Now we can simplify $\Omega$:
$
\Omega = \mathbb{E} a_1 a_1' - \mathbb{E} a_1 a_2' \ [\mathbb{E}XX' \sigma^2(X) ]\ \mathbb{E} a_2 a_1'
$
Let us subtract and add $(\mathbb{E} a_2 a_2')^{-1}$ to the term in brackets:
$
\Omega = \mathbb{E} a_1 a_1' - \mathbb{E} a_1 a_2' \ [\mathbb{E}XX' \sigma^2(X) - (\mathbb{E} a_2 a_2')^{-1} + (\mathbb{E} a_2 a_2')^{-1}]\ \mathbb{E} a_2 a_1'
$
And now we expand:
$
\Omega = \underbrace{\mathbb{E} a_1 a_1' - \mathbb{E} a_1 a_2' \ (\mathbb{E} a_2 a_2')^{-1} \ \mathbb{E} a_2 a_1'}_A +
\underbrace{\mathbb{E} a_1 a_2' \ [(\mathbb{E} a_2 a_2')^{-1} - \mathbb{E}XX' \sigma^2(X)] \ \mathbb{E} a_2 a_1'}_B
$
So basically $\Omega = A + B$. We can show that $A$ is positive semi-definite.
Matrix analogue of Cauchy-Schwarz inequality. If $g$ and $h$ are random vectors of the same length, then
$
(\mathbb{E} gh') (\mathbb{E}hh')^{-1}(\mathbb{E} hg') \leq \mathbb{E} gg'
$
in the sense that their difference is a positive semi-definite matrix.
Using the matrix analogue of the Cauchy-Schwarz inequality, we can see that $\mathbb{E} a_1 a_1' - \mathbb{E} a_1 a_2' \ (\mathbb{E} a_2 a_2')^{-1} \ \mathbb{E} a_2 a_1'$ is positive semi-definite.
Now for $B$. Again, we are interested in the "meat" of the sandwich, namely $(\mathbb{E} a_2 a_2')^{-1} - \mathbb{E}XX' \sigma^2(X)$. In this case, by the very same inequality, this matrix is negative semi-definite: consider $g=X\sigma(X)$, $h=\frac{X}{\sigma(X)}$, so
$
(\mathbb{E} gh') (\mathbb{E}hh')^{-1}(\mathbb{E} hg') = (\mathbb{E} XX') \left(\mathbb{E} \frac{XX'}{\sigma^2(X)}\right)^{-1} (\mathbb{E} XX') \le \mathbb{E}XX' \sigma^2(X) = \mathbb{E} gg'.
$
In case of homoskedasticity, $\sigma^2(X) \equiv \sigma^2$, to the latter inequality turns into equality because then,
$
(\mathbb{E} XX') \left(\mathbb{E} \frac{XX'}{\sigma^2}\right)^{-1} (\mathbb{E} XX') \equiv \mathbb{E}XX' \sigma^2
$, so $\Omega=A$ under homoskedasticity. However, it seems logical that at some point in time, under, $B$ should outweigh $A$ and make $\Omega$ NSD... or not?
And there we have it. $\Omega$ turns out to be a sum of a PSD and a NSD matrix. So adding and subtracting $(\mathbb{E}a_2 a_2')^{-1}$ was a convenient but a useless trick.
Question. Is it possible to show that $\Omega$ is positive semi-definite at all? Or is there a counterexample showing the contrary?

A: Indeed, no such ranking exists. I ran another simulation in a very simplified case (two-point distribution of $X$, two values of $\sigma^2(X)$, two different probabilities of being retained) and, depending on the probabilities, the inequality sign flipped.


text:
Q: Frequency algorithm of element inside array in time O(n) I wanted to ask if there is an algorithm that can find, in an array of length n, if there is an array element with a certain frequency percentage (10%, 20% etc...) in linear time.
Selection sort is O(n^2) and the majority algorithm even if O(n) can only find if the number is repeated at least n/2 times.

A: You are making this out to be a lot harder than it really is, assuming you don't have space limits.
The idea is to iterate the array and save the count of each element while doing so. Dictionary (or equivalent structure) lookup is O(1) so it's not a problem.
Then just iterate over the dictionary and see what elements have the required frequency.
Python pseudocode:
for elem in array:
    count[elem] = count.get(elem, 0) + 1
for elem, elem_count in count.items():
    if 0.20 <= float(elem_count) / len(array) <= 0.25:
        print "{} has a frequency between 20% and 25%".format(elem)

A: int counter = 0; (no influence on run time in this code line).
Iterate the arry using loop (for,while,whatever). For each element:
  - if(element == what_you_search)
    counter++;
//This if statment is o(1) in each iteration, there were n interation so in the overall it is
//o(n) for the whole loop.
int percentage = counter / (array.len()); //It is being done in o(1).
o(1) + o(n) + o(1) = o(n)


text:
Q: Accessing Data from Within a List or Tuple and Cleaning it Here is a conceptual problem that I have been having regarding the cleaning of data and how to interact with lists and tuples that I'm not sure completely how to explain, but if I can get a fix for it, I can conceptually be better at using python.
Here it is: (using python 3 and sqlite3)
I have an SQLite Database with a date column which has text in it in the format of MM-DD-YY 24:00. when viewed in DB Browser the text looks fine. However, when using a fetchall() in Python the code prints the dates out in the format of 'MM-DD-YY\xa0'. I want to clean out the \xa0 from the code and I tried some code that is a combination of what I think I should do plus another post I read on here. This is the code:
 print(dates)
 output [('MM-DD-YY\xa0',), ('MM-DD-YY\xa0',)etc.blahblah] i just typed this in here
 to show you guys the output
 dates_clean = []
 for i in dates:
      clean = str(i).replace(u'\xa0', u' ')
      dates_clean.append(clean)

Now when I print dates_clean I get:
 ["('MM-DD-YY\xa0',)", "('MM-DD-YY\xa0',)"etc]

so now as you can see when i tried to clean it, it did what I wanted it to do but now the actual tuple that it was originally contained in has become part of the text itself and is contained inside another tuple. Therefore when I write this list back into SQLite using an UPDATE statement. all of the date values are contained inside a tuple.
It frustrates me because I have been facing issues such as this for a while, where I want to edit something inside of a list or a tuple and have the new value just replace the old one instead of keeping all of the characters that say it is a tuple and making them just text. Sorry if that is confusing like I said its hard for me to explain. I always end up making my data more dirty when trying to clean it up.
Any insights in how to efficiently clean data inside lists and tuples would be greatly appreciated. I think I am confused about the difference between accessing the tuple or accessing what is inside the tuple. It could also be helpful if you could suggest the name of the conceptual problem I'm dealing with so I can do more research on my own.
Thanks!

A: You are garbling the output by calling str() on the tuple, either implicitly when printing the whole array at once, or explicitly when trying to "clean" it.
See (python3):
>>> print("MM-DD-YY\xa024:00")
MM-DD-YY 24:00

but:
>>> print(("MM-DD-YY\xa024:00",))
('MM-DD-YY\xa024:00',)

This is because tuple.__str__ calls repr on the content, escaping the non-ascii characters in the process.
However if you print the tuple elements as separate arguments, the result will be correct. So you want to replace the printing with something like:
for row in dates:
    print(*row)

The * expands the tuple to separate parameters. Since these are strings, they will be printed as is:
>>> row = ("MM-DD-YY\xa023:00", "MM-DD-YY\xa024:00")
>>> print(*row)
MM-DD-YY 23:00 MM-DD-YY 24:00

You can add separator if you wish
>>> print(*row, sep=', ')
MM-DD-YY 23:00, MM-DD-YY 24:00

... or you can format it:
>>> print('from {0} to {1}'.format(*row))
from MM-DD-YY 23:00 to MM-DD-YY 24:00

Here I am using the * again to expand the tuple to separate arguments and then simply {0} for zeroth member, {1} for first, {2} for second etc. (you can also use {} for next if you don't need to change the order, but giving the indices is clearer).

Ok, so now if you actually need to get rid of the non-breaking space anyway, replace is the right tool. You just need to apply it to each element of the tuple. There are two ways:

*

*Explicit destructuring; applicable when the number of elements is fixed (should be; it is a row of known query):
Given:
>>> row = ('foo', 2, 5.5)

you can destructure it and construct a new tuple:
>>> (a, b, c) = row
>>> (a.replace('o', '0'), b + 1, c * 2)
('f00', 3, 11.0)

this lets you do different transformation on each column.

*Mapping; applicable when you want to do the same transformation on all elements:
Given:
>>> row = ('foo', 'boo', 'zoo')

you just wrap a generator comprehension in a tuple constructor:
>>> tuple(x.replace('o', '0') for x in row)
('f00', 'b00', 'z00')

On a side-note, SQLite has some date and time functions and they expect the timestamps to be in strict IS8601 format, i.e. %Y-%m-%dT%H:%M:%S (optionally with %z at the end; using strftime format; in TR#35 format it is YYYY-MM-ddTHH-mm-ss(xx)).

A: In your case, dates is actually a list of tuples, with each tuple containing one string element. The , at the end of the date string is how you identify a single element tuple.
The for loop you have needs to work on each element within the tuples, instead of the tuples themselves. Something along the lines of:
for i in dates:
     date = i[0]
     clean = str(date).replace('\xa0', '')
     dates_clean.append(date)

I am not sure this the best solution to your actual problem of manipulating data in the db, but should answer your question.
EDIT: Also, refer the Jan's reply about unicode strings and python 2 vs python 3.


text:
Q: Record Video Button in tkinter GUI python I'm pretty new to python and espcially tkinter and opencv.
I've got someway (a little way) to creating a gui that will eventually control a microscope and ai. But I've hit a stumbling block, trying to record the video that is displayed within the gui, I think its to do with the video feed already been captured in the display, but I can't find a way around it. It all works fine until I hit record then it crashes and i get the error: open VIDEOIO(V4L2:/dev/video0): can't open camera by index.
Apologies for the long code but I've cut it down to as much as I think possible.
The problem is in the root.recbtn and def rec sections.
import cv2
import tkinter as tk
import multiprocessing
from tkinter import *
from PIL import Image,ImageTk
from datetime import datetime
from tkinter import messagebox, filedialog

e = multiprocessing.Event()
p = None

# Defining CreateWidgets() function to create necessary tkinter widgets
def createwidgets():

    root.cameraLabel = Label(root, bg="gray25", borderwidth=3, relief="ridge")
    root.cameraLabel.grid(row=2, column=1, padx=10, pady=10, columnspan=3)

    root.browseButton = Button(root, bg="gray25", width=10, text="BROWSE", command=destBrowse)
    root.browseButton.grid(row=1, column=1, padx=10, pady=10)

    root.recbtn = Button(root, bg="gray25", width=10, text="Record", command=rec)
    root.recbtn.grid(row=1, column=5, padx=10, pady=10)

    root.saveLocationEntry = Entry(root, width=55, textvariable=destPath)
    root.saveLocationEntry.grid(row=1, column=2, padx=10, pady=10)

    # Calling ShowFeed() function
    ShowFeed()

# Defining ShowFeed() function to display webcam feed in the cameraLabel;

def ShowFeed():
    # t5  # Capturing frame by frame
    ret, frame = root.cap.read()

    if ret:
        # Flipping the frame vertically
        frame = cv2.flip(frame, 1)

        # Changing the frame color from BGR to RGB
        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)

        # Creating an image memory from the above frame exporting array interface
        videoImg = Image.fromarray(cv2image)

        # Creating object of PhotoImage() class to display the frame
        imgtk = ImageTk.PhotoImage(image = videoImg)

        # Configuring the label to display the frame
        root.cameraLabel.configure(image=imgtk)

        # Keeping a reference
        root.cameraLabel.imgtk = imgtk

        # Calling the function after 10 milliseconds
        root.cameraLabel.after(10, ShowFeed)
    else:
        # Configuring the label to display the frame
        root.cameraLabel.configure(image='')

def destBrowse():
    # Presenting user with a pop-up for directory selection. initialdir argument is optional
    # Retrieving the user-input destination directory and storing it in destinationDirectory
    # Setting the initialdir argument is optional. SET IT TO YOUR DIRECTORY PATH
    destDirectory = filedialog.askdirectory(initialdir="YOUR DIRECTORY PATH")

    # Displaying the directory in the directory textbox
    destPath.set(destDirectory)

def rec():
    vid_name = datetime.now().strftime('%d-%m-%Y %H-%M-%S')

    # If the user has selected the destination directory, then get the directory and save it in image_path
    if destPath.get() != '':
        vid_path = destPath.get()
    # If the user has not selected any destination directory, then set the image_path to default directory
    else:
        messagebox.showerror("ERROR", "No Directory Selected!")

    # Concatenating the image_path with image_name and with .jpg extension and saving it in imgName variable
    vidName = vid_path + '/' + vid_name + ".avi"
    capture = cv2.VideoCapture(0)

    fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
    videoWriter = cv2.VideoWriter(vidName, fourcc, 30.0, (640, 480))

    while (True):

        ret, frame = capture.read()

        if ret:
            cv2.imshow('video', frame)
            videoWriter.write(frame)

        if cv2.waitKey(1) == 27:
            break

    capture.release()
    videoWriter.release()

# Creating object of tk class
root = tk.Tk()

# Creating object of class VideoCapture with webcam index
root.cap = cv2.VideoCapture(0)

# Setting width and height
width, height = 1200, 1200
root.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
root.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

# Setting the title, window size, background color and disabling the resizing property
root.title("Test-AI-tes")
root.geometry("1600x1024")
root.resizable(True, True)
root.configure(background = "gray18")

# Creating tkinter variables
destPath = StringVar()
imagePath = StringVar()

createwidgets()
root.mainloop()

Thanks!

A: This answer is similar to @Art's answer but I removed the after_id and queue.
import cv2
import threading
import tkinter as tk
from PIL import Image, ImageTk

def stop_rec():
    global running
    running = False

    start_button.config(state="normal")
    stop_button.config(state="disabled")

def start_capture():
    global capture, last_frame

    capture = cv2.VideoCapture(0)

    fourcc = cv2.VideoWriter_fourcc("X", "V", "I", "D")
    video_writer = cv2.VideoWriter(r"sample.avi", fourcc, 30.0, (640, 480))

    while running:
        rect, frame =  capture.read()

        if rect:
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
            last_frame = Image.fromarray(cv2image)
            video_writer.write(frame)

    capture.release()
    video_writer.release()

def update_frame():
    if last_frame is not None:
        tk_img = ImageTk.PhotoImage(master=video_label, image=last_frame)
        video_label.config(image=tk_img)
        video_label.tk_img = tk_img

    if running:
        root.after(10, update_frame)

def start_rec():
    global running

    running = True
    thread = threading.Thread(target=start_capture, daemon=True)
    thread.start()
    update_frame()

    start_button.config(state="disabled")
    stop_button.config(state="normal")

def closeWindow():
    stop_rec()
    root.destroy()

running = False
after_id = None
last_frame = None

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", closeWindow)

video_label = tk.Label()
video_label.pack(expand=True, fill="both")

start_button = tk.Button(text="Start", command=start_rec)
start_button.pack()
stop_button = tk.Button(text="Stop", command=stop_rec, state="disabled")
stop_button.pack()

root.mainloop()

It uses the boolean flag running instead of using after_id. Also instead of storing the images in a queue then showing it, I only keep the last image. That way it can run in real time on my computer. Don't worry all of the frames are still being stored in the video file.

A: You cannot have infinite while loop along with the GUI's loop. You should instead make use of threading, whenever you have an IO operation to complete.
Example code:
import cv2
import threading
import tkinter as tk
from PIL import Image, ImageTk
from queue import Queue

def stop_rec():
    global running, after_id
    running = False

    if after_id:
        root.after_cancel(after_id)
        after_id = None

    with frame_queue.mutex:
        frame_queue.queue.clear()

def start_capture():
    global capture

    capture = cv2.VideoCapture(0)

    fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
    video_writer = cv2.VideoWriter(r"sample.avi", fourcc, 30.0, (640, 480))

    while running:

        rect, frame =  capture.read()

        if rect:
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
            videoImg = Image.fromarray(cv2image)
            # current_frame = ImageTk.PhotoImage(image = videoImg)
            frame_queue.put(videoImg)
            video_writer.write(frame)

    capture.release()
    video_writer.release()

def update_frame():
    global after_id

    if not frame_queue.empty():
        video_label.image_frame = ImageTk.PhotoImage(frame_queue.get_nowait())
        video_label.config(image=video_label.image_frame)

    after_id = root.after(10, update_frame)

def start_rec():
    global running

    stop_rec()

    running = True
    thread = threading.Thread(target=start_capture, daemon=True)
    thread.start()
    update_frame()

def closeWindow():
    stop_rec()
    root.destroy()

running = False
after_id = None
frame_queue = Queue()

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", closeWindow)

video_label = tk.Label()
video_label.pack(expand=True, fill="both")

tk.Button(text="Start", command=start_rec).pack()
tk.Button(text="stop", command=stop_rec).pack()

root.mainloop()

Quick explanation:

*

*start the record function in a new thread.

*Use Queue to store the frames.

*Then make use of [widget].after to update the label at regular intervals.

*To stop the recording make use of [widget].after_cancel(after_id)(after_id is returned when you use .after method) and set the running variable to False to stop the loop.


text:
Q: Excel VBA flashing image / text boxes - selective screen update? I am creating a football manager game in Excel - just for a vba / Excel training exercise.
It's nearly finished, but the match screen flashes every iteration (each half minute that passes). I have played around with screen updating but still get the same problem, as I need the screen to update once every iteration to show time has passed, the game stats have changed etc.
a) The worksheet is fine, but the main screen image flashes (big issue), as do the text boxes (minor issue). If I just use a background image it doesn't flash but lacks the same visual effect.
b) the flash seems random - i.e. sometimes you'll go a whole 90 minutes without it flashing at all - other times it flashes like crazy and drives you mad.
Any suggestions?
I won't paste the whole code because its pretty huge.


text:
Q: Warning in console.log when adding embedded google maps I want to add google maps (embedded) map in my web app. I'm building an angular 8 and using built-in server but still in console.log showing warnings
A cookie associated with a cross-site resource at https://google.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review coo...

What I've done in my code in my ngOnInit method, I already added this
    this.cookieService.set('cross-site-cookie',"bar");
    this.cookieService.set('SameSite','SameSite=None; Secure');

The code above I use npm package called ngx-cookie-service. Also as I made myself a reference to this website
https://github.com/GoogleChromeLabs/samesite-examples/blob/master/javascript.md

I'm not sure either I have done it right or wrong. What I did is I just copy entirely using "copy link" from google maps from my place. How to fix this.

A: <iframe src="your google map url"></iframe>

Try this out.

A: Try the following:
You can disable them through chrome://flags Cookie Deprecation messages disabled.
Chrome Console SameSite Cookie Attribute Warning
If you can to add a google map full follow this tutorial:
https://dev.to/devpato/setup-google-map-in-angular-app-the-pro-way-3m9p
Easier way to add a google map to your angular app:
https://dev.to/devpato/setup-google-maps-with-agm-in-angular-app-33em


text:
Q: Residual sum of squares in multiple outputs problem On ESL page 56, "...suppose $\mathrm{Cov}(\epsilon)=\Sigma$, then the multivariate weighted criterion $\mathrm{RSS}(B;\Sigma)=\sum_{i=1}^{N}(y_i-f(x_i))^T\Sigma^{-1}(y_i-f(x_i))=\mathrm{tr}((Y-XB)\Sigma^{-1}(Y-XB)^T)$ arises naturally from multivariate Gaussian theory. Here $f(x)$ is the vector
function $(f_1(x),...,f_K(x))$, and $y_i$ the vector of K responses for observation i..."
My questions are:1. What is the definition of RSS in multiple outputs problem? 2.How to derive this equation?
I tried to think retroductively, even I know that $\Sigma^{-1}$ is a precision matrix, it didn't help to expand this equation and get the definition of RSS in this case.


text:
Q: Problem using function useEffect() in React Hooks I have a little problem. I searched all over the internet and I can't find an answer. I'm trying to use function useEffect(), but unfortunately, I can`t.
I have to say that I imported useEffect via import React, { useEffect } from 'react';

A: First to use useEffect hook you need to use it within function component and only at the top level of function like this
function SomeComponent() {

    // >> HERE << you should use it within this area

    return (
        // some JSX
    )
}

And what this hook can do you can read more at React useEffect hook from official site

This section I will explain how to use it in the way I understand. There are 3 way to use this hook
First: Run only on the first time component rendered
function SomeComponent() {

    useEffect(() => {
        console.log("This will run once when rendered!")
    }, []) // << Leave this list blank

    return (
        // some JSX
    )
}

Second: Run every time when something in watching list is updated
function SomeComponent() {

    useEffect(() => {
        console.log("This will run when a or b or c has updated!")
    }, [a, b, c]) // << This is watching list

    return (
        // some JSX
    )
}

Third: Run when this component re-rendered (also the first time rendered)
function SomeComponent() {

    useEffect(() => {
        console.log("This will run when I first rendered and every time I re-rendered!")
    }) // << Remove the list completely

    return (
        // some JSX
    )
}

This is my understanding sorry if I say something wrong feel free to correct me.


text:
Q: Debug.Assert() has unexpected side effects - searching for alternatives I'm frequently using asserts to detect unexpected program states. I thought an assert is a conditional message box the immediately stops all threads so that (on pressing "Retry") I can inspect the current application state.
This is not the case! While the assert message is open, my wpf application continues processing events. It is absurd, as on breaking into the debugger the situation might be totally different compared to what the assert "saw" initially. You can have the case that the check for the assert to fire changes through the assert itself, you can have recursive execution of methods - with the consequence of multiple asserts or states in which the program would never come normally.
As far as I understand the assert-function, this is a problem by design. The dialog runs on the same GUI thread as the application itself and hence needs to process messages for its own purpose. But this often has the described side-effects.
So I'm searching for an assert alternative that fulfills the requirement to stop all running threads when invoked. As workaround, I sometimes use "Debugger.Break();" which has (unfortunately) no effect if started without debugger.
For illustrating the problem, please see the following code snipped that in the most simplified manner produces some phenomenons:
public partial class MainWindow : Window
{
  int _count = 0;

  public MainWindow()
  {
    InitializeComponent();
  }
  private void onLoaded(object sender, RoutedEventArgs e)
  {
    test();
  }
  protected override void OnLocationChanged(EventArgs e)
  {
    base.OnLocationChanged(e);
  }
  void test()
  {
    ++_count;
    Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() =>
    {
      test();
    }));

    Trace.TraceInformation(_count.ToString());
    Debug.Assert(_count != 5);
  }
}

On running the code, watch the output panel of the developer studio. You will see the numbers go up to 5, then the assert fires. But while the dialog is open, the numbers are still increasing. Hence the condition of the assert changes while the assert is open!
Now check the main window –it's still responsive. Set a breakpoint at "base.OnLocationChanged(e);" and move the main window => you will hit the break point. But mind the callstack:
MainWindow.OnLocationChanged(System.EventArgs e)
(…)
System.dll!Microsoft.Win32.SafeNativeMethods.MessageBox(System.IntPtr
System.dll!System.Diagnostics.AssertWrapper.ShowMessageBoxAssert(stri
System.dll!System.Diagnostics.DefaultTraceListener.Fail(string message, str
System.dll!System.Diagnostics.DefaultTraceListener.Fail(string message)
System.dll!System.Diagnostics.TraceInternal.Fail(string message)
System.dll!System.Diagnostics.Debug.Assert(bool condition)
MainWindow.test()
MainWindow.test.AnonymousMethod__0()

This clearly shows that arbitrary code can be executed while the assert is open.
So I'm searching for an assert like mechanism that stopps all existing threads and runns in it's own (thread-) context.
Any ideas?

A: You are finding out more about how the dispatcher loop works.  And yes, the MessageBox that the default trace listener uses to report the failure does not do much to stop your program.  It was designed to stop the user, it is a modal dialog box that disables all user input.  But does not stop anything that you do in your code.  Like it calling Dispatcher.BeginInvoke().
You will need another implementation of the TraceListener.Fail() method.  That's quite possible, edit your App.xaml.cs file and make it look similar to this:
using System.Diagnostics;
...
    public partial class App : Application {
        public App() {
            if (Debugger.IsAttached) {
                var def = Debug.Listeners["Default"];
                Debug.Listeners.Remove(def);
                Debug.Listeners.Add(new MyListener(def));
            }
        }

        private class MyListener : TraceListener {
            private TraceListener defListener;
            public MyListener(TraceListener def) { defListener = def; }
            public override void Write(string message) { defListener.Write(message); }
            public override void WriteLine(string message) { defListener.WriteLine(message); }

            public override void Fail(string message, string detailMessage) {
                base.Fail(message, detailMessage);
                Debugger.Break();
            }
        }
    }

The code works by removing the DefaultTraceListener, the one that's giving you a headache, from the installed listeners.  And adds a custom one, the MyListener class.  Which doesn't do much, just uses the original listener to get messages displayed in the Output window.  But with an override for the Fail() message, it automatically triggers a debugger break.  Just what you want here.

A: I'm answering my own question as summary and extension of the provided information by Jon Skeet and Hans Passant:
For the case the program runs in the debugger the option with Debugger.Break() or enabling the EEMessageException is for me the way to go. Both methods immediately stop all threads.
If not debugging and the assert occurs in the GUI thread a message box running on a separate thread helps (see http://eprystupa.wordpress.com/2008/07/28/running-wpf-application-with-multiple-ui-threads/)
Here is the code putting all together (by extending the suggestion from Hans Passant)
  public partial class App : Application
  {
    public App()
    {
      var def = Debug.Listeners["Default"];
      Debug.Listeners.Remove(def);
      Debug.Listeners.Add(new MyListener(def, Dispatcher.CurrentDispatcher));
    }

    private class MyListener : TraceListener
    {
      private TraceListener _defListener;
      private Dispatcher _guiDisp;
      public MyListener(TraceListener def, Dispatcher guiDisp)
      {
        _defListener = def;
        _guiDisp = guiDisp;
      }
      public override void Write(string message) { _defListener.Write(message); }
      public override void WriteLine(string message) { _defListener.WriteLine(message); }

      public override void Fail(string message, string detailMessage)
      {
        base.Fail(message, detailMessage);  //write message to the output panel

        if (Debugger.IsAttached)
        {
          //if debugger is attached, just break => all threads stopped
          Debugger.Break();
        }
        else if (Dispatcher.CurrentDispatcher == _guiDisp)
        {
          //running standalone and called in the GUI thread => block it
          Thread anotherGuiThread = new Thread(() =>
          {
            //TODO: nice dlg with buttons
            var assertDlg = new Window() { Width = 100, Height = 100 };
            assertDlg.Show();
            assertDlg.Closed += (s, e) => assertDlg.Dispatcher.InvokeShutdown();
            System.Windows.Threading.Dispatcher.Run();  //run on its own thread
          });

          anotherGuiThread.SetApartmentState(ApartmentState.STA);
          anotherGuiThread.Start();
          anotherGuiThread.Join();
        }
        else
        {
          //running standalone and NOT called in the GUI thread => call normal assert
          _defListener.Fail(message, detailMessage);
        }
      }
    }
  }


text:
Q: Write a string in a CSV column I'm very new at Powershell scripting, hit the wall again. Need help please!
I have a powershell script that I use to do some operations on a CSV file. I need to add another operation to this script. I need to write a certain string to the column J
Here is the existing script
Import-Csv C:\sandbox\test.csv -Header A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z |
    ForEach-Object {$_.Z = $_.U; $_} |
    Select-Object * -ExcludeProperty B | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content C:\sandbox\out.csv

Now, I want to add the word "text" to each of the rows, in column J.

A: Well, if you insist. the easiest way to do that, would be to add another ; and another bit of code to make j equal to 'text'
{$_.Z = $_.U; $_.j = 'text'; $_}

A: other solution :
Import-Csv C:\sandbox\test.csv -Header A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z |
    select *, @{N='J';E={'TEST'}}, @{N='Z';E={$_.U}} -ExcludeProperty B, Z, J |
        export-csv "C:\sandbox\out.csv" -NoTypeInformation


text:
Q: guessing capacitor behaviour correctly I came across this Animation and have no idea why the output is shaped like this. Apperantly the capacitor is charging and discharging but I cannot tell when this happens. All I know is that capacitors do not like the voltage across them to change and resist it.
Can you help me understand and comprehend this animation as I am terrible at guessing capacitor behaviour.

A: As current flows through a capacitor, it charges up and develops a voltage across it. This voltage takes up some of the voltage drop from the source that is available to the rest of the circuit.
That's why you have that negative slope. As the cap develops a voltage, less voltage is available to power the other components in your circuit.
If the cap ever manages to charge up to match the source voltage, then zero volts is available to the rest of the circuit and no current can flow but this circuit is changing too often, too quickly for the capacitor ever reach that point.

A: You were looking at node voltages not the difference which is Vcap.
Try again. CdV/dt=Ic

A: The capacitor combined with the resistors forms a high pass filter, in that only the rising and falling edges can pass through un-distorted. The flat top and bottom cannot be maintained, so they drop off in amplitude until the next rising/falling edge. (Called droop effect)
The pulse width and time-constant of the RC values are just enough to create what you see. If the value of C is lower the droop effect is more pronounced until you have mostly just rising and falling edges.
If the value of C is MUCH higher then the waveform would pass through with no droop effect, assuming the pulse rate and width does not change.


text:
Q: Failed Windows Update, Understanding Rollbacks A little bit of background, I work as an network administrator for an investment banking company, if a computer isn't working then the directors consider that to be losing money, this means that is a important that everything is available to run at 6AM when the sales team start, even though the IT team don't start till 7am.
TL;DR Computers must work immediately at 6am, IT start at 7am.
So when we run windows updates, sometimes the updates fail and have to be rolled back, they only seem to roll back when a user attempts to login.
How can I get a failed update to roll back immediately after failing?


text:
Q: Async Tasks, Cancellation, and Exceptions I'm currently learning how to properly expose asynchronous parts of our library API with Tasks so they can be easier and nicer to use for customers. I decided to go with the TaskCompletionSource approach of wrapping a Task around it that doesn't get scheduled on the thread pool (in the instance here unneeded anyway since it's basically just a timer). This works fine, but cancellation is a bit of a headache right now.
The example shows the basic usage, registering a delegate on the token, but is a tiny bit more complicated than in my case, more to the point, I'm not really sure what to do with the TaskCanceledException. The documentation says either just returning and having the task status switch to RanToCompletion, or throwing an OperationCanceledException (which results in the task's result being Canceled) is fine. However, the examples seem to only pertain to, or at least mention, tasks that are started via a delegate passed to TaskFactory.StartNew.
My code currently is (roughly) as follows:
public Task Run(IFoo foo, CancellationToken token = default(CancellationToken)) {
  var tcs = new TaskCompletionSource<object>();

  // Regular finish handler
  EventHandler<EventArgs> callback = (sender, args) => tcs.TrySetResult(null);
  // Cancellation
  token.Register(() => {
    tcs.TrySetCanceled();
    CancelAndCleanupFoo(foo);
  });

  RunFoo(foo, callback);
  return tcs.Task;
}

(There is no result and no possible exceptions during execution; one reason why I chose to start here, and not at more complicated places in the library.)
In the current form, when I call TrySetCanceled on the TaskCompletionSource, I always get a TaskCanceledException if I await the task returned. My guess would be that this is normal behaviour (I hope it is) and that I'm expected to wrap a try/catch around the call when I want to use cancellation.
If I don't use TrySetCanceled, then I'll eventually run in the finish callback and the task looks like it finished normally. But I guess if a user wants to distinguish between a task that finished normally and one that was canceled, the TaskCanceledException is pretty much a side-effect of ensuring that, right?
Another point I didn't quite understand: Documentation suggests that any exceptions, even those that pertain to cancellation, are wrapped in an AggregateException by the TPL. However, in my tests I'd always get the TaskCanceledException directly, without any wrapper. Am I missing something here, or is that just poorly-documented?

TL;DR:

*

*For a task to transition into the Canceled state, there's always a corresponding exception needed for that and users have to wrap a try/catch around the async call to be able to detect that, right?

*The TaskCanceledException being thrown unwrapped is also expected and normal and I'm not doing anything wrong here?

A: I always recommend people read the Cancellation in Managed Threads docs. It's not quite complete; like most MSDN docs, it tells you what you can do, not what you should do. But it's definitely more clear than the dotnet docs on cancellation.

The example shows the basic usage

First, it's important to note that the cancellation in your example code only cancels the task - it does not cancel the underlying operation. I strongly recommend that you do not do this.
If you want to cancel the operation, then you would need to update RunFoo to take a CancellationToken (see below for how it should use it):
public Task Run(IFoo foo, CancellationToken token = default(CancellationToken)) {
  var tcs = new TaskCompletionSource<object>();

  // Regular finish handler
  EventHandler<AsyncCompletedEventArgs> callback = (sender, args) =>
  {
    if (args.Cancelled)
    {
      tcs.TrySetCanceled(token);
      CleanupFoo(foo);
    }
    else
      tcs.TrySetResult(null);
  };

  RunFoo(foo, token, callback);
  return tcs.Task;
}

If you can't cancel foo, then don't have your API support cancellation at all:
public Task Run(IFoo foo) {
  var tcs = new TaskCompletionSource<object>();

  // Regular finish handler
  EventHandler<EventArgs> callback = (sender, args) => tcs.TrySetResult(null);

  RunFoo(foo, callback);
  return tcs.Task;
}

Callers can then perform a cancelable wait on the task, which is a much more appropriate code technique for this scenario (since it is the wait that is canceled, not the operation represented by the task). Performing a "cancelable wait" can be done via my AsyncEx.Tasks library, or you could write your own equivalent extension method.

The documentation says either just returning and having the task status switch to RanToCompletion, or throwing an OperationCanceledException (which results in the task's result being Canceled) is fine.

Yeah, those docs are misleading. First, please don't just return; your method would complete the task successfully - indicating the operation completed successfully - when in fact the operation did not complete successfully. This may work for some code, but is certainly not a good idea in general.
Normally, the proper way to respond to a CancellationToken is to either:

*

*Periodically call ThrowIfCancellationRequested. This option is better for CPU-bound code.

*Register a cancellation callback via Register. This option is better for I/O-bound code. Note that registrations must be disposed!

In your particular case, you have an unusual situation. In your case, I would take a third approach:

*

*In your "per-frame work", check token.IsCancellationRequested; if it is requested, then raise the callback event with AsyncCompletedEventArgs.Cancelled set to true.

This is logically equivalent to the first proper way (periodically calling ThrowIfCancellationRequested), catching the exception, and translating it into an event notification. Just without the exception.

I always get a TaskCanceledException if I await the task returned. My guess would be that this is normal behaviour (I hope it is) and that I'm expected to wrap a try/catch around the call when I want to use cancellation.

The proper consuming code for a task that can be canceled is to wrap the await in a try/catch and catch OperationCanceledException. For various reasons (many historical), some APIs will cause OperationCanceledException and some will cause TaskCanceledException. Since TaskCanceledException derives from OperationCanceledException, consuming code can just catch the more general exception.

But I guess if a user wants to distinguish between a task that finished normally and one that was canceled, the [cancellation exception] is pretty much a side-effect of ensuring that, right?

That's the accepted pattern, yes.

Documentation suggests that any exceptions, even those that pertain to cancellation, are wrapped in an AggregateException by the TPL.

This is only true if your code synchronously blocks on a task. Which it should really avoid doing in the first place. So the docs are definitely misleading again.

However, in my tests I'd always get the TaskCanceledException directly, without any wrapper.

await avoids the AggregateException wrapper.
Update for comment explaining CleanupFoo is a cancellation method.
I'd first recommend trying to use CancellationToken directly within the code initiated by RunFoo; that approach would almost certainly be easier.
However, if you must use CleanupFoo for cancellation, then you'll need to Register it. You'll need to dispose that registration, and the easiest way to do this may actually be to split it into two different methods:
private Task DoRun(IFoo foo) {
  var tcs = new TaskCompletionSource<object>();

  // Regular finish handler
  EventHandler<EventArgs> callback = (sender, args) => tcs.TrySetResult(null);

  RunFoo(foo, callback);
  return tcs.Task;
}

public async Task Run(IFoo foo, CancellationToken token = default(CancellationToken)) {
  var tcs = new TaskCompletionSource<object>();
  using (token.Register(() =>
      {
        tcs.TrySetCanceled(token);
        CleanupFoo();
      });
  {
    var task = DoRun(foo);
    try
    {
      await task;
      tcs.TrySetResult(null);
    }
    catch (Exception ex)
    {
      tcs.TrySetException(ex);
    }
  }
  await tcs.Task;
}

Properly coordinating and propagating the results - while preventing resource leaks - is quite awkward. If your code could use CancellationToken directly, it would be much cleaner.

A: What you are doing is fine - Task represents some operation with result in future, it is not necessary related to running anything on another thread or something like that. And it's perfectly normal to use standard means of cancellation for, well, cancellation, instead of returning something like boolean value.
To answer your questions: when you do tcs.TrySetCanceled() it will move task to cancelled state (task.IsCancelled will be true) and no exceptions are thrown at this point. But when you await this task - it will notice that task is cancelled and that is the point where TaskCancelledException will be thrown. Nothing is wrapped into aggregate exception here because there is really nothing to wrap - TaskCancelledException is thrown as a part of await logic. Now if you will do something like task.Wait() instead - then it will wrap TaskCancelledException into AggregateException as you would expect.
Note that await unwraps AggregateExceptions anyway, so you might never expect await task to throw AggregateException - in case of multiple exceptions only first one will be thrown - the rest will be swallowed.
Now if you are using cancellation token with regular tasks - things are a bit different. When you do something like token.ThrowIfCancellationRequested it will actually throw OperationCancelledException (note that it's not TaskCancelledException but TaskCancelledException is subclass of OperationCancelledException anyway). Then, if CancellationToken used to throw this exception is the same as CancellationToken passed to task when it was started (like in example by your link) - task will move to the Cancelled state the same way. This is the same as tcs.TrySetCancelled in your code with the same behavior. If tokens mismatch - task will go to Faulted state instead, like the regular exception was thrown.

A: From the comments, it looks like you have an animation library that accepts an IAnimation, executes it (obviously asynchronously) and then signals back that it completed.
This isn't an actual task, in the sense that it isn't a piece of work that has to run on a thread. It's an asynchronous operation, which in .NET is exposed using a Task object.
Furthermore, you aren't actually cancelling something, you are stopping the animation. That's a perfectly normal operation so it shouldn't throw an exception. It would be better if your method returned a value that explained whether the animation completed or not, eg:
public Task<bool> Run(IAnimation animation, CancellationToken token = default(CancellationToken)) {
  var tcs = new TaskCompletionSource<bool>();

  // Regular finish handler
  EventHandler<EventArgs> callback = (sender, args) => tcs.TrySetResult(true);
  // Cancellation
  token.Register(() => {
                         CleanupFoo(animation);
                         tcs.TrySetResult(false);
                       });
  RunFoo(animation, callback);
  return tcs.Task;
}

The call to run an animation is simple:
var myAnimation = new SomeAnimation();
var completed = await runner.Run(myAnimation,token);
if (completed)
{
}

UPDATE
This can be improved further with some C# 7 tricks.
For example, instead of using callbacks and lambdas, you can use local functions. Apart from making the code cleaner, they don't allocate a delegate each time they are called. The change doesn't require C# 7 support on the client's side:
Task<bool> Run(IAnimation animation, CancellationToken token = default(CancellationToken)) {
  var tcs = new TaskCompletionSource<bool>();

  // Regular finish handler
  void OnFinish (object sender, EventArgs args) => tcs.TrySetResult(true);
  void OnStop(){
    CleanupFoo(animation);
    tcs.TrySetResult(false);
  }

  // Null-safe cancellation
  token.Register(OnStop);
  RunFoo(animation, OnFinish);
  return tcs.Task;
}

You can also return more complex results, eg a result type that contains a Finished/Stopped flag and the final frame if the animation was stopped. If you don't want to use meaningless fields (why specify a frame if the animation completed?), you can return a Success type or a Stopped type that implement eg IResult.
Before C# 7, you'd need to check the return type or use overloading to access different types. With pattern matching though, you can get the actual result with a switch, eg:
interface IResult{}
public class Success:IResult{}

public class Stopped {
    public int Frame{get;}
    Stopped(int frame) { Frame=frame; }
}

....

var result=await Run(...);
switch (result)
{
    case Success _ :
        Console.WriteLine("Finished");
        break;
    case Stopped s :
        Console.WriteLine($"Stopped at {s.Frame}");
        break;
}

Pattern matching is actually faster than type checking too. This requires that the client supports C# 7.


text:
Q: Temporary Table vs Create and Drop Table I'm creating a table "InterviewTemp" , inserting data there, updating a second table with that data and then dropping the "InterviewTemp" table.
there is an example:
CREATE TABLE [entrevistasTemp](
    [id_usuario] [int] NULL,
    [id_entrevista] [int] NULL,
    [comentarios] [varchar](300) NULL
)

INSERT [entrevistasTemp] ([id_usuario], [id_entrevista], [comentarios]) VALUES (12099, 4515, CONVERT(TEXT, N'Riesgo muy alto.  Marun Victoria, '))
INSERT [entrevistasTemp] ([id_usuario], [id_entrevista], [comentarios]) VALUES (15347, 4516, CONVERT(TEXT, N'Riesgo muy alto.  Marun Victoria, '))

UPDATE entrevistas
    set entrevistas.comentarios = entrevistasTemp.comentarios
    from entrevistasTemp
WHERE entrevistas.id = entrevistasTemp.id_entrevista

drop table entrevistasTemp

there is a better way to do this?
EDIT: just inserting 4.5k rows

A: Create a temporary table instead of a table:
CREATE TABLE #entrevistasTemp(
    [id_usuario] [int] NULL,
    [id_entrevista] [int] NULL,
    [comentarios] [varchar](300) NULL
)

INSERT #entrevistasTemp ([id_usuario], [id_entrevista], [comentarios]) VALUES (12099, 4515, CONVERT(TEXT, N'Riesgo muy alto.  Marun Victoria, '))
INSERT #entrevistasTemp ([id_usuario], [id_entrevista], [comentarios]) VALUES (15347, 4516, CONVERT(TEXT, N'Riesgo muy alto.  Marun Victoria, '))

UPDATE entrevistas
    set entrevistas.comentarios = #entrevistasTemp.comentarios
    from #entrevistasTemp
WHERE entrevistas.id = #entrevistasTemp.id_entrevista

drop table #entrevistasTemp

A: Answer solely depending upon size of data being inserted and frequency of rows being accessed.
If you have a large dataset then you can create a table insert data into that table then implement indexing in the table then use that table for any further operations and thereafter drop the table.
If data size is limited. Then going with answer by aF would be preferable.

A: Even better than the temporary table (if your version of SQL Server supports it [2005+]) is a table variable.  When you create a temporary table, SQL Server must recompile the query any time it runs.  Table variables don't have this issue.  They are also created in memory rather than on disk, and have fewer locking and transaction log contention issues.
Code would look like this:
DECLARE @entrevistasTemp TABLE
(
    [id_usuario] [int] NULL,
    [id_entrevista] [int] NULL,
    [comentarios] [varchar](300) NULL
)

INSERT INTO @entrevistasTemp ([id_usuario], [id_entrevista], [comentarios]) VALUES (12099,
    4515, CONVERT(TEXT, N'Riesgo muy alto.  Marun Victoria, '))
INSERT INTO @entrevistasTemp ([id_usuario], [id_entrevista], [comentarios]) VALUES (15347,
    4516, CONVERT(TEXT, N'Riesgo muy alto.  Marun Victoria, '))

UPDATE entrevistas
    SET entrevistas.comentarios = et.comentarios
    FROM @entrevistasTemp et
WHERE entrevistas.id = et.id_entrevista


text:
Q: Adding REST methods to WCF Data Services? I need to extend my WCF Data Service to include additional methods, not only the database tables..
But it doesn't seem to be working correctly.
Firstly i want to ask if this is legal? or frowned upon?
The reason i need to do it is i need add additional REST methods that will make a call to ASP.NET Membership services (the tables are in the db) to validate a login i.e.
    public bool IsValidLogin(string username, string password)
    {
        return System.Web.Security.Membership.ValidateUser(username, password);
    }

Here is what i have (i have simplied the IsValidLogin for testing).
    [WebGet(UriTemplate = "TestMe")]
    public bool IsValidLogin()
    {
        return true;
    }

    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
        // Examples:
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        config.SetServiceOperationAccessRule("IsValidLogin", ServiceOperationRights.All);

Now when i go to
  http://localhost/MyDataAccess/MyService.svc/IsValidLogin

It seems to work i get an true back in the form of XML. But i have set a URI so i thought i could do this
  http://localhost/MyDataAccess/MyService.svc/TestMe

But it fails? I am really confused, any ideas?
Also for it to work I needed to add this line, but a little but confused here
    config.SetServiceOperationAccessRule("IsValidLogin", ServiceOperationRights.All);

Any help really appreciated

A: Not commenting on the REST dicsussion above, just posting a link on documentation on how to do so called "service operations": http://msdn.microsoft.com/en-us/library/cc668788.aspx

A: The ServiceOperation notion is a tacked on capability to provide exactly the escape you needed when you wanted to do something other than read data from a table.
Unfortunately, the default path in WCF REST has lead you to misunderstand how RESTful systems are supposed to work.  REST is not just about exposing some data at URLs.
You really have two choices, either stick with RPC style of distributed computing that WS-*/SOAP based WCF provides or spend some time learning what REST is really all about.  There are some links here to get you started.
I can't tell you what is the right approach for your scenario.  What I can tell you is that you are not going to learn how to do REST from using the current WCF REST implementation.  I'm not saying it is impossible to do, you just will be doing a lot of swimming upstream.


text:
Q: Can I pass a PHP Array as JSON encoded object as select field value and use with Javascript? I have a PHP function that returns database values to populate a select form field.  I am trying to populate the value of the option elements with all relevant data from the query (id, name, min, max) from the database so I don't have to send a AJAX request to get the rest, so I decided to json_encode the php array before populating select field.
Relevant PHP:
$items[] = array( "text" => $injury['name'], "value" => json_encode($injury) );
HTML Output from PHP:

<select name="input_2" id="input_2_2" class="medium gfield_select" tabindex="4"><option value=" ">Select an Injury</option><option value="{"id":"1","name":"Arm","min":"15000","max":"25000"}">Arm</option><option value="{"id":"3","name":"Head","min":"100000","max":"150000"}">Head</option><option value="{"id":"2","name":"Leg","min":"30000","max":"45000"}">Leg</option></select>

In the javascript side I am using jQuery to get the value of the option as below:
    `jQuery(injuryClass).on("change", function () {
        var injurySelect = jQuery(this);
        injury = injurySelect.val();

    var results = jQuery.parseJSON(jQuery(injury));
console.log(results)

I get a console error:
uncaught error: syntax error, unrecognized expression: {"id":"1","name":"Arm","min":"15000","max":"25000"}

A: The mistake is in jQuery.parseJSON(jQuery(injury));. You call jQuery() with the unparsed JSON. But jQuery expects a selector and the JSON is not a valid one.
Try: jQuery.parseJSON(injury);


text:
Q: Apache Storm calling function from python bolt I have a simple storm bolt which only needs to call a function from another python module. Everything works until I call a method which has print statements inside the function.
So my bolt:
import storm
from pipeline import module as m

class ExampleBolt(storm.BasicBolt):

    def initialize(self, conf, context):
        self._conf = conf;
        self._context = context;
        storm.logInfo("ExampleBolt instance starting ...")

    def process(self, tuple):
        id, text = tuple.values
        result = m.dummy_funct(text)
        storm.emit([result])

ExampleBolt().run()

the method:
def dummy_funct(text):
    print "log info"
    return text

The bolt calls the method one time and then hangs on output. Using Apache Storm 0.9.3

A: Check that, whether from second time only process block is getting executed. Not the whole program is getting executed.


text:
Q: .net core Dockerfile issue / MSBUILD : error MSB1009: Project file does not exist Below is the output of the Error when i build a Dockerfile
My Dockerfile seems like that :
FROM microsoft/aspnetcore-build:6.0 AS build-env
WORKDIR /app
# copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# build runtime image
FROM microsoft/aspnetcore:6.0
WORKDIR /app
COPY — from=build-env /app/out .
EXPOSE 80/tcp
ENTRYPOINT ["dotnet", "AuditModule.dll"]


text:
Q: add files to root and access it within Android Studio Project in java you could add the file within the project so you could use it on any device, i.e if the file is "data.dat" in java I could put the file in the project root and write this line
try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("data.dat')))

unfortunately I couldn't do this in android studio can someone please explain
in Android Studio it always gives me FileNotFoundException, I even tried using the absolute path but it didn't work, any Idea on how to do it?


text:
Q: How to access Rails 3 engine models in rails console In the mail app's rails console (irb), how to access engine's models.
update: Say "team" is my main app and "team_page" is the engine. "team_page" is required in main app in the gemfile through 'gem => "team_page", :path => "local/path/to/team_page"'.
when I go to team's rails console, I couldn't access team_page's models.

A: First you must know the module's name. To help with that, you can run a
bundle show team_page

to find its directory and explore over there (probably under lib/team_page.rb) until
you see the following definition:
module TeamPage
  # ...
end

Let's say that the module is called TeamPage. Then just prepend double colon to its name like this:
::TeamPage::SomeModel.some_method


text:
Q: Must I declare own wxFrame class? I'm creating simple c++ application with user interface. I have written own classes with needed mechanics, and now I must display some of its components using wxWidgets. MyApp contains objects of that classes, but they are also needed in MyFrame when handling events. It would be much more comfortable without passing pointers to that objects to MyFrame and implement everything in MyApp::OnInit function. Is that possible?
// should contain informations about game state, players, gameboard, etc
class MyApp : public wxApp {
    GameBoard gb;
    Player player;
    bool lightTheme;
public:
    virtual bool OnInit();
};

// should contain only window layout, button events, etc
class MyFrame : public wxFrame {
    GameBoard *gb;
    Player *player;
    bool *lightTheme;

    std::vector<wxStaticBitmap*> cardImages;
// some events here
    void displayImages(wxGridSizer*);
public:
    MyFrame(GameBoard*, Player*, bool*);
};

A: To answer your title question, you don't have to declare MyFrame and can just create and directly use wxFrame and use Bind() to connect the different event handlers. In all but the simplest situations, it's typically convenient to have a MyFrame class centralizing the data and event handlers for the window, but it is not required by any means.
If you decide to keep everything in MyApp instead, you may find wxGetApp() useful for accessing it from various places in your code.