text:
Q: Java compiler level does not match the version of the installed Java project facet I have created a New Dynamic Project under Eclipse Helios Version, where my JRE Version is set to 1.6.
I have added Maven capabilities to the Web Application by clicking on Configure → Convert to Maven Project.
After adding this, a build error appeared in the Eclipse Problems view:
Java compiler level does not match the version of the installed Java project facet.
Unknown Faceted Project Problem (Java Version Mismatch)

Please tell me how to resolve this error (I want to have my JRE version as 1.6 only).

A: I resolved this problem by setting the java version in Project Facet property of the project properties, Right click the project root folder -> Properties, search for Project Facets, and select compatible java version.
For reference -

A: I changed the configuration inside workspace/project/.setting/org.eclipse.wst.common.project.facet.core to :
installed facet="jst.web" version="2.5"
installed facet="jst.java" version="1.7"

Before changing config, remove project from IDE.
This worked for me.

A: I resolved it by Myproject--->java Resource---->libraries-->JRE System Libraries[java-1.6] click on this go to its "property" select "Classpath Container" change the Execution Environment to java-1.8(jdk1.8.0-35) (that is latest)

A: If your project is not a Maven project, right-click on your project and choose Properties to open the Project Properties dialog.
There is a Project Facets item on the left, select it, look for the Java facet on the list, choose which version you want to use for the project and apply.

A: The Project Facet->Java should match whatever you have in the pom.xml for the maven-compiler-plugin artifact source and target.This is perfect.But if you donot have it here then you can also fix it by matching Java compiler version in Porject-Facets from the setting: Eclispe->Preferences->Java->Compiler

A: You can change project facet from
Project --> Properties --> Project Facet --> Java --> {required JDK version}

A: Right click the project and select properties
Click the java compiler from the left and change to your required version
Hope this helps

A: In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.

A: TK Gospodinov answer is correct even for maven projects. Beware: I do use Maven. The pom was correct and still got this issue. I went to "Project Facets" and actually removed the Java selection which was pointing to 1.6 but my project is using 1.7. On the right in the "Runtimes" tab I had to check the jdk1.7 option. Nothing appeared on the left even after I hit "Apply". The issue went away though which is why I still think this answer is important of the specific "Project Facets" related issue. After you hit OK if you come back to "Project Facets" you will notice Java shows up as version 1.7 so you can now select it to make sure the project is "marked" as a Java project. I also needed to right click on the project and select Maven|Update Project.

A: Assuming that you are using the m2e plugin in Eclipse, you'll need to specify the source and target versions as 1.6 for maven-compiler-plugin. m2e uses these values to determine the project's Java compiler level. A snippet of the POM is shown below:
<build>
  <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
    </plugin>
  </plugins>
</build>

Alternatively, you can specify the maven.compiler.source and maven.compiler.target properties with values of 1.6, that happen to be the equivalent:
<properties>
    <maven.compiler.target>1.6</maven.compiler.target>
    <maven.compiler.source>1.6</maven.compiler.source>
</properties>

A: I found @bigleftie's comment above very helpful:
"Four things must match

*

*Project->Java Build Path->Libraries->JRE version

*Project->Java Compiler-> Compiler Compliance Level

*Project->Project Facets->Java->Version

*(if using Maven) pom.xml - maven-compiler-plugin artefact source and target".

In my case, in the project properties, Java compiler, the JDK compliance was set to use the workspace settings, which were different from the java version for the project. I clicked on 'Configure Workspace Settings', and changed the workspace Compiler compliance level to what I wanted, and the problem was resolved.

A: If using eclipse,
Under.settings click on org.eclipse.wst.common.project.facet.core.xml
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <installed facet="java" version="1.7"/>
</faceted-project>

Change the version to the correct version.


text:
Q: Wrong color in progress bar I've got a progress bar which starts as determinate with green color, than changes behavior and became red and indeterminate, finally in the last step returns determinate.
In the second step red color is correct but with the last step, the foreground color is wrong, it is brown instead of red.

The progress bar in xaml file:
<Grid Margin="10,0" Height="58" VerticalAlignment="Bottom">
    <ProgressBar x:Name="progress_bar" Height="20" VerticalAlignment="Bottom" Margin="0,0,0,38" />
    <TextBlock x:Name="progress_bar_text" Margin="300,2,300,40" HorizontalAlignment="Center" >0% - Waiting to start...</TextBlock>
</Grid>

Then when the abort button is pressed:
private void Button_abort_Click(object sender, RoutedEventArgs e)
{
    progress_bar.IsIndeterminate = true;
    progress_bar.Foreground = Brushes.Red;
}

Finally when the task is terminated the task bar behavior returns determinate.
progress_bar.IsIndeterminate = false;
progress_bar.Foreground = Brushes.Red;

Why the progress bar is brown instead of red?

A: try adding this style in your code:
<Style TargetType="{x:Type ProgressBar}">
    <Setter Property="Foreground" Value="HotPink"/>
    <Setter Property="BorderBrush" Value="Gray"/>
    <Setter Property="Value" Value="10"/>
    <Setter Property="Minimum" Value="0"/>
    <Setter Property="Maximum" Value="100"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ProgressBar}">
                <Border BorderThickness="{TemplateBinding BorderThickness}"  Width="{TemplateBinding Width}" MinWidth="10" Height="{TemplateBinding Height}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}">
                    <Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stretch="Fill">
                        <Grid Width="{TemplateBinding Maximum}" Height="50">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Grid Background="{TemplateBinding Foreground}" Grid.Column="0" Width="{TemplateBinding Value}">
                            </Grid>
                        </Grid>
                    </Viewbox>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

This will overwrite the original control template and make the progressbar flat and the color will stay what you set it to be

redpajama_set_name: RedPajamaStackExchange


text:
Q: populating form fields with array How can I take a array values and populate already existing text fields.
For an example, array would have 5 values and there would be 5 text fields.
Array [ tom, Matt, Lucy, Suzanna, Hank ]
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">

A: You should be able to use something like the following to iterate through your <input> elements and pop off each name until they have each been exhausted :
// Your array
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank'];

// Loop through the array and target the next available textbox
for(var input in document.getElementsByName('firstName')){
    // If there are any names to use, use one
    if(array.length > 0){
       // Pop the next name off of your array and set the value
       // of your textbox
       input.value = array.pop();
    }
}

If you have any issues actually using the above example to set the values, you can always use a slightly different loop to handle things :
// Your array
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank'];

// Store your input elements
var inputs = document.getElementsByName('firstName');
// Loop through the array and target the next available textbox
for(var i = 0; i < inputs.length; i++){
        // If there are any names to use, use one
        if(array.length > 0){
           // Pop the next name off of your array and set the value
           // of your textbox
           inputs[i].value = array.pop();
        }
}

You can see a working example in action here and what the output using the data you provided might look like below :

A: You could iterate over the array as a whole, or just simply access every array value one by one

A: you can do that in a bunch of different ways.
e.g
give the fields a class and use jquery to add the value to them
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">

then you can use jquery or javascript to add the value to them:
var currIndex = 0;
$(document).ready(function(){
    $(".damn").each(function(){
        $(this).val(myarray[currIndex++]);
    });
});

UPDATE:  You can also use the approach created by Rion Williams up there.


text:
Q: How should I store static data for a Controller? I have an image model and with it are a set of sizes that the image can be resized to that consist of a string name and the max height/width for that size.
My initial thought was to put it in the database and create a model for image sizes, but this seems like overkill and this would be called fairly often and not changed very often.
So I thought I could store it as a form of static data (a list of an ImageSize class or something), but I'm not sure where in the Controller to put this.
Where should I put this data?

A: You could create another class holding your static data then add the using statement in your Controller class to read the data inside of that class.

A: You can use your web.config file for storing static data. You can also use xml file or application variables for this purpose.
But I would have preferred the web.config file.
More details
IIS and Static content?


text:
Q: Should the appendix be before the bibliography or after? My thesis latex format does not include an appendix, but I need one. Should I put it after the bibliography or before?

A: It depends on the style guide you are following.
In APA Style appendices come after references.

A: The dominant convention, supported by Chicago, Hart's, and Butcher's, is to put the bibliography after the appendices when setting a book.
However, the conventions governing the order of end matter are much less fixed than those governing front matter, which is partly fixed in legislation.  And not only books have appendices and reference lists: some conference series and journals have the appendices following the reference list.


text:
Q: Cannot launch app from Android Studio after update device from Android 8 to 9 I deleted and reposted my question as I thought it was resolved and marked it, but it was not, and I'm adding much more info about it.
I'm working on an Android app and after updating my device's Android version to 9 I'm not being able to run my app from Android Studio anymore.
I'm seeing two different errors in Event Log:
The first (and shortest):

Session 'app': Install failed. Installation failed

Tried everything from next link with no luck:
Session 'app' error while installing APK
The second:

Broken pipe java.io.IOException: Broken pipe at
  sun.nio.ch.FileDispatcherImpl.write0(Native Method) at
  sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47) at
  sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93) at
  sun.nio.ch.IOUtil.write(IOUtil.java:65) at
  sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471) at
  com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:524)
  at
  com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:627)
  at
  com.android.ddmlib.SplitApkInstaller.uploadApk(SplitApkInstaller.java:133)
  at
  com.android.ddmlib.SplitApkInstaller.install(SplitApkInstaller.java:73)
  at com.android.ddmlib.Device.installPackages(Device.java:927) at
  com.android.tools.deployer.AdbClient.install(AdbClient.java:75) at
  com.android.tools.deployer.ApkInstaller.install(ApkInstaller.java:32)
  at com.android.tools.deployer.Deployer.install(Deployer.java:76) at
  com.android.tools.idea.run.tasks.DeployTask.perform(DeployTask.java:79)
  at
  com.android.tools.idea.run.tasks.AbstractDeployTask.perform(AbstractDeployTask.java:109)
  at
  com.android.tools.idea.run.LaunchTaskRunner.run(LaunchTaskRunner.java:132)
  at
  com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:727)
  at
  com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:164)
  at
  com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:582)
  at
  com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:532)
  at
  com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:87)
  at
  com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:151)
  at
  com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:403)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)
My device is a Huawei P20 and I'm working with latest Android Studio
  3.4.1 with Ubuntu, and app run (launch) from Android Studio stopped working after Android 8 to 9 update.
As a note I can add that build process runs OK and device is detected
  correctly when launching (in the first screen where you select the
  target device) and I can also see device as connected in logcat
  viewer, but when finishing building, when ready to deploy you hear the
  sound that the computer does when plugging / unplugging an usb device

.
Any help?
Edit 1:
I thought it ended up being an OS (Ubuntu) problem, because restored a recent backup of my virtual machine and it was working fine, but after updating Android Studio and SDKs (as suggested) it started failing again so it has to be something in conjunction between my device OS Android 9 and the latest SDK updates, I presume.
In the "failing" vm I can run the app in an old Android 4 phone and in my 4.4.3 Asus tablet, and not in my new Android 9 one, and that's why I gussed it could be an Android 9 related issue.
This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.xxx.xxx"
          android:versionCode="1"
          android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <application
        android:name=".activities.shared.AppSettings"
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/Theme.myTheme.TitleBar">
        <service
            android:name=".activities.shared.OnClearFromRecentService"
            android:stopWithTask="false"
            android:enabled="true"
            android:exported="true">
        </service>

        <provider
            android:name=".activities.shared.GenericFileProvider"
            android:authorities="${applicationId}.testMe.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

        <activity
            android:name=".activities.launch.SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.main.MainActivity"
            android:configChanges="orientation"
            android:parentActivityName=".activities.launch.SplashActivity">
        </activity>
        <activity
            android:name=".activities.about.AboutUsActivity"
            android:parentActivityName=".activities.main.MainActivity">
        </activity>
        <activity
            android:name=".activities.about.ChangeLogActivity"
            android:parentActivityName=".activities.about.AboutUsActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.xxx.xxx.activities.about.AboutUsActivity"/>
        </activity>
        <activity
            android:name=".activities.about.ReportProblemActivity"
            android:parentActivityName=".activities.about.AboutUsActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.xxx.xxx.activities.about.AboutUsActivity"/>
        </activity>
        <activity
            android:name=".activities.main.HowToUseActivity"
            android:parentActivityName=".activities.main.MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.xxx.xxx.activities.main.MainActivity"/>
        </activity>
        <activity
            android:name=".activities.DisplayThoughtActivity"
            android:parentActivityName=".activities.main.MainActivity">
        </activity>
        <activity
            android:name=".activities.shared.SettingsActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="Settings">
        </activity>

        <receiver android:name=".helpers.notification.AlarmTakeTestReceiver"/>
    </application>

</manifest>

This is my build.gradle file:
apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    buildToolsVersion '29.0.0'
    def code
    Properties versionProps = new Properties()
    def versionPropsFile = file('version.properties')
    if (versionPropsFile.exists())
        versionProps.load(new FileInputStream(versionPropsFile))
    code = (versionProps['VERSION_CODE'] ?: "0").toInteger() + 1
    versionProps['VERSION_CODE'] = code.toString()
    versionProps.store(versionPropsFile.newWriter(), null)
    packagingOptions {
        pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
    }
    defaultConfig {
        applicationId 'com.xxx.xxx'
        minSdkVersion 17
        targetSdkVersion 28
        versionCode code
        versionName "1.0." + code
        multiDexEnabled true
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationVariants.all { variant ->
                variant.outputs.all { output ->
                    project.ext { appName = 'xxx' }
                    def newName = 'xxx.apk'
                    outputFileName = new File("./build/", newName)
                    //def newName = output.outputFile.name //output.packageApplication.outputFile
                    //newName = newName.replace("app-", "$project.ext.appName-")
                    //newName = newName.replace("-release", "")
                }
            }
        }
        debug {
        }
    }
    allprojects {
        repositories {
            jcenter()
            mavenCentral()
            def androidHome = System.getenv("ANDROID_HOME")
            maven {
                url "$androidHome/extras/android/m2repository/"
            }
            maven {
                url "https://maven.java.net/content/groups/public/"
            }
        }
    }
    productFlavors {
    }
}

dependencies {
    //Google Guava
    api 'com.google.guava:guava:28.0-android'
    //writingminds
    api 'com.writingminds:FFmpegAndroid:0.3.2'
    //JavaCV video
    api group: 'org.bytedeco', name: 'javacv', version: '1.5'
    //api group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '4.1-1.4.4', classifier: 'android-arm'
    //api group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '4.0.1-1.4.4', classifier: 'android-arm'
    //volley
    api 'com.android.volley:volley:1.1.1'
    //spotify
    api 'com.github.kaaes:spotify-web-api-android:0.4.1'
    //mail API 19
    //api 'com.sun.mail:android-mail:1.6.3'
    //api 'com.sun.mail:android-activation:1.6.3'
    //mail API 16
    api 'com.sun.mail:android-mail:1.5.6'
    api 'com.sun.mail:android-activation:1.5.6'
    //apache commons lang
    api 'org.apache.commons:commons-lang3:3.8.1'
    //Font Selector List Preference
    api 'com.vanniktech:vntfontlistpreference:1.0.0'
    //Rate my app
    api 'com.github.hotchemi:android-rate:1.0.1'
    //Support
    api 'com.android.support:appcompat-v7:28.0.0'
    api 'com.android.support:support-v4:28.0.0'
    /*api 'com.android.support:support-v4:28.0.0'
    api 'com.android.support:appcompat-v7:28.0.0'
    api 'com.android.support:cardview-v7:28.0.0'
    api 'com.android.support:recyclerview-v7:28.0.0'
    api 'com.android.support:customtabs:28.0.0'
    api 'com.android.support:support-annotations:28.0.0'*/
    //multidex
    api 'com.android.support:multidex:1.0.3'
    //AlertDialog
    implementation 'com.github.d-max:spots-dialog:1.1@aar'
    //glide animated gifs
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}

Edit 2:
Tried to run another of my working apps and I got this error after building successfully and when about to deploy apk:

Installation failed with message 'cmd package install-create -r -t -S
  11182369' returns error 'Unknown failure: Security exception:
  Permission Denial: runInstallCreate from pm command asks to run as
  user -1 but is calling from user 0; this requires
  android.permission.INTERACT_ACROSS_USERS_FULL
  java.lang.SecurityException: Permission Denial: runInstallCreate from
  pm command asks to run as user -1 but is calling from user 0; this
  requires android.permission.INTERACT_ACROSS_USERS_FULL at
  com.android.server.am.UserController.handleIncomingUser(UserController.java:1827)
  at
  com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:25069)
  at
  android.app.ActivityManager.handleIncomingUser(ActivityManager.java:4848)
  at
  com.android.server.pm.PackageManagerShellCommand.translateUserId(PackageManagerShellCommand.java:2402)
  at
  com.android.server.pm.PackageManagerShellCommand.doCreateSession(PackageManagerShellCommand.java:2408)
  at
  com.android.server.pm.PackageManagerShellCommand.runInstallCreate(PackageManagerShellCommand.java:949)

A: It is a strange problem that has been discussed on SO a few times, happens particularly for  devices newly updated Android 9.
Have you tried disabling and then re-enabling developer options? (And maybe restarting the device?) That seems to have fixed it for some.
If that doesn't work, you might want to look at these and go from there -
Android Pie - 9 (API 28) : Installing APK .... not successfully installing
Permission Denial: startActivity asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL


text:
Q: Cannot debug custom Workflow in VS 2010 for SP2010 I am having problem to debug sharepoint 2010 custom workflow through VS 2010. When ever I click on start debbuging, I get the following message

I am dbo.owner on the SharePoint Config Databases. So I do not know why this happening?
Any help much appreciated!
Thank you

A: Looks to me like more of a Visual Studio\SP installation issue than a Database issue.. so Im not sure if DB Ownership has much to assist with this.
Can you edit\customize the workflow at all using SharePoint Designer?  Even if thats not the ultimate end solution, perhaps it can help you confirm if the workflow is corrupt at all?


text:
Q: What is L2TP connection in ZTE 670L router and how to make it work? My ISP has provided me ZTE 670L GPON router.  The router has an option L2TP VPN Connection.
I have L2TP account on an Internet server. They have provided me  Servername, Userid, Password, Preshared key.
From my Windows 10 laptop, I can easily connect to this VPN server by creating L2TP connection. However when I enter the values in L2TP connection in ZTE 670L router the status shows Disconnected.  Auth type is Auto, PAP & CHAP, all 3 give same Disconnected status.
I guess router page does not have provision for pre-shared key? See the screenshot. Is this the reason it shows Disconnected in Status and how does it actually work in this router?

A:
I have L2TP account on an Internet server. They have provided me Servername, Userid, Password, Preshared key.

Sounds like you actually have an L2TP-over-IPsec account, where the username and password are for L2TP while the preshared key is for IPsec (IKEv1) encryption.
L2TP/IPsec is a very common combination for VPNs (due to Windows having built-in support for it) but it's not the same as "plain" L2TP; your router won't be able to actually talk to the L2TP server unless it has established an IPsec association first.
I suspect that the L2TP support in your router is not meant to be used with external VPN services, but instead only for connecting to your own ISP (in the same way that many ISPs require PPPoE).


text:
Q: MATLAB - Failed to initialize GPU BLAS library I'm very new at Matlab. I'm running a function called inside a parfor loop (I have 4 CPUs / 4 Workers). In this function, I want to multiply two matrices named "M1" and "M2," using GPU in the following manner:
MyFunction()
    ...
    gpu_M1 = gpuArray(M1);
    ...
    for k = 1:v2
        ...
        gpu_M2T = gpuArray(M2');
        gpu_x = gpu_M1* gpu_M2T;
        x = gather(gpu_x);
        ...
    end
end % End of MyFunction()

% Part of the main program
...
parfor n = 1:v1
  MyFunction();
end
...

Based on the outcomes in the Command Window, it seems to work fine during the first four iteration this function is called. However, while executing the following one (5th), I get the message "Failed to initialize GPU BLAS library." Does any of you know what this problem could be? I would appreciate your help. I'm running this code in Matlab R2022b. These are some details of my graphic card:
graphic card

I read that perhaps the problem would be an out-of-memory problem, so after x = gather(gpu_x), I added the code "clear gpu_linesT," but it didn't work out. Indeed after doing that, I got an out-of-memory error. It seems that I created that error rather than fixing the previous one.


text:
Q: OpenCV VideoCapture::get(CV_CAP_PROP_POS_MSEC) returns 0 I'm trying to timestamp the frames when recording video using OpenCV 3.1.0. However, when using VideoCapture::get(CV_CAP_PROP_POS_MSEC) to get the millisecond timestamp of the last frame grabbed the value returned is always 0.
The code I'm using:
int fps = 10;

VideoCapture cap(0); // open the default camera

cap.set(CV_CAP_PROP_FPS, fps);
cap.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 1024);

if(!cap.isOpened())  // check if we succeeded
    return -1;

Mat testFrame;
cap >> testFrame;
cap >> testFrame;
cap >> testFrame;

Size outSize = Size(testFrame.cols, testFrame.rows);

VideoWriter writer("video.avi", CV_FOURCC('M','J','P','G'), fps, outSize, true);

for(; ;)
{
    Mat frame;
    cap >> frame; // get a new frame from camera

    long stamp = cap.get( CV_CAP_PROP_POS_MSEC); // THIS DOESN'T SEEM TO WORK

    std::cout << "Timestamp: " << stamp << std::endl;

    writer.write(frame);
}

As output I always get many lines like the following:
Timestamp: 0

Could you help me understand what I'm doing wrong?
Thanks :)

A: This bug has been fixed in a recent pull request. From the link:

There is a bug in cap_v4l.cpp file the causes this problem. The value of the timestamp is copied from a buffer at line 868, but the the data in the buffer in not valid because we have already called VIDIOC_QBUF ioctl at line 865. The solution is to flip the two lines of the code, so we read the timestamp before calling VIDIOC_QBUF ioctl.


text:
Q: Error When deploying Salesforce lightning / Aura components with Eclipse I am trying to deploy a Salesforce lightning coponent thorugh Eclipse from one dev org to another but I am receiving below errors.
I am able to succesfully install the components  through an unmanaged package but would like to konw if it is possible to deploy lightning components through Eclipse
Please see attached images for the errors.
INVALID_CROSS_REFERENCE_KEY ERROR
Eclipse unknown data type

A: For deploying aura components follow the steps below:
1) Open Package.xml in Ecllipse
2) Add following code:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
        <name>AuraDefinitionBundle</name>
    </types>
    <version>35.0</version>
</Package>

3) Refresh your project from server

Regards,
Ajay

A: I was able to deploy the complete aura folder to sandbox, i think you need to create a new project with aura components and its dependencies and try to deploy to the sandox.


text:
Q: Short story; Alien soldier uses an Earth soldier's body to train in I read this in an anthology in UK at least forty years ago.
An alien soldier is almost complete in his training and needs to have his final test, this is done by him taking over the body of an Earth soldier during combat. Then he'll be deemed fit to fight his Emperor's enemies.
On Earth a young American recruit is assigned to machine gun duties in a pill box, he's told how to call it in if he sees enemy activity, he asks about some names scratched into the concrete with tick marks beside them. The sergeant points to a tin bucket at the far end of the pillbox, he explains they keep score who can flip a cigarette butt from the observation stool to the bucket - he then leaves and the young soldier begins his watch.
After a couple hours he thinks he sees movement so he looks closely and it's a large number of enemy troops charging, he hastily radios and then goes to his gun, then he stiffens in shock as the alien mentally assumes command of his body.
After a couple of seconds adjusting to such unfamiliar eyes and limbs the alien mounts a spectacular defence, with careful placement of shot and zones of fire, then he gets badly wounded but continues until help arrives.
Back across the galaxy the alien triumphantly gets passed as a full warrior, back on Earth the sergeant shakes his head in admiration as they stretcher away his wounded man, then shakes it again when he sees the rookies name scratched into the wall with one tick mark beside it.
(Note: I posted this recently in here but then deleted because I'd got it hopelessly confused with an Asimov short about Kilroy!)


text:
Q: Using NEST to percolate I'm indexing my query as follows:
client.Index(new PercolatedQuery
{
    Id = "std_query",
    Query = new QueryContainer(new MatchQuery
    {
        Field = Infer.Field<LogEntryModel>(entry => entry.Message),
        Query = "just a text"
    })
}, d => d.Index(EsIndex));

client.Refresh(EsIndex);

Now, how do I use the percolator capabilities of ES to match an incoming document with this query? To say the NEST documentation is lacking in this area would be a huge understatement. I tried using client.Percolate call, but it's deprecated now and they advise to use the search api, but don't tell how to use it with percolator...
I'm using ES v5 and the same version of NEST lib.

A: There are plans to improve the documentation for 5.x once the GA release is out; I understand that documentation could be clearer in many places and any help in this area would be most appreciated :)
The documentation for the Percolate query is generated from the integration test for it. Pulling out all the pieces for an example here, using details from you other question. First, let's define the POCO models
public class LogEntryModel
{
    public string Message { get; set; }

    public DateTimeOffset Timestamp { get; set; }
}

public class PercolatedQuery
{
    public string Id { get; set; }

    public QueryContainer Query { get; set; }
}

We're going to fluently map all properties instead of using mapping attributes. The fluent mappings are the most powerful and can express all ways to map in Elasticsearch.
Now, create the connection settings and client to work with Elasticsearch.
var pool = new SingleNodeConnectionPool(new Uri($"http://localhost:9200"));
var logIndex = "log_entries";
var connectionSettings = new ConnectionSettings(pool)
    // infer mapping for logs
    .InferMappingFor<LogEntryModel>(m => m
        .IndexName(logIndex)
        .TypeName("log_entry")
    )
    // infer mapping for percolated queries
    .InferMappingFor<PercolatedQuery>(m => m
        .IndexName(logIndex)
        .TypeName("percolated_query")
    );

var client = new ElasticClient(connectionSettings);

We can specify the index name and type name to infer for our POCOs; that is, when NEST makes a request using LogEntryModel or PercolatedQuery as the generic type parameter in a request (e.g. the T in .Search<T>()), it will use the inferred index name and type name if they are no specified on the request.
Now, delete the index so that we can start from scratch
// delete the index if it already exists
if (client.IndexExists(logIndex).Exists)
    client.DeleteIndex(logIndex);

And create the index
client.CreateIndex(logIndex, c => c
    .Settings(s => s
        .NumberOfShards(1)
        .NumberOfReplicas(0)
    )
    .Mappings(m => m
        .Map<LogEntryModel>(mm => mm
            .AutoMap()
        )
        .Map<PercolatedQuery>(mm => mm
            .AutoMap()
            .Properties(p => p
                // map the query field as a percolator type
                .Percolator(pp => pp
                    .Name(n => n.Query)
                )
            )
        )
    )
);

The Query property on the PercolatedQuery is mapped as a percolator type. This is new in Elasticsearch 5.0. The mapping request looks like
{
  "settings": {
    "index.number_of_replicas": 0,
    "index.number_of_shards": 1
  },
  "mappings": {
    "log_entry": {
      "properties": {
        "message": {
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          },
          "type": "text"
        },
        "timestamp": {
          "type": "date"
        }
      }
    },
    "percolated_query": {
      "properties": {
        "id": {
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          },
          "type": "text"
        },
        "query": {
          "type": "percolator"
        }
      }
    }
  }
}

Now, we're ready to index the query
client.Index(new PercolatedQuery
{
    Id = "std_query",
    Query = new MatchQuery
    {
        Field = Infer.Field<LogEntryModel>(entry => entry.Message),
        Query = "just a text"
    }
}, d => d.Index(logIndex).Refresh(Refresh.WaitFor));

With the query indexed, Let's percolate a document
var logEntry = new LogEntryModel
{
    Timestamp = DateTimeOffset.UtcNow,
    Message = "some log message text"
};

// run percolator on the logEntry instance
var searchResponse = client.Search<PercolatedQuery>(s => s
    .Query(q => q
        .Percolate(p => p
            // field that contains the query
            .Field(f => f.Query)
            // details about the document to run the stored query against.
            // NOTE: This does not index the document, only runs percolation
            .DocumentType<LogEntryModel>()
            .Document(logEntry)
        )
    )
);

// outputs 1
Console.WriteLine(searchResponse.Documents.Count());

The percolated query with id "std_query" comes back in the searchResponse.Documents
{
  "took" : 117,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "log_entries",
        "_type" : "percolated_query",
        "_id" : "std_query",
        "_score" : 0.2876821,
        "_source" : {
          "id" : "std_query",
          "query" : {
            "match" : {
              "message" : {
                "query" : "just a text"
              }
            }
          }
        }
      }
    ]
  }
}

This is an example of percolating a document instance. Percolation can also be run against already indexed documents
var searchResponse = client.Search<PercolatedQuery>(s => s
    .Query(q => q
        .Percolate(p => p
            // field that contains the query
            .Field(f => f.Query)
            // percolate an already indexed log entry
            .DocumentType<LogEntryModel>()
            .Id("log entry id")
            .Index<LogEntryModel>()
            .Type<LogEntryModel>()
        )
    )
);


text:
Q: lightning:container - 404 not found lightning:container gives 404 error, but iframe loads fine :(
<lightning:container aura:id="Cont" src="{! $Resource.StaticResource1 + '/index.html'}" />

<iframe aura:id="Cont" src="{! $Resource.StaticResource1 + '/index.html'}" />

index.html
<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <title>Container</title>
</head>

<body>
  From ... Container.
</body>

</html>

Any suggestions, what I'm doing wrong.
Thanks
==>
It is so strange, when I create another static resource with the same index.html it works fine !!!!!!!

A: The "Lightning Container Component Isolation" section of the LockerService and Lightning Container Component: Securely Using Third-Party Libraries in Lightning Components suggests that lightning:container is the way to go though is not explicit about the LockerService blocking a raw iframe.
And the src attribute is listed for iframe in Locker Service API Viewer as being available...
Personally I'd just use the lightning:container.


text:
Q: TextEditingController vs OnChanged I am looking for a better explanation on the benefit of TextEditingController over OnChanged event for a TextField.
My understanding is that onChanged's setState notifies all widgets of the change in state variable value. This way any widget (e.g. Text) can simply use the state variable and it will be notified of its changes.
My false hopes were TextEditingController would make it even simpler that I won't even need a state variable. Something like below:
import "package:flutter/material.dart";

class TestForm extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TestFormState();
  }
}

class TestFormState extends State<TestForm> {
  //string myStateVariable = "";
  final ctrl = TextEditingController();

  @override
  Widget build(BuildContext context) {

    var tf = TextField(
      controller: ctrl,
    );

    var t = Text("Current value: " + ctrl.text);  // <<<<<<<<<<< false hope! doesnt work!

    var x = Column(children: <Widget>[tf,t],);

    return MaterialApp(home: Material(child: Scaffold(
      appBar: AppBar(title: Text("Test Form"),),
      body: x,
    )));
  }
}

Can anyone explain why TextEditingController or something similar cannot manage the state itself and notifies all consumers of change in state?
Thanks.

A: You are just not setting state synchronously that's all. What onChanged does is exactly possible with this approach:
class _TestFormState extends State<TestForm> {
  late TextEditingController controller;

  @override
  void initState() {
    controller = TextEditingController()
      ..addListener(() {
        setState(() {});
      });
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        Text('Current Value: ${controller.text}'),
        TextField(
          controller: controller,
        ),
      ],
    );
  }
}

As you see, we have listener that setting state every time state of the controller changes. This is exactly what onChanged does.
So, about benefits, you can achieve everything with both approach, it's a subjective way.
About benefits:
If you need to hold field values within Stream, onChanged is what you need. In other cases you may use controller.
Actually you won't need both in most of time in my opinion because TextFormField + Form within StatefulWidget is quite complete way to implement form pages. Checkout cookbook: https://flutter.dev/docs/cookbook/forms/validation

A: TextEditingController actually is managing his own state, that's why you can see the input on the screen once you change it.
You have 2 problems here, the first is that you are not adding any listener to the TextEditingController, you are just asking "give me the current value" only when you build the widget, not "give me the value any time it changes". To achieve this you need to add a listener to the text controller and it will be called every time that the value change.
Try this :
  @override
  void initState() {
    super.initState();
    // Start listening to changes.
    ctrl.addListener(_printValue);
  }

  _printValue() {
    print("Value: ${ctrl.text}");
  }

This will work because print doesn't need to render anything on the screen but if you change it to return a widget it will not work either. That is the second problem, as you pointed out, your parent widget is not been rebuild when the value change, in this case you cannot avoid the setState (or other way to tell flutter that needs to rebuild the widget) when the value change because you need to rebuild the widget to view the change.
Another thing that ill like to point out is that TextEditingController is much powerful and it can be used for more things that just add notifiers to changes. For example if you want a button on other part of the screen that clear the text on a TextField you will need a TextEditingController binded to that field.
Hope it helps!


text:
Q: Window manager view is not allowing to go back I am adding a view from XML to Window Manager view, Everything is working fine but when i want to go back to previous activity back button is not working even i have removed the added view from window manager inside onBackPressed.
manager = ((WindowManager) getApplicationContext().getSystemService(
            Context.WINDOW_SERVICE));

    localLayoutParams = getWindow().getAttributes();
    localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
    localLayoutParams.gravity = Gravity.TOP;
    localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
    localLayoutParams.flags = 0x80000000 | localLayoutParams.flags;
    localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    localLayoutParams.height =    WindowManager.LayoutParams.WRAP_CONTENT;
    localLayoutParams.format = PixelFormat.TRANSPARENT;

    localLayoutParams.screenBrightness = brightness / (float) 255;

    LayoutInflater inflater = getLayoutInflater();
    overlay = inflater.inflate(R.layout.activity_main, null);

    manager.addView(overlay, localLayoutParams);

And when i press the back button here is the code to remove the view
if(overlay!=null)
 manager.removeView(overlay);

Please help me out of this issue.


text:
Q: To classify a bike and a bicyclist separately or not? I'm planning to start a project about classification of objects in traffic. Currently I am putting together a custom dataset to train a network (YOLOv4 probably). Thinking ahead about labeling the dataset, I'm wondering whether I should separately label a bicyclist as a human and a bicycle, or not.
Looking at the COCO dataset, we can see that humans on bicycles or motorcycles are separately labeled as 'Person', and the vehicles as 'Bicycle' or 'Motorcycle'. Please see the following example: https://cocodataset.org/#explore?id=67208.
To improve the distinction between a bicycle and a motorcycle, I was planning to label the vehicle including the human, for the reason that the pose and the outfit may help with the classification. But since I will also be looking for pedestrians, I'm now afraid that the person on the bicycle will often be wrongly classified as a pedestrian.
Does anyone have experience with this or recommendations for me?
= Edit =
To avoid that a person walking around in a motorcycle suit would be classified as 'Motorcycle' instead of 'Pedestrian', I now label the person on a motorcycle separately. Whether a detection that is classified as a 'Person' is a pedestrian, bicyclist, or a motorcyclist, will be decided on in post-processing by checking whether another detection for a motorcycle or bicycle is near the detection of the person.


text:
Q: Calculating function on files from directory I wrote a code that calculate something. As I have many files, I am trying to rewrite the code, that it can read a files from a folder, calculate some function and give an output in another folder. I found some examples how I can make it, but something is wrong. As an output I did not received every file (ex. I have 5 input files in a folder, but I received only 4 files with results). What I am doing wrong? Here is my main part of the code:
int main()
{
int my_size = 100;
char katalogIn[512];
strcpy(katalogIn, "input");
char katalogOut[512];
strcpy(katalogOut, "output");

DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(katalogIn)) == NULL) {
    fprintf(stderr, "Cannot open directory: %s\n", katalogIn);
    return 1;
}

int fileCounter = 0;
char fileName[512];

    while ((entry = readdir(dp)) != NULL) {
       lstat(entry->d_name, &statbuf);
       fileCounter++;
       if (S_ISDIR(statbuf.st_mode)) {
    //printf("Done");
       } else {

     if (fileName != NULL)
     {
        FILE *fileData1;
            strcpy(fileName, katalogIn);
            strcat(fileName, "/");
            strcat(fileName, entry->d_name);
            fileData1 = fopen(fileName, "r");
            if (fileData1 == NULL) {
                printf("Cannot open the file\n");
                return -1;
            }

            char buffor[512];
    float *x = (float*)malloc(my_size * sizeof(float));
    float *y = (float*)malloc(my_size * sizeof(float));
    float *z = (float*)malloc(my_size * sizeof(float));
    if (x != NULL && y != NULL && z != NULL)
    {
        int i;
        fseek(fileData1, 0, 0);
        for (i = 0; i < my_size; i++)
        {
            if (fscanf(fileData1, "%f\t%f\t%f", x + i, y + i, z +i) != 3)

            {
                break;
            }
        }
        fclose(fileData1);

        FILE *fileOutput1;
            strcpy(fileName, katalogOut);
            strcat(fileName, "/");
            strcat(fileName, entry->d_name);
            //strcat(fileName,"out");
            fileOutput1 = fopen(fileName, "w");
            if (fileOutput1 == NULL) {
                printf("Cannot open the file\n");
                return -1;
            }

        for (i = 0; i < my_size; i++)
        {
            float convX, convY;
            int successCode = my_func(x[i], y[i], &convX, &convY);
            fprintf(fileOutput1,"%.2f\t%.2f\t%.2f\n", convX, convY,z[i]);

        }
        free(x);
        free(y);
        free(z);
        fclose(fileOutput1);
    }
      }

   }}

closedir(dp);
return (EXIT_SUCCESS);
}

A: In your readdir loop, the name of the "entry" (entry->d_name) is the relative name to the directory it's in. So if you have a file /input/foo then entry->d_name will be "foo" only.
You should really check what lstat returns. I'll bet it's -1 with errno set to ENOENT (which means statbuf is uninitialized and all members will have indeterminate values).
To get lstat to not fail, you either need to chdir into the directory, or you should have a temporary string where you concatenate the directory and file names. Something you do later in the code (though I would suggest using snprintf instead of three string function calls).

There are also a few other problems that looks weird. For example fileName is an array, which means it will never be NULL.
Also please read this discussion about casting the result of malloc. Not that you need to allocate dynamically, since you have a size fixed at time of compilation which means you could use arrays for x, y and z.


text:
Q: How to Edit XML value in cakePHP1.3? I have XML resource which provide this:
<container>
    <element id="first-el">
        <name>My element</name>
        <size>20</size>
    </element>
    <element>
        <name>Your element</name>
        <size>30</size>
    </element>
</container>

What i want to do is to change value of <size>, where id is "first-el", and change 20 to 50.
The resulting XML should look like this:
<container>
    <element id="first-el">
        <name>My element</name>
        <size>50</size>
    </element>
    <element>
        <name>Your element</name>
        <size>30</size>
    </element>
 </container>

I tried to use addChild() of XML Method in CakePHP, but is there a better way to do this?

A: I have no idea what sort of additional functionality CakePHP provides in regards to XML, but there already tools for this in plain old PHP:

*

*DOM Document

*Simple XML
Both let you manipulate existing XML data.

A: There is a class in CakePHP that will handle all of this for you. You can read the specifics here:
CakePHP 1.3:
http://book.cakephp.org/1.3/en/view/1485/Xml
CakePHP 2.0:
http://book.cakephp.org/2.0/en/core-utility-libraries/xml.html


text:
Q: How to add more data items than design view page height allows. I'm out of Design View vertical space I understand that I can never exceed the width of a report body, but I have more report items than a (Design View) page can hold and I don't know what to do.
To clarify, what is currently on the Design View page correctly becomes a longer display view, and becomes multiple printed pages. Just what I want.
The problem is that I've run out of vertical design canvas and I don't know how to fix that.

A: Now that we've identified the PBI-Desktop tag was erroneous, the problem domain is SSRS Report Builder/PBI Paginated Report Builder doesn't give you enough space to craft your report.
The right but wrong answer is to go into the Property menu of the Body and there you can change the Size of the report.

Here you can see me manually increasing the size of the report body but it's easier/more precise to work with the property window.

Why it's the wrong answer -> You're designing a paginated report - one designed to be pica perfect on your page. Now we're stuffing a 21.875 inch body of a report into an 8x11 page piece of paper. Viewing of it might be ok but when someone clicks print, what happens? Is it going to squish all of that into a single page? Will Page 1 of the report really span N pages? It's been too long since I've worked with SSRS to that level of precision and I really don't remember but do test early if printing is a crucial aspect of the report delivery.
Outdated PBI Desktop/Service answer in case someone else needs it
In Power BI Desktop, click in the background and under Visualizations go to the Format tab. Change the default page size to custom and I could create a 99999 pixel tall report but I doubt that's advisable


text:
Q: Understanding simple carousel transition code I'm new to jQuery in general and basically made this one slide transition, it has minimal and compact code:
$(function () {
    var str_next = $('.cara .item').eq(1);

    function slide(elem) {
        elem.addClass('next');

        $('.cara .item').each(function() {
            if ($(this).hasClass('active')) {
                console.log('does have it');
                $(this).removeClass('active');
            }
        });

        setTimeout(function () {
            elem.removeClass('next').addClass('active');
        }, 2000);
    }

    slide(str_next);
});

Fiddle here
If you have a close look at the jQuery the following lines of code are causing the one slide transition effect:
setTimeout(function(){
    elem.removeClass('next').addClass('active');
}, 2000);

Now for the transition effect to take place it is very important that the next class be attached to elem, but in the above code the next class is being removed from elem and there is still a transition, why?
For example if I were to change the above lines of code to as follows:
setTimeout(function(){
    elem.removeClass('next');
    setTimeout(function() {
        elem.addClass('active');
    }, 500);
}, 2000);

There would be no transition, so how come the below works:
setTimeout(function(){
    elem.removeClass('next').addClass('active');
}, 2000);

Why is it that inspite of removing next class the transition takes place?

A: The transition does not play because it relies on the positioning of the image.
Before the image slides into view its display property is set to none, making it invisible and its position is unchanged.
By adding next class the position of the item is set to left: 100%, this causes it to move to the right, effectively out of view.
When you now remove the next class and add the active class the image's display property is set to block, making it visible and by removing the next class the image returns to its original position (where you can see it after the animation).
Now if you remove the next class first the image would move to its original position while being invisible, that's why there's no animation.
So to answer your question: the next class provides a starting position for the movement animation, if the image is not in that starting position it doesn't have to move and so there is no animation.
Edit clarification: The transition always plays in the background, only because the active class is added it becomes visible. So even if you remove the next class before adding the active class the transition starts playing and becomes visible. The transition comes from the difference in position the next class causes, the visibility of the images comes from the active class, these are completely separate. So the transition always plays when removing the next class, it simply isn't always visible.


text:
Q: Are there any credible shared hosting services that are compatible with subsonic projects? I have a website project that was written with subsonic though medium trust hosting services like GoDaddy and AT&T don't support subsonic projects.
I was wondering if anyone knows of any hosting services that will work with subsonic. I am not as tech savvy so I am looking for a tech support heavy hosting service that will be able to walk me through the hosting (live person over the phone and not a chat box).

A: I used to use Subsonic 2.x with a website site with medium trust hosting (WebCentral in Australia) and didn't have any issues from a website point of view.
The database connection appeared to require the ability to read the sysobjects table which is not always standard.
Also we generated our SubSonic classes before deploying so they weren't created on the fly.
Not sure this is an answer but would be interested to know what errors you get when you try to deploy the site on GoDaddy or AT&T.


text:
Q: php resume capability or download in chunks PHP $_SERVER does not return HTTP_range key and without that key how can I perform a "resume download" or download in chunks?
   if (isset($_SERVER['HTTP_RANGE'])) {
    echo "find";
   } else{
    echo "not find";
   }

i can't get $_SERVER['HTTP_RANGE'] from server .......
There is no key HTTP_RANGE when i print $_SERVER
===================================================
<?php

    // get the file request, throw error if nothing supplied

    // hide notices
    @ini_set('error_reporting', E_ALL & ~ E_NOTICE);

    //- turn off compression on the server
    @apache_setenv('no-gzip', 1);
    @ini_set('zlib.output_compression', 'Off');

    if(!isset($_REQUEST['file']) || empty($_REQUEST['file']))
    {
        header("HTTP/1.0 400 Bad Request");
        exit;
    }

    // sanitize the file request, keep just the name and extension
    // also, replaces the file location with a preset one ('./myfiles/' in this example)
    $file_path  = $_REQUEST['file'];
    $path_parts = pathinfo($file_path);
    $file_name  = $path_parts['basename'];
    $file_ext   = $path_parts['extension'];
    $file_path  = './myfiles/' . $file_name;

    // allow a file to be streamed instead of sent as an attachment
    $is_attachment = isset($_REQUEST['stream']) ? false : true;

    // make sure the file exists
    if (is_file($file_path))
    {
        $file_size  = filesize($file_path);
        $file = @fopen($file_path,"rb");
        if ($file)
        {
            // set the headers, prevent caching
            header("Pragma: public");
            header("Expires: -1");
            header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
            header("Content-Disposition: attachment; filename=\"$file_name\"");

            // set appropriate headers for attachment or streamed file
            if ($is_attachment) {
                    header("Content-Disposition: attachment; filename=\"$file_name\"");
            }
            else {
                    header('Content-Disposition: inline;');
                    header('Content-Transfer-Encoding: binary');
            }

            // set the mime type based on extension, add yours if needed.
            $ctype_default = "application/octet-stream";
            $content_types = array(
                    "exe" => "application/octet-stream",
                    "zip" => "application/zip",
                    "mp3" => "audio/mpeg",
                    "mpg" => "video/mpeg",
                    "avi" => "video/x-msvideo",
            );
            $ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default;
            header("Content-Type: " . $ctype);

            //check if http_range is sent by browser (or download manager)
            if(isset($_SERVER['HTTP_RANGE']))
            {
                list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
                if ($size_unit == 'bytes')
                {
                    //multiple ranges could be specified at the same time, but for simplicity only serve the first range
                    //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
                    list($range, $extra_ranges) = explode(',', $range_orig, 2);
                }
                else
                {
                    $range = '';
                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
                    exit;
                }
            }
            else
            {
                $range = '';
            }

            //figure out download piece from range (if set)
            list($seek_start, $seek_end) = explode('-', $range, 2);

            //set start and end based on range (if set), else set defaults
            //also check for invalid ranges.
            $seek_end   = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)),($file_size - 1));
            $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);

            //Only send partial content header if downloading a piece of the file (IE workaround)
            if ($seek_start > 0 || $seek_end < ($file_size - 1))
            {
                header('HTTP/1.1 206 Partial Content');
                header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$file_size);
                header('Content-Length: '.($seek_end - $seek_start + 1));
            }
            else
              header("Content-Length: $file_size");

            header('Accept-Ranges: bytes');

            set_time_limit(0);
            fseek($file, $seek_start);

            while(!feof($file))
            {
                print(@fread($file, 1024*8));
                ob_flush();
                flush();
                if (connection_status()!=0)
                {
                    @fclose($file);
                    exit;
                }
            }

            // file save was a success
            @fclose($file);
            exit;
        }
        else
        {
            // file couldn't be opened
            header("HTTP/1.0 500 Internal Server Error");
            exit;
        }
    }
    else
    {
        // file does not exist
        header("HTTP/1.0 404 Not Found");
        exit;
    }
    ?>


text:
Q: How to switch to different python function on button clicks with jQuery? here is my <form> in index.html

      <form action="{{ url_for('predict1')}}" method="post">

<textarea name="message" id="newitem" rows="3" cols="150" class="form-control"
              required="required"></textarea>

        <input type="submit" class="button" value="Generate">
      </form>

{{ prediction_text }}

from here I am calling a predict1 function which gives the output in prediction_text variable.
This is the predict function in app.py
@app.route('/predict',methods=['post'])
def predict1():
   ''' some work '''
   return render_template("index.html",prediction_text = output_var)

def predict2():
   ''' some work '''
   return render_template("index.html",prediction_text = output_var)

here is the jQuery in index.html.
$('textarea#newitem').keyup(function (e) {
    var code = e.which;
    if (code == 16) {     // shift 16 to call predict1()
      e.preventDefault();
      $('h3#predh3').append(e.target.value);
    }
  });
  $('textarea#newitem').keyup(function (e) {
    var code = e.which;
    if (code == 13) {     //Enter 13 for call predict2()
      e.preventDefault();
      $('h3#predh3').append(e.target.value);
    }
});

jQuery bounded by


text:
Q: i am new to JSF.

i have a problem with  tag my .jsp page is like this:
<h:form id="form1">
                <t:inputHidden id="primaryKey"
                    value="#{EditConfigurationBean.primaryKey}" forceId="true" />
                <t:inputHidden id="beanName"
                    value="#{EditConfigurationBean.beanName}" forceId="true" />
                <t:dataTable id="datatable" value="#{EditConfigurationBean.config}"  rowIndexVar="rowIndex" var="rowvar"
                    rowClasses="standardTable_Row1,standardTable_Row2"
                    columnClasses="standardTable_Column1,standardTable_Column2,standardTable_Column3">
                        <h:column>
                            <f:facet name="header">
                                <h:panelGroup>
                                    <f:verbatim>
                                        <object width="0px" height="0px"></object>
                                    </f:verbatim>
                                    <h:outputText
                                        value="Entry Name" />
                                </h:panelGroup>
                            </f:facet>
                            <h:outputLabel value="#{rowvar.bean.name}"></h:outputLabel>
                        </h:column>
                        <t:column>
                            <f:facet name="header">
                                <h:panelGroup>
                                    <f:verbatim>
                                        <object width="0px" height="0px"></object>
                                    </f:verbatim>
                                    <h:outputText
                                        value="Entry Value" />
                                </h:panelGroup>
                            </f:facet>
                            <h:inputText styleClass="inputText" value="#{rowvar.value}"></h:inputText>
                        </t:column>
                    </t:dataTable>
                        <t:htmlTag value="div" styleClass="commandBar">

        <h:commandButton onmouseover="over(this)" onmouseout="out(this)" action="#{EditConfigurationBean.back}" id="navigation" immediate="true" value="back" styleClass="commandButton" />

        <h:commandButton onmouseover="over(this)" onmouseout="out(this)" action="#{EditConfigurationBean.update}" value="Update" styleClass="commandButton" />

    </t:htmlTag>
            </h:form>

and my backbean code is:
public class ConfigurationEditBean{
    public String getInit(){
        try {
            config = loadConfig();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (config != null)
            this.entriesCount =this.config.size();
        return "";
    }
    private int primaryKey;
    private java.lang.String beanName;
    private int entriesCount;
    private List<ConfigurationFullEntry> config;

    public int getEntriesCount() {
        return entriesCount;
    }

    public void setEntriesCount(int entriesCount) {
        this.entriesCount = entriesCount;
    }

    public void setConfig(List<ConfigurationFullEntry> config) {
        this.config = config;
    }

    public int getPrimaryKey() {
        return primaryKey;
    }

    public void setPrimaryKey(int primaryKey) {
        this.primaryKey = primaryKey;
    }

    public java.lang.String getBeanName() {
        return beanName;
    }

    public void setBeanName(java.lang.String beanName) {
        this.beanName = beanName;
    }
    private List<ConfigurationFullEntry> loadConfig() throws Exception{
        List<ConfigurationFullEntry> entriesList = new ArrayList<ConfigurationFullEntry>();
            //do load from DB
        return entriesList;
    }
    public List<ConfigurationFullEntry> getConfig() {
        return config;
    }
    public String update(){
        return "";
    }
    public String back(){
        return "";
    }
}

the problem is that page display correctly but when i am change value of one
tags and submit the form, corresponding setXXX of backbean is not called.
also when i have tried an inputtext tag outside of

wha's wrong about my codes?
thanks in advance

Update: this is my generated HTML no nested form exist within it.:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<base href="http://localhost:7001"><title>My JSF 'ConfigurationEditor.jsp' starting page</title><form id="j_id_id2" name="j_id_id2" method="post" action="/HealthMonitorConsole/ConfigurationEditor.jsf" enctype="application/x-www-form-urlencoded"><input type="hidden" id="primaryKey" name="primaryKey" value="0"><input type="hidden" id="beanName" name="beanName" value="com.pardis.healthMonitor.dm.service.ServiceBean">

Name	Value

Server	<input id="j_id_id2:j_id_id5:0:j_id_id13" name="j_id_id2:j_id_id5:0:j_id_id13" type="text" value="">

arash	<input id="j_id_id2:j_id_id5:1:j_id_id13" name="j_id_id2:j_id_id5:1:j_id_id13" type="text" value="">

<input id="j_id_id2:j_id_id14" name="j_id_id2:j_id_id14" type="submit" value="Save" onclick="if(typeof window.getScrolling!='undefined'){oamSetHiddenInput('j_id_id2','autoScroll',getScrolling());}"> <input type="hidden" name="autoScroll"> <input type="hidden" name="j_id_id2_SUBMIT" value="1"><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="8EgC7hvJoXWgMHaUZxk5rx66APlnNueyP32ajDxbvc/i5akMf2jX5SQ5BLInRDoWgWvcMUADuXlYwCWVxYrNWghZBdlolM+1zLfQTh4aUm4="></form>

i am writing every thing like tutorial examples but it does not work!

A: You need to ensure that exactly the same datamodel is preserved during the apply request values phase of the form submit as it was during the render response phase of the initial page display. A normal place is to do the preloading is the constructor of the backing bean.
public class Bean {
    private List<Item> items;

    public Bean() {
        items = itemDAO.list();
    }

    // ...
}

An alternative is to put the bean in the session scope, but this has more impact on user experience.
Since you're using Tomahawk, you can also just set the preserveDataModel attribute of the t:dataTable to true like so:
<t:dataTable preserveDataModel="true">

This will store the datamodel in the view's component tree (which in turn is stored in the session scope) so that exactly the same datamodel is available in the subsequent request.
See also:

*

*Using Datatables


text:
Q: Drupal: File upload required? For some reason, my form breaks when I try to make a file upload required. Here is the code for it:
$form_id = "upload_form";

$form[$form_id] = array (
    '#type' => 'fieldset',
    '#description' => t('This is a utility to import nodes from a Comma Separated Value file. To begin, pick a node type, and upload a CSV.'),
);

$form[$form_id]['type'] = array(
    '#title' => t('Enter node type'),
    '#type' => 'textfield',
//      '#autocomplete_path' => '', TODO: autocomplete for node types
    '#required' => TRUE,
    '#description' => t('This node type should already exist. If it doesn\'t, create it first.'),
);

$form[$form_id]['upload'] = array(
    '#type' => 'file',
    '#title' => t('Upload CSV file'),
//      '#size' => 40,
    '#description' => t('This will not work for a non-CSV file.'),
//      '#required' => TRUE, TODO: breaks it. why?
);

$form[$form_id]['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);

$form['#attributes'] = array('enctype' => 'multipart/form-data');

On a Drupal support site, someone says that it's impossible to make file uploads required. Is this true?

A: This is my workaround to make file field required:
<?
    // A piece of form that defines the file field
    $form['attachment'] = array(
        '#type' => 'file',
        '#title' => t('Title'),
        //'#required' => TRUE,  // check this manually
    );

    // Form validation hook
    function yourformname_validate($form, &$form_state) {
        // Validate file
        $validators = array(
            'file_validate_extensions' => array('doc txt pdf'), // does not work for user 1
            'file_validate_size' => array(1000000, 0),
        );
        $file = file_save_upload('attachment', $validators, file_directory_path());
        if ($file) {
             $form_state['values']['attachment'] = $file; // drupal file object
        }
        else{
             form_set_error('attachment', "File is required");
        }
    }
?>

A: I'm not a Drupal expert but you could check if the $_FILES variable exists, no?


text:
Q: Fixing ECONNREFUSED without turning off firewall? I am following a tutorial on YouTube for creating a connection to my MySQL DB using createPool(). This is the code I wrote, following the video tutorial:
import * as express from 'express';
import * as morgan from 'morgan';
import * as path from 'path';
import routes from './routes';

const app = express();

app.use(morgan('dev'));
app.use(express.static('public'));
app.use(express.json());
app.use(routes);
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'));
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server listening on port: ${port}`));

// TEST
import * as mysql from 'mysql';

const pool = mysql.createPool({
    host: 'localhost',
    user: 'todos_app',
    password: 'todos_app',
    database: 'todos_app'
});

pool.query('DESCRIBE users', (err, results) => {
    if (err) {
        console.log(err);
    } else {
        console.log(results);
    }
});

However, instead of getting the results seen in the video, I keep getting this error message:
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true

One of the solutions said to turn off my firewall, but that doesn't seem like a great solution to me. Especially since I want to create a nodejs backend for a web app that I'm creating.
Any suggestions? Thanks in advance!


text:
Q: How to double the AES keysize in keepass? keepass is open source on github right? Is there any way to "append" its existing AES256, double the key size, make the program support AES512? What are ways to achieve that result
Thanks

A: AES does only supports keysizes of 128, 192 and 256 bits. See Wikipedia
Changing an AES implementation to use 512bit keys would require some experience in cryptography.
Considering that the best attacks on AES are only slightly better than brute-force (and are not real-world feasible) there is no reason to use larger keys. Bruteforcing 256 bits is not possible in the lifetime of the human race.

A: It should be possible to implement an AES-style encryption algorithm using 512 bits in theory. However, it is significantly more complicated than appending 2 AES256 keys onto each other. For more details check out this post and linked paper on the Cryptography Stack Exchange.
On Keepass in particular, the source code is available here. However, it appears to be implemented in c++, not python, so you may wish to change the tag on your question. I'm not familiar with the code base so I'm not sure which file you should start with.


text:
Q: how to find the Min value among multiple col i have in my DB 3 col and i want to find a single value among all of them as explaind here: table name:MyTable
-----------------------------
--id-- col1-- col2-- col3-
-----------------------------
   1     200    300     400
   2     100    150     300
   3     800    102     20
   4     80     80       0

i want the result out of col1 col2 col3 to be = 0 , which is the min value among them.
is it possible !!!!
my try:
select Min(col1, col2 , col3) as Tablemin
from MyTable

A: ANSI SQL:
select min(col)
from
(
    select col1 [col] from MyTable
    union all
    select col2 from MyTable
    union all
    select col3 from MyTable
)t

A: If it is MySQL or Oracle, there is LEAST() function:
SELECT LEAST(MIN(col1), MIN(col2), MIN(col3))
       AS MinOfAllColumns
FROM MyTable

Then, there is the CASE statement which can be used in most RDBMSs:
SELECT CASE WHEN MIN(col1) <= MIN(col2) AND MIN(col1) <= MIN(col3)
                THEN MIN(col1)
            WHEN MIN(col2) <= MIN(col3)
                THEN MIN(col2)
                ELSE MIN(col3)
       END
       AS MinOfAllColumns
FROM MyTable

This can also work but it's hard to get other fields with the UNION approach:
SELECT MIN(col) AS MinOfAllColumns
FROM
  ( SELECT MIN(col1) AS col
    FROM MyTable
  UNION
    SELECT MIN(col2)
    FROM MyTable
  UNION
    SELECT MIN(col3)
    FROM MyTable
  ) AS tmp

A: Simple way to display min is:
string val = textBox2.Text;
DataSet ds;
con.Open();
string str = "SELECT * FROM Add_Rooms WHERE Price >= @price";
cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("@price", val);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, "Add_Rooms");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Add_Rooms";
con.Close();

A: In SQLITE the answer is as simple as:
SELECT MIN(MIN(col1), MIN(col2), MIN(col3)) FROM MyTable;


text:
Q: error "Class was not found by locator" when running tests My tests stopped working as soon as I created interface class and implemented it in my User class. Tests throw this error:
Class app\models\MyInterface was not found by locator

I figured out that Go\ParserReflection\ReflectionEngine calls interface_exists($fullClassName, false) and this returns false.
Any idea how to fix that?
EDIT
I added a functional tests and now it cannot find my BaseController class which i use to extend from.
Class app\controllers\BaseController was not found by locator

Controllers are not even in my $kernel->init(['includePaths' => ...]) so I think it should be ignored by goaop?
Any input will be appreciated.

A: I've fixed this using this answer.
You also could take a look this issue on Github.


text:
Q: Mediawiki: Invalid Login Token I'm trying to login via the api but allways get a "badtoken" error ("Invalid token").
I've followed the complete guide on the Mediawiki/Api-Help and do exactly what they suggest.

*

*I get the login-token:

*I do the POST request for the clientlogin.

Here is my code:
$wiki = 'example.de/wiki/';
$api = $wiki.'api.php?';
$retry = false;
$wpName = 'someone'
$wpPassword = 'supersave';

$json_a = (file_get_contents($wiki.'api.php?action=query&meta=tokens&type=login&format=json');
$json_b = json_decode($json_a,true);
$token = $json_b['query']['tokens']['logintoken'];
echo("\nToken: ".$token."\n");

$data = array(
        'action'               => 'clientlogin',
        'loginreturnurl'       => $wiki,
        'logintoken'           => $token,
        'username'             => $wpName,
        'password'             => $wpPassword,
        'rememberMe'           => 1);

$ch = curl_init($api);
$postString = http_build_query($data, '', '&');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Get the response
$response = curl_exec($ch);
curl_close($ch);

Does anyone knows what to do to perform the login?


text:
Q: Can the twin-prime conjecture be related to the growth of $\phi_2(n)=n \prod\limits_{p>2\,\land\,p|n}\left(1-\frac{2}{p}\right)$? This question is based on this Math StackExchange question by user buja and my related Math StackExchange question which was asked about a month ago and is still unanswered.

I believe
$$\phi_2(n)=n \prod\limits_{p>2\,\land\,p|n}\left(1-\frac{2}{p}\right)\tag{1}$$
is related to the twin-primes analogous to the way Euler's totient function
$$\phi(n)=n \prod\limits_{p|n}\left(1-\frac{1}{p}\right)\tag{2}$$
is related to the primes.

Question: Noting that the Euler totient function $\phi(n)$ defined in formula (2) above is related to the prime number theorem for arithmetic progressions and the Riemann hypothesis, I'm wondering if the twin-prime conjecture can be related to the growth of $\phi_2(n)$ defined in formula (1) above.

The remainder of this question clarifies the analogy I referred to previous to my question above.

The number of elements left after removing all primes up to $p_k$ and their multiples from the set $\left\{1,2,3,...p_k\#\right\}$ where $p_k\#=\prod\limits_{i=1}^k p_i$ is the primorial is given by
$$E_k=p_k\#\ \prod\limits_{i=1}^k \left(1-\frac{1}{p_i}\right)=\prod\limits_{i=1}^k \left(p_i-1\right)\tag{3}$$
which can be written in terms of the more general Euler totient function
$$\phi(n)=n \prod\limits_{p|n}\left(1-\frac{1}{p}\right)\tag{4}$$
as
$$E_k=\phi\left(p_k\#\right).\tag{5}$$

I believe the number of elements left after removing all multiples of primes up to $p_k$ and their associates (defined as pairs of numbers of the form $6 n\pm 1$) from the set $\left\{1,2,3,...p_k\#\right\}$ is given by
$$N_k=p_k\#\ \prod\limits_{i=2}^k \left(1-\frac{2}{p_i}\right)=2 \prod\limits_{i=2}^k \left(p_i-2\right)\tag{6}$$
which can be written in terms of the more general function
$$\phi_2(n)=n \prod\limits_{p>2\,\land\,p|n}\left(1-\frac{2}{p}\right)\tag{7}$$
as
$$N_k=\phi_2\left(p_k\#\right).\tag{8}$$

I believe $\phi_2(n)$ is related to $\phi(n)$ as follows
$$\phi_2(n)=\sum\limits_{d|n} (-1)^{d-1}\ \mu(rad(d))\ \phi\left(\frac{n}{d}\right)\tag{9}$$
where $\mu(n)$ is the Möbius function and $rad(n)$ is the radical of an integer.

Note that $\mu(rad(n))=(-1)^{\nu(n)}$ where $\nu(n)$ is the number of distinct primes dividing $n$ (see OEIS entry A001221), so formula (9) above can also be evaluated as follows.
$$\phi_2(n)=\sum\limits_{d|n} (-1)^{d-1}\ (-1)^{\nu(d)}\ \phi\left(\frac{n}{d}\right)\tag{10}$$

My related question on Math StackExchange provides additional information which perhaps provides a bit more insight.

A: This approach to trying to understand twin primes dates back at least to the 1950s. Sandor and Crstici's "Handbook of Number Theory II" mentions on page 289 in this context papers by V. A Golubev on this function, with references. In particular, he defined $\phi_2(n)$ as your function when $n$. The Handbook gives a slightly different definition for when $n$ is even, but I think there's a typo in their definition, and I can't say for certain what the issue is. Unfortunately, it looks like Golubev's papers are in Russian, so tracking them down and seeing exactly what is in them may be difficult. But this does suggest that the idea has at least been tried.
Note also that there's a closely related related function $S_k(n)$, as the number of sets of consecutive positive integers which are less than or equal to $n$, and all relatively prime to $n$. This is the Schemmel totient function. For $k=2$, it is essentially your function with $$S_2(n) = n\prod_{p|n} \left(1-\frac{2}{p}\right).$$ The Schemmel totient is of interest for reasons which are not necessarily connected with anything involving twin primes.


text:
Q: Facebook cURL posting as me? Create facebook app
Using a cURL to post a message from an App but it's appearing to be posted from me? How can I can it to post from the app, here's my cURL
    $attachment =  array(
    'access_token' => $token,
    'message' => '$message',
    'name' => '$name',
    'link' => '$link',
    'description' => '$description',
    'picture'=> '$picture',
    'actions' => json_encode(array('name' => '$name2','link' => '$link2'))
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://graph.facebook.com/'.$pId.'/feed');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);

The post works, but it just appears as if I posted it and not the App, suggestions?!

A: Here is the code it works for me
$file = 'image.jpg';
$args = array(
   'message' => 'Photo from application',
    'access_token'=>urlencode('Your Access token'),
);
$args[basename($file)] = '@'.realpath($file);

$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$result = curl_exec($ch);
curl_close ($ch);

May be it helps you.


text:
Q: What do I need to add to my dailymotion embed code to make video play on iOS? The video plays fine on my computer, but I want to make it play on devices like iPhones and such. I'm an absolute beginner at all this and appreciate all the help I can get. Here's the code as it exists on my site, please just tell me what to add or change. Thank you!

A: There are many different player parameters in the url of the video in your iframe, do you truly need all of them? You will find the documentation at https://developer.dailymotion.com/player. We'll do a quick review here:

*

*api=postMessage : enables the Player API => only needed if you use the player API, so you can probably remove it

*id=player: ID of the player unique to the page to be passed back with all API messages. => only needed if you use the player API, so you can probably remove it

*syndication=lr:167083 : this is used if you have a syndication key, in case you are a partner and you want to track your generated revenues. If this is not your own syndication key, I suggest you remove this parameter!

*autoplay=1 : will autoplay the video. This parameter may not work on some mobile OS versions as most mobile devices prevent the video from auto playing to save user's bandwidth.

*controls=0 : the video controls will not be displayed

*html=1 : this is a testing parameter that should not be used for production purposes

*chromeless=1 : we recommend you to remove this parameter as it removes all the player UI, so you user won't be able to interact with the video (play it, pause it, etc)

Hence we suggest you remove all the cited parameters that will not be useful for you, and use the following iframe instead:

Then, you video will play fine on mobile. What happened is that with the combination of chromeless=0 , autoplay=0 and controls=0 , your videos could not start automatically on mobile and you had hidden the controls for the user to start it. Hence you only had a black rectangle instead of the player.
With the code I mentioned, the video will play muted, without the dailymotion logo, without the sharing on social networks button, etc. You can changed all this by removing the remaining player parameters.


text:
Q: Entity Framework 4.3.1 always run all migrations on Update-Database I have created an initial migration with Add-Migration. When I run Update-Database on an empty DB it creates all tables, including adding an entry in the __MigrationHistory table.
Now I run Update-Database again just to test, and instead of "No changes detected" I get this:
PM> Update-Database -Verbose -Project testProject.Web
Using StartUp project 'testProject.Web'.
Target database is: 'testProject_dbo' (DataSource: localhost, Provider: Devart.Data.MySql, Origin: Explicit).
Applying explicit migrations: [201203151243164_Start].
Applying explicit migration: 201203151243164_Start.
CREATE TABLE attachments (
 ...table data...
)
Table 'attachments' already exists
Table 'attachments' already exists

It seems like the update is unaware of the current DB state. The only solution is to delete all tables and update. That works also if I add more migrations.
As you see, I am using a different database provider than usual (Devart.Data.Mysql), but I'm not sure if the problem is there. Maybe I'm missing something trivial?

A: The problem was resolved after communicating with DevArt. I never called the IgnoreSchemaName workaround in the Configuration class that was generated when running Enable-Migrations. To summarize, this is the class that made it work finally:
internal sealed class Configuration : DbMigrationsConfiguration<YourDbContext>
{
    public Configuration()
    {
        // Because the Package Manager Console (NuGet) instantiates YourDbContext with the empty constructor,
        // a custom connection must be specified. Based on http://www.devart.com/blogs/dotconnect/?p=5603
        // Note that the MySqlProviderFactory must also be present in Web.config or App.config in the *startup project*
        // for this to work! Configuration example:

        /*
          <system.data>
            <DbProviderFactories>
              <clear />
              <remove invariant="Devart.Data.MySql" />
              <add name="dotConnect for MySQL" invariant="Devart.Data.MySql" description="Devart dotConnect for MySQL" type="Devart.Data.MySql.MySqlProviderFactory, Devart.Data.MySql, Version=6.30.196.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
            </DbProviderFactories>
          </system.data>
        */

        // Apply the IgnoreSchemaName workaround
        MySqlEntityProviderConfig.Instance.Workarounds.IgnoreSchemaName = true;

        // Create a custom connection to specify the database and set a SQL generator for MySql.
        var connectionInfo = MySqlConnectionInfo.CreateConnection("<Your ConnectionString>");

        TargetDatabase = connectionInfo;
        SetSqlGenerator(connectionInfo.GetInvariantName(), new MySqlEntityMigrationSqlGenerator());

        // Enable automatic migrations if you like
        AutomaticMigrationsEnabled = false;

        // There is some problem with referencing EntityFramework 4.3.1.0 for me, so another fix that needs
        // to be applied in Web.config is this:

        /*
          <runtime>
            <assemblyBinding>
              <!-- This redirection is needed for EntityFramework Migrations through the Package Manager Console (NuGet) -->
              <dependentAssembly>
                <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
                <bindingRedirect oldVersion="4.3.0.0" newVersion="4.3.1.0" />
              </dependentAssembly>
            </assemblyBinding>
          </runtime>
        */

        // After these Web.config additions, running migrations in Package Manager Console should be as easy as:
        // Update-Database -Verbose -ProjectName Your.MigrationsProject

        // Creating new migrations:
        // Add-Migration -Name MigrationDescription -ProjectName Your.MigrationsProject
    }
}

After that I emptied the database one more time to generate a correct migration history entry, and everything was fine. DevArt gives more details about the configuration.

A: I had the same odd behaviour, but in my case it turned out to be much simpler: a code merge had reset my Startup Project to the default, which was not the project that contained the migrations.
I didn't notice until I tried the -Verbose flag, which explicitly laid out that my Startup project was not the same as the NuGet project configured in Package Manager.
Worth the sanity check!


text:
Q: How do I send multiple photos from my iPhone camera roll in a single email? I'm sure I'm missing something obvious, but:

*

*From the camera app, I can select a photo, and then hit the send button to create an email with that photo in it.

*From mail, I can't find any way to add an enclosure without having started in the app that owns it.

I want to send multiple photos in a single email.

A: since software update 3.0 you can select multiple photos copy them and paste it as email body, in iOS you can SHARE it as email.

A: [I posted this answer to address a followup question that appears to have been subsequently deleted. I will leave my answer up as it does add a more complete details than the prior answer, which was correct albeit terse.]
You can mail multiple photos, but not an unlimited number. I assume to limit the overall email message size, as there could be limits on some mail gateways.
Open Photos app, select "Camera Roll" (or other album) from your albums. Touch the "Edit" button, and the screen heading should change to "Select Items." You can then select multiple photos, then touch "share" and select "Mail". If you don't see "Mail" as one of the options, then you have selected too many photos to attach to a single message. Try just two to see what it should look like. On my phone just now I was able to choose 5 and still have Mail as an option, but if I chose 6, then Mail was not an option.

A:
From mail, I can't find any way to add an enclosure without having
  started in the app that owns it.

You can now do this in iOS 6. In a new mail message, tap and hold in the message body, then tap the right arrow in the overlay and tap "Insert Photo or Video."


text:
Q: Recurse through directories and log files by file type in python I want to investigate a set of directories and get the following info

*

*No of files by filetype

*List of files by filetype with full path

*1&2 per subdirectory directory
I have the following code. The ext list generator is fine. I am stuck on how to assign the name of the list and counter for each extension. We don't know what these will be or how many there are. Not sure what other issues may arise after this.
import os, sys, datetime

top = os.getcwd() # change to a specific path if required.
RootOutput = top
SourceDIR = top
outDIR = top+"\\workingFiles" # directory where output is written to. Includes temp files
# END setting base paths
# NOTHING BELOW should need editing.
List =[]
extList=[]

os.chdir(top)

for root, dirs, files in os.walk(SourceDIR, topdown=False):
    for fl in files:
      currentFile=os.path.join(root, fl)
      ext=fl[fl.rfind('.'):]
      if ext not in extList:
        extList.append(ext)
      List.append(currentFile)

print extList

for ext in extList:
    ext+"Counter"=0
    ext+"FileList"=[]

for fl in List:
    ext=fl[fl.rfind('.'):]
    ext+"Counter"+=1
    ext+"FileList".append(fl)

for ext in extList:
    print ext
    print ext+"Counter"
    print ext+"FileList"

CODE updated as per answer. Issue with txt file as it only creates one text file.
# iterate over dictionary keys
for elem in ext_dict.keys():
    print elem
    print ext_dict[elem]["Counter"]
    print ext_dict[elem]["FileList"]
    log = open(elem+'_Log.txt', 'a')
    Num=0
    for fl in ext_dict[elem]["FileList"]:
        Num+=1
        log.write(str(Num)+","+str(fl)+"\n")
    log.close()

The final script for anyone to use follows.
#-------------------------------------------------------------------------------
# Name:    File_Review
# Purpose: Review of all files in directory/subdirectories with report on file type and size
#
# Author:      georgec
#
# Created:     25/01/2013
# Copyright:   (c) ATGIS 2013
# Licence:     Creative Commons 3.0 - BY
#-------------------------------------------------------------------------------

import os, sys, datetime

top = os.getcwd() # change to a specific path if required.
RootOutput = top
SourceDIR = top
SourceDIR = r'P:\2013'
outDIR = top # directory where output is written to. Includes temp files
finalDIR = top+"\\final" # folder for final data only
DirLimiterList=['']

# END setting base paths
# NOTHING BELOW should need editing.

os.chdir(top)

def InvestigateFiles(SourceDIR,outDIR,DirLimiter):
    List =[]
    extList=[]
    dirList=[]
    dirCount=0
    for root, dirs, files in os.walk(SourceDIR, topdown=False):
        for fl in files:
            currentFile=os.path.join(root, fl)
            ext=fl[fl.rfind('.')+1:]
            if ext!='':
                if DirLimiter in currentFile:
                    List.append(currentFile)
                    directory1=os.path.basename(os.path.normpath(currentFile[:currentFile.rfind(DirLimiter)]))
                    directory2=(currentFile[len(SourceDIR):currentFile.rfind('\\'+directory1+DirLimiter)])
                    directory=directory2+'\\'+directory1
                    if directory not in dirList:
                        dirCount+=1
                        dirList.append(directory)

            if ext not in extList:
              extList.append(ext)

    print extList

    ext_dict = {}

    # Create the dictionary
    for ext in extList:
        ext_dict[ext] = {}
        ext_dict[ext]["Counter"] = 0
        ext_dict[ext]["FileList"] = []

    #populate the dictionary
    for fl in List:
        if ext_dict.has_key(fl[fl.rfind('.')+1:]):
            ext = fl[fl.rfind('.')+1:]
            ext_dict[ext]["Counter"] = ext_dict[ext]["Counter"] + 1
            ext_dict[ext]["FileList"].append(fl)

    # iterate over dictionary keys
    for elem in ext_dict.keys():
        uniqueDirList=[]
        print elem
        print ext_dict[elem]["Counter"]
        count= ext_dict[elem]["Counter"]
        print ext_dict[elem]["FileList"]
        log = open(elem+'_'+DirLimiter[DirLimiter.find('\\')+1:DirLimiter.rfind('\\')]+'_Log.txt', 'a')
        Num=0
        for fl in ext_dict[elem]["FileList"]:
            Num+=1
            log.write(str(Num)+";"+str(fl)+";"+str(os.path.getsize(fl))+"\n")
##            finaldir=fl[fl.rfind(DirLimiter):fl.rfind('\\')]
##            directory2=fl[fl.rfind('\\Input\\')+6:fl.rfind('\\')]
##            uniqueDir=directory2+finaldir
##            if uniqueDir not in uniqueDirList:
##             uniqueDirList.append(uniqueDir)
##             log.write(str(Num)+";"+str(fl)+";"+str(os.path.getsize(fl))+";"+str(uniqueDir)+'\n')
##             log.write(finaldir+"\n"+directory2+"\n"+uniqueDir+"\n"+"\n")
##            else:
##             log.write(str(Num)+";"+str(fl)+";"+str(os.path.getsize(fl))+";\n")
##        log.write('Directories: '+str(count)+'\n Unique Directories: '+str(len(uniqueDirList)))
        log.close()

for DirLimiter in DirLimiterList:
 InvestigateFiles(SourceDIR,outDIR,DirLimiter)

A: you should use a dictionary for storing the data
ext_dict = {}

# Create the dictionary
for ext in extList:
    ext_dict[ext] = {}
    ext_dict[ext]["Counter"] = 0
    ext_dict[ext]["FileList"] = []

#populate the dictionary
for fl in List:
    if ext_dict.has_key(f1[f1.rfind('.'):]):
        ext = f1[f1.rfind('.'):]
        ext_dict[ext]["Counter"] = ext_dict[ext]["Counter"] + 1
        ext_dict[ext]["FileList"].append(fl)

# iterate over dictionary keys
for elem in ext_dict.keys():
    print elem
    print ext_dict[elem]["counter"]
    print ext_dict[elem]["FileList"]